+ {/* View Mode Toggle + SJF */}
+
+
setViewMode('list')}
@@ -1175,6 +1175,22 @@ export function QueuePage() {
+
{
+ const newValue = !(settings?.queue_shortest_first ?? false);
+ sjfMutation.mutate(newValue);
+ }}
+ className={`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${
+ settings?.queue_shortest_first
+ ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
+ : 'bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
+ }`}
+ title={t('queue.sjf.tooltip', 'Shortest Job First — scheduler prioritizes shorter prints')}
+ >
+
+ {t('queue.sjf.label', 'SJF')}
+
+
{isLoading ? (
@@ -1248,22 +1264,6 @@ export function QueuePage() {
- {
- const newValue = !(settings?.queue_shortest_first ?? false);
- sjfMutation.mutate(newValue);
- }}
- className={`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${
- settings?.queue_shortest_first
- ? 'bg-bambu-green/20 border-bambu-green text-bambu-green'
- : 'bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray'
- }`}
- title={t('queue.sjf.tooltip', 'Shortest Job First — scheduler prioritizes shorter prints')}
- >
-
- {t('queue.sjf.label', 'SJF')}
-
-
{window.innerWidth<640&&u()}:void 0,children:[ae&&d&&a.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),a.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[L&&u&&a.jsx("button",{onClick:ee=>{ee.stopPropagation(),u()},className:`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${d?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:d&&a.jsx(Kr,{className:"w-4 h-4"})}),L?a.jsx("div",{...M,...T,className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation shrink-0",children:a.jsx(jh,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?a.jsxs("div",{className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium shrink-0",children:["#",e]}):a.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),a.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?a.jsx("img",{src:t.plate_id!=null?he.getArchivePlateThumbnail(t.archive_id,t.plate_id):he.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?he.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):he.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ea,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("p",{className:"text-sm sm:text-base text-white font-medium truncate",children:[t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,(k?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${P.find(ee=>ee.index===t.plate_id)?.name||y("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?a.jsx(vo,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:y("queue.viewArchive"),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(vo,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:y("queue.viewInFileManager"),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):null,t.batch_name&&a.jsx("span",{className:"flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-purple-500/20 text-purple-300 rounded border border-purple-500/30",children:t.batch_name})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[a.jsxs("span",{className:`flex items-center gap-1 sm:gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model&&!t.printer_id?"text-blue-400":""}`,children:[a.jsx(Pr,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),a.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model&&!t.printer_id?`${y("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?y("queue.filter.unassigned"):t.printer_name||`${y("common.printer")} #${t.printer_id}`})]}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(Pc,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),ls(t.print_time_seconds)]}),t.filament_used_grams&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(CQ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Het(t.filament_used_grams)]}),t.created_by_username&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:y("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(Gu,{className:"w-3.5 h-3.5"}),t.created_by_username]}),L&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),t.scheduled_time?(Qn(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?y?.("queue.time.overdue")??"Overdue":Sx(t.scheduled_time,c,y):y?.("queue.time.asap")??"ASAP"]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[a.jsx(gQ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.staged")]}),t.require_previous_success&&a.jsx("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:y("queue.badges.requiresPrevious")}),t.auto_off_after&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[a.jsx(am,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.autoPowerOff")]}),t.gcode_injection&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-500/10 text-emerald-400 rounded-full border border-emerald-500/20 flex items-center gap-1",children:[a.jsx(ey,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.gcodeInjection")]})]}),Q&&v&&a.jsxs("div",{className:"mt-2 sm:mt-3",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${v.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(v.progress||0),"%"]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mt-1.5 sm:mt-2 text-[10px] sm:text-xs text-bambu-gray",children:[v.remaining_time!=null&&v.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),ls(v.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:y("printers.estimatedCompletion"),children:["ETA ",vO(v.remaining_time,c,y)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(ea,{className:"w-3 h-3"}),v.layer_num,"/",v.total_layers]})]})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[a.jsx(qa,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[a.jsx(qa,{className:"w-3 h-3"}),t.error_message]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:ee=>ee.stopPropagation(),children:[a.jsx(qet,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:y}),a.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[Q&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("printers:control")?y("queue.actions.stopPrint"):y("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:a.jsx(Upe,{className:"w-4 h-4"})}),L&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("printers:control")?y("queue.actions.startPrint"):y("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2",children:a.jsx(Ds,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?y("common.edit"):y("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?y("common.cancel"):y("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),re&&a.jsxs(a.Fragment,{children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("queue:create")?y("queue.actions.requeue"):y("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2",children:a.jsx(vr,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?y("common.remove"):y("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})]})]})}function Vet(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=Sr(),[o,l]=w.useState(null),[c,d]=w.useState(""),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState(null),[_,k]=w.useState(null),[P,N]=w.useState([]),[M,T]=w.useState(!1),[A,C]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[F,$]=w.useState(()=>{const ve=localStorage.getItem("queue.historySortAsc");return ve!==null?ve==="true":!1}),[I,Q]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[L,re]=w.useState(()=>{const ve=localStorage.getItem("queue.pendingSortAsc");return ve!==null?ve==="true":!0}),[ae,ee]=w.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[ue,le]=w.useState(()=>localStorage.getItem("queue.viewMode")||"list");w.useEffect(()=>{localStorage.setItem("queue.historySortBy",A)},[A]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(F))},[F]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",I)},[I]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(L))},[L]),w.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ae))},[ae]),w.useEffect(()=>{localStorage.setItem("queue.viewMode",ue)},[ue]);const de=Ooe(pP(JT,{activationConstraint:{distance:8}}),pP(ZT,{coordinateGetter:sle})),{data:K}=et({queryKey:["settings"],queryFn:he.getSettings}),te=K?.time_format||"system",{data:se,isLoading:be}=et({queryKey:["queue",o,c],queryFn:()=>he.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:Ne}=et({queryKey:["printers"],queryFn:()=>he.getPrinters()}),B=lt({mutationFn:ve=>he.updateSettings({queue_shortest_first:ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),Y=lt({mutationFn:ve=>he.cancelQueueItem(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),D=lt({mutationFn:ve=>he.removeFromQueue(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),j=lt({mutationFn:ve=>he.stopQueueItem(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),z=lt({mutationFn:ve=>he.startQueueItem(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),W=lt({mutationFn:ve=>he.reorderQueue(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),q=lt({mutationFn:async()=>{const ve=se?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];for(const fe of ve)await he.removeFromQueue(fe.id);return ve.length},onSuccess:ve=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:ve}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),ce=lt({mutationFn:ve=>he.bulkUpdateQueue(ve),onSuccess:ve=>{e.invalidateQueries({queryKey:["queue"]}),N([]),T(!1),n(ve.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),O=lt({mutationFn:async ve=>{for(const fe of ve)await he.cancelQueueItem(fe);return ve.length},onSuccess:ve=>{e.invalidateQueries({queryKey:["queue"]}),N([]),n(t("queue.toast.bulkCancelled",{count:ve}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),G=ve=>{N(fe=>fe.includes(ve)?fe.filter(ke=>ke!==ve):[...fe,ve])},X=w.useMemo(()=>{const ve=new Set;return Ne?.forEach(fe=>{fe.location&&ve.add(fe.location)}),se?.forEach(fe=>{fe.target_location&&ve.add(fe.target_location)}),Array.from(ve).sort()},[Ne,se]),V=w.useCallback(ve=>u?ve.target_location?ve.target_location===u:ve.printer_id?Ne?.find(ke=>ke.id===ve.printer_id)?.location===u:!1:!0,[u,Ne]),J=w.useMemo(()=>{let ve=se?.filter(ke=>ke.status==="pending")||[];u&&(ve=ve.filter(V));const fe=ke=>{if(!ke.scheduled_time)return 0;const Ee=Qn(ke.scheduled_time)?.getTime()??0,Ae=Date.now()+4320*60*60*1e3;return Ee>Ae?0:Ee};return K?.queue_shortest_first?[...ve].sort((ke,Ee)=>{const Ae=ke.printer_id??-(ke.target_model?.charCodeAt(0)??0),_e=Ee.printer_id??-(Ee.target_model?.charCodeAt(0)??0);if(Ae!==_e)return Ae-_e;const je=ke.been_jumped?1:0,Be=Ee.been_jumped?1:0;if(je!==Be)return Be-je;const Re=ke.print_time_seconds??1/0,Ye=Ee.print_time_seconds??1/0;return Re!==Ye?Re-Ye:ke.position-Ee.position}):[...ve].sort((ke,Ee)=>{let Ae;if(I==="name"){const _e=ke.archive_name||ke.library_file_name||"",je=Ee.archive_name||Ee.library_file_name||"";Ae=_e.localeCompare(je)}else I==="printer"?Ae=(ke.printer_name||"").localeCompare(Ee.printer_name||""):I==="time"?Ae=fe(ke)-fe(Ee):Ae=ke.position-Ee.position;return L?Ae:-Ae})},[se,I,L,V,u,K?.queue_shortest_first]),ie=()=>{const ve=J.map(fe=>fe.id);P.length===ve.length?N([]):N(ve)},me=w.useMemo(()=>{let ve=se?.filter(fe=>fe.status==="printing")||[];return u&&(ve=ve.filter(V)),ve},[se,u,V]),pe=w.useMemo(()=>{const ve=new Set;return me.forEach(fe=>{fe.printer_id&&ve.add(fe.printer_id)}),Array.from(ve)},[me]),oe=ep({queries:pe.map(ve=>({queryKey:["printerStatus",ve],queryFn:()=>he.getPrinterStatus(ve),refetchInterval:5e3}))}),U=w.useMemo(()=>{const ve={};return pe.forEach((fe,ke)=>{const Ee=oe[ke];Ee?.data?.state&&(ve[fe]=Ee.data.state)}),ve},[pe,oe]),R=w.useMemo(()=>{const ve={};return pe.forEach((fe,ke)=>{const Ee=oe[ke];Ee?.data&&(ve[fe]={progress:Ee.data.progress??void 0,remaining_time:Ee.data.remaining_time??void 0,state:Ee.data.state??void 0})}),ve},[pe,oe]),ne=w.useMemo(()=>{let ve=se?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];return u&&(ve=ve.filter(V)),[...ve].sort((fe,ke)=>{let Ee;if(A==="name"){const Ae=fe.archive_name||fe.library_file_name||"",_e=ke.archive_name||ke.library_file_name||"";Ee=Ae.localeCompare(_e)}else A==="printer"?Ee=(fe.printer_name||"").localeCompare(ke.printer_name||""):Ee=(Qn(ke.completed_at||ke.created_at)?.getTime()??0)-(Qn(fe.completed_at||fe.created_at)?.getTime()??0);return F?-Ee:Ee})},[se,A,F,V,u]),xe=w.useMemo(()=>J.reduce((ve,fe)=>ve+(fe.print_time_seconds||0),0),[J]),Se=w.useMemo(()=>J.reduce((ve,fe)=>ve+(fe.filament_used_grams||0),0),[J]),ye=ve=>{const{active:fe,over:ke}=ve;if(!ke||fe.id===ke.id)return;const Ee=J.findIndex(_e=>_e.id===fe.id),Ae=J.findIndex(_e=>_e.id===ke.id);if(Ee!==-1&&Ae!==-1){const je=nA(J,Ee,Ae).map((Be,Re)=>({id:Be.id,position:Re+1}));W.mutate(je)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(nN,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsx(Fet,{activeCount:me.length,pendingCount:J.length,totalTime:xe,totalWeight:Se,historyCount:ne.length,t}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:o===-1?"unassigned":o||"",onChange:ve=>{const fe=ve.target.value;l(fe==="unassigned"?-1:fe===""?null:Number(fe))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),Ne?.map(ve=>a.jsx("option",{value:ve.id,children:ve.name},ve.id))]}),a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:c,onChange:ve=>d(ve.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),X.length>0&&a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:u,onChange:ve=>m(ve.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),X.map(ve=>a.jsx("option",{value:ve,children:ve},ve))]}),a.jsx("div",{className:"hidden sm:block flex-1"}),ne.length>0&&a.jsxs(Ie,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>f(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(un,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),a.jsx("div",{className:"hidden sm:flex items-center gap-3 mb-6",children:a.jsxs("div",{className:"flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsx("button",{className:`p-2 transition-colors ${ue==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("list"),title:t("queue.timeline.listView"),children:a.jsx(Ew,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 transition-colors ${ue==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("timeline"),title:t("queue.timeline.timelineView"),children:a.jsx(Npe,{className:"w-4 h-4"})})]})}),be?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):se?.length===0?a.jsxs(Dt,{className:"p-12 text-center border-dashed",children:[a.jsx(Wr,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):ue==="timeline"?a.jsx(Bet,{queueItems:se||[],printerStatuses:R,onItemClick:ve=>{["completed","failed","skipped","cancelled"].includes(ve.status)?g(ve):ve.status==="pending"?v(ve):ve.status==="printing"&&k({type:"stop",item:ve})},t}):a.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[me.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-2 sm:space-y-3",children:me.map(ve=>a.jsx(KY,{item:ve,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>k({type:"stop",item:ve}),onRequeue:()=>{},onStart:()=>{},timeFormat:te,hasPermission:r,canModify:s,printerState:ve.printer_id?U[ve.printer_id]:null,t},ve.id))})]}),J.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:J.length}),")"]}),a.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("button",{onClick:()=>{const ve=!(K?.queue_shortest_first??!1);B.mutate(ve)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${K?.queue_shortest_first?"bg-bambu-green/20 border-bambu-green text-bambu-green":"bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,title:t("queue.sjf.tooltip","Shortest Job First — scheduler prioritizes shorter prints"),children:[a.jsx(Pc,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.sjf.label","SJF")}),a.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?.queue_shortest_first?"bg-bambu-green":"bg-bambu-gray"}`})]}),a.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:I,onChange:ve=>Q(ve.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>re(!L),title:t(L?"common.ascending":"common.descending"),className:"px-2",children:L?a.jsx(Lf,{className:"w-4 h-4"}):a.jsx(bx,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-3 sm:mb-4 p-2 sm:p-3 bg-bambu-dark rounded-lg",children:[a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:ie,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[P.length===J.length&&J.length>0?a.jsx(us,{className:"w-4 h-4 text-bambu-green"}):a.jsx(eo,{className:"w-4 h-4"}),P.length===J.length&&J.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),P.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:P.length})}),a.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>T(!0),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light",disabled:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?t("queue.bulkEdit.editSelected"):t("queue.permissions.noEditItems"),children:[a.jsx(Za,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>O.mutate(P),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:O.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?t("queue.bulkEdit.cancelSelected"):t("queue.permissions.noCancelItems"),children:[a.jsx(Bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),a.jsx(ele,{sensors:de,collisionDetection:Boe,onDragEnd:ye,children:a.jsx(rle,{items:J.map(ve=>ve.id),strategy:wet,children:a.jsx("div",{className:"space-y-2 sm:space-y-3",children:J.map((ve,fe)=>a.jsx(KY,{item:ve,position:fe+1,onEdit:()=>v(ve),onCancel:()=>k({type:"cancel",item:ve}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>z.mutate(ve.id),timeFormat:te,isSelected:P.includes(ve.id),onToggleSelect:()=>G(ve.id),hasPermission:r,canModify:s,t},ve.id))})})})]}),ne.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("button",{onClick:()=>ee(!ae),className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2 hover:text-bambu-green transition-colors",children:[ae?a.jsx(Va,{className:"w-4 h-4 sm:w-5 sm:h-5"}):a.jsx(Fn,{className:"w-4 h-4 sm:w-5 sm:h-5"}),t("queue.sections.history"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:ne.length}),")"]})]}),!ae&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:A,onChange:ve=>C(ve.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>$(!F),title:t(F?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:F?a.jsx(Lf,{className:"w-4 h-4"}):a.jsx(bx,{className:"w-4 h-4"})})]})]}),!ae&&a.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:ne.slice(0,50).map(ve=>a.jsx(Ret,{item:ve,onRemove:()=>k({type:"remove",item:ve}),onRequeue:()=>g(ve),timeFormat:te,hasPermission:r,canModify:s,t},ve.id))})]})]}),y&&a.jsx(kd,{mode:"edit-queue-item",archiveId:y.archive_id??void 0,libraryFileId:y.library_file_id??void 0,archiveName:y.archive_name||y.library_file_name||`File #${y.archive_id||y.library_file_id}`,queueItem:y,onClose:()=>v(null)}),b&&a.jsx(kd,{mode:"add-to-queue",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,onClose:()=>g(null)}),_&&a.jsx(kn,{title:_.type==="cancel"?t("queue.confirm.cancelTitle"):_.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:_.type==="cancel"?t("queue.confirm.cancelMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):_.type==="stop"?t("queue.confirm.stopMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:_.type==="cancel"?t("queue.confirm.cancelButton"):_.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{_.type==="cancel"?Y.mutate(_.item.id):_.type==="stop"?j.mutate(_.item.id):D.mutate(_.item.id),k(null)},onCancel:()=>k(null)}),p&&a.jsx(kn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:ne.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{q.mutate(),f(!1)},onCancel:()=>f(!1)}),M&&a.jsx($et,{selectedCount:P.length,printers:Ne?.map(ve=>({id:ve.id,name:ve.name}))||[],onSave:ve=>{Object.keys(ve).length>0&&ce.mutate({item_ids:P,...ve})},onClose:()=>T(!1),isSaving:ce.isPending,canControlPrinter:r("printers:control"),t})]})}function Get({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const k=new ResizeObserver(P=>{const N=P[0]?.contentRect.width||0;i(N)});return k.observe(_),()=>k.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach($=>{const I=$.split("T")[0];_[I]=(_[I]||0)+1});const k=new Date,P=new Date(k);P.setMonth(P.getMonth()-e),P.setDate(P.getDate()-P.getDay());const N=[],M=[];let T=[],A=-1;const C=new Date(P);let F=0;for(;C<=k;)C.getDay()===0&&T.length>0&&(N.push(T),T=[],F++),C.getMonth()!==A&&(M.push({month:C.toLocaleDateString("en-US",{month:"short"}),weekIndex:F}),A=C.getMonth()),T.push(new Date(C)),C.setDate(C.getDate()+1);return T.length>0&&N.push(T),{weeks:N,monthLabels:M,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),d=_=>{if(_===0)return"bg-bambu-dark";const k=_/c;return k<=.25?"bg-bambu-green/30":k<=.5?"bg-bambu-green/50":k<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,y=r-p-16,v=m>0?Math.floor((y-(m-1)*f)/m):12,b=Math.max(8,Math.min(20,v)),g=b<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:_,weekIndex:k},P)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:g,marginLeft:P===0?0:`${(k-(o[P-1]?.weekIndex||0))*(b+f)-24}px`},children:_},P))}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"flex flex-col",style:{gap:f,marginRight:4,width:p},children:u.map((_,k)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:g,visibility:k%2===1?"visible":"hidden"},children:_},_))}),s.map((_,k)=>a.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(P=>{const N=_.find(C=>C.getDay()===P);if(!N)return a.jsx("div",{style:{width:b,height:b}},P);const M=N.toISOString().split("T")[0],T=l[M]||0,A=M===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${d(T)} ${A?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${N.toLocaleDateString()}: ${T} print${T!==1?"s":""}`},P)})},k))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:g},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),a.jsx("span",{children:"More"})]})]})})}const YY=["weight","prints","time"];function bP({value:t,onChange:e,exclude:n}){const{t:r}=Lt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=n?YY.filter(o=>!n.includes(o)):YY;return a.jsx("div",{className:"flex gap-0.5 bg-bambu-dark rounded-lg p-0.5",children:s.map(o=>a.jsx("button",{onClick:()=>e(o),className:`px-2 py-0.5 text-xs rounded-md transition-colors ${t===o?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:i[o]},o))})}function gh(t){if(t>=1e6){const e=t/1e6;return`${e%1===0?e.toFixed(0):e.toFixed(1)}t`}if(t>=1e3){const e=t/1e3;return`${e%1===0?e.toFixed(0):e.toFixed(1)}kg`}return`${Math.round(t)}g`}const mk=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],Wet=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],XY=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"];function Ket({archives:t,currency:e="$",dateFrom:n,dateTo:r}){const{t:i}=Lt(),[s,o]=w.useState("weight"),[l,c]=w.useState("weight"),d=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{const F=Qn(C.completed_at||C.created_at)||new Date,$=`${F.getFullYear()}-${String(F.getMonth()+1).padStart(2,"0")}-${String(F.getDate()).padStart(2,"0")}`,I=A.get($)||{date:$,filament:0,cost:0,prints:0};I.filament+=C.filament_used_grams||0,I.cost+=C.cost||0,I.prints+=C.quantity||1,A.set($,I)}),Array.from(A.values()).sort((C,F)=>C.date.localeCompare(F.date)).map(C=>({...C,dateLabel:new Date(C.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[t]),u=w.useMemo(()=>{if(n&&r)return Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1;if(n)return Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1;if(t.length<2)return 0;const A=t.map(C=>new Date(C.completed_at||C.created_at).getTime());return(Math.max(...A)-Math.min(...A))/864e5},[t,n,r]),m=w.useMemo(()=>{if(u>7)return[];const A=new Map,C=u>1;return t.forEach(F=>{const $=Qn(F.completed_at||F.created_at)||new Date,I=$.getHours(),Q=`${$.getFullYear()}-${String($.getMonth()+1).padStart(2,"0")}-${String($.getDate()).padStart(2,"0")}T${String(I).padStart(2,"0")}`,L=A.get(Q)||{date:Q,filament:0,cost:0,prints:0};L.filament+=F.filament_used_grams||0,L.cost+=F.cost||0,L.prints+=F.quantity||1,A.set(Q,L)}),Array.from(A.values()).sort((F,$)=>F.date.localeCompare($.date)).map(F=>{const[$,I]=F.date.split("T"),Q=new Date($),L=parseInt(I,10),re=C?`${Wet[Q.getDay()]} ${XY[L]}`:XY[L];return{...F,dateLabel:re}})},[t,u]),p=w.useMemo(()=>{if(d.length<=60)return d;const A=new Map;return d.forEach(C=>{const F=new Date(C.date),$=new Date(F);$.setDate(F.getDate()-F.getDay());const I=`${$.getFullYear()}-${String($.getMonth()+1).padStart(2,"0")}-${String($.getDate()).padStart(2,"0")}`,Q=A.get(I)||{week:I,filament:0,cost:0,prints:0};Q.filament+=C.filament,Q.cost+=C.cost,Q.prints+=C.prints,A.set(I,Q)}),Array.from(A.values()).sort((C,F)=>C.week.localeCompare(F.week)).map(C=>({date:C.week,dateLabel:`Week of ${new Date(C.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...C}))},[d]),f=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{const $=(C.filament_type||"Unknown").split(", ");$.forEach(I=>{const Q=(C.filament_used_grams||0)/$.length;A.set(I,(A.get(I)||0)+Q)})}),Array.from(A.entries()).map(([C,F])=>({name:C,value:Math.round(F)})).sort((C,F)=>F.value-C.value)},[t]),y=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{(C.filament_type||"Unknown").split(", ").forEach(I=>{A.set(I,(A.get(I)||0)+1)})}),Array.from(A.entries()).map(([C,F])=>({name:C,value:F})).sort((C,F)=>F.value-C.value)},[t]),v=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{const $=(C.filament_type||"Unknown").split(", "),I=(C.actual_time_seconds||C.print_time_seconds||0)/$.length;$.forEach(Q=>{A.set(Q,(A.get(Q)||0)+I)})}),Array.from(A.entries()).map(([C,F])=>({name:C,value:Math.round(F/3600*10)/10})).sort((C,F)=>F.value-C.value)},[t]),b=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{if(C.status!=="completed"&&C.status!=="failed")return;(C.filament_type||"Unknown").split(", ").forEach($=>{const I=A.get($)||{completed:0,failed:0};C.status==="completed"?I.completed++:I.failed++,A.set($,I)})}),Array.from(A.entries()).filter(([,C])=>C.completed+C.failed>=2).map(([C,F])=>{const $=F.completed+F.failed,I=Math.round(F.completed/$*100);return{name:C,rate:I,total:$}}).sort((C,F)=>F.rate-C.rate)},[t]),g=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{if(!C.filament_color)return;const F=C.filament_color.split(",").map(I=>I.trim()),$=(C.filament_used_grams||0)/F.length;F.forEach(I=>{const Q=A.get(I)||{count:0,weight:0};Q.count++,Q.weight+=$,A.set(I,Q)})}),Array.from(A.entries()).map(([C,F])=>({hex:C,value:l==="prints"?F.count:Math.round(F.weight)})).sort((C,F)=>F.value-C.value)},[t,l]),_=s==="weight"?f:s==="prints"?y:v,k=u<=7&&m.length>0?m:p,P=t.reduce((A,C)=>A+(C.filament_used_grams||0),0),N=t.reduce((A,C)=>A+(C.cost||0),0),M=t.reduce((A,C)=>A+(C.quantity||1),0),T=new Set(t.map(A=>A.printer_id).filter(Boolean)).size;return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-2 max-[640px]:grid-cols-1",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodFilament")}),a.jsx("p",{className:"text-2xl font-bold text-white leading-none",children:gh(P)})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[T," ",i("nav.printers").toLowerCase()]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodCost")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,N.toFixed(2)]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[M," ",i("common.prints")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.avgPerPrint")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[M>0?(P/M).toFixed(0):0,"g"]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,M>0?(N/M).toFixed(2):"0.00"," avg"]})]})]}),k.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.usageOverTime")}),a.jsx(Sh,{width:"100%",height:250,children:a.jsxs(bVe,{data:k,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:A=>`${A}g`}),a.jsx(_h,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:A=>[`${Number(A??0).toFixed(0)}g`,"Filament"]}),a.jsx(Jre,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:i("stats.noPrintDataInRange")}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.byMaterial")}),a.jsx(bP,{value:s,onChange:o})]}),_.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Sh,{width:160,height:160,children:a.jsxs(PW,{children:[a.jsx(qR,{data:_,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:_.map((A,C)=>a.jsx(zx,{fill:mk[C%mk.length]},`cell-${C}`))}),a.jsx(_h,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:A=>[s==="weight"?gh(Number(A??0)):s==="time"?`${Number(A??0)}h`:`${A??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:_.map((A,C)=>{const F=_.reduce((I,Q)=>I+Q.value,0),$=F>0?(A.value/F*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:mk[C%mk.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:A.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?gh(A.value):s==="time"?`${A.value}h`:A.value," · ",$,"%"]})]},A.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noFilamentData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.filamentSuccess")}),b.length>0?a.jsx("div",{className:"space-y-1.5",children:b.map(A=>a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-white truncate w-20 flex-shrink-0",children:A.name}),a.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-secondary rounded-full",children:a.jsx("div",{className:`h-full rounded-full transition-all ${A.rate>=90?"bg-status-ok":A.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${A.rate}%`}})}),a.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${A.rate>=90?"text-status-ok":A.rate>=70?"text-status-warning":"text-status-error"}`,children:[A.rate,"%"]}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",A.total,")"]})]},A.name))}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.colorDistribution")}),a.jsx(bP,{value:l,onChange:c,exclude:["time"]})]}),g.length>0?(()=>{const A=g.reduce((C,F)=>C+F.value,0);return a.jsxs("div",{children:[a.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[a.jsx(Sh,{width:"100%",height:"100%",children:a.jsxs(PW,{children:[a.jsx(qR,{data:g,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:g.map((C,F)=>a.jsx(zx,{fill:C.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${F}`))}),a.jsx(_h,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:C=>[l==="weight"?gh(Number(C??0)):`${C??0}`,i(l==="weight"?"stats.filamentByWeight":"stats.filamentByPrints")]})]})}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsx("span",{className:"text-lg font-bold text-white",children:l==="weight"?gh(A):A}),a.jsxs("span",{className:"text-[10px] text-bambu-gray",children:[g.length," ",g.length===1?"color":"colors"]})]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1 mt-2",children:g.slice(0,8).map(C=>{const F=A>0?(C.value/A*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-1.5 text-xs min-w-0",children:[a.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20",style:{backgroundColor:C.hex}}),a.jsxs("span",{className:"text-bambu-gray truncate",children:[F,"%"]})]},C.hex)})}),g.length>8&&a.jsxs("p",{className:"text-[10px] text-bambu-gray mt-1 text-center",children:["+",g.length-8," more"]})]})})():a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noColorData")})]})]})]})}function Yet({id:t,title:e,component:n,isHidden:r,size:i,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:f}=ile({id:t}),y={transform:Kx.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...y,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...c,...d,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:l,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(hO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(NP,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(Tw,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function Xet({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const A={};return t.forEach(C=>{A[C.id]=C.defaultSize||4}),A},[c,d]=w.useState(()=>{const A=localStorage.getItem(e);if(A)try{const C=JSON.parse(A);if(!C.sizes)C.sizes=l();else{const F=l();for(const $ in F)$ in C.sizes||(C.sizes[$]=F[$])}return C}catch{}return{order:t.map(C=>C.id),hidden:t.filter(C=>C.defaultVisible===!1).map(C=>C.id),sizes:l()}}),[u,m]=w.useState(!1),[p,f]=w.useState(!1);w.useEffect(()=>{if(!r)return;const A=window.matchMedia(`(max-width: ${r}px)`),C=$=>{f($.matches)};C(A);const F=$=>C($);return A.addEventListener?A.addEventListener("change",F):A.addListener(F),()=>{A.removeEventListener?A.removeEventListener("change",F):A.removeListener(F)}},[r]);const y=r&&p?1:n;w.useEffect(()=>{const A=()=>m(C=>!C);return window.addEventListener("toggle-hidden-panel",A),()=>window.removeEventListener("toggle-hidden-panel",A)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const C=t.map(F=>F.id).filter(F=>!c.order.includes(F));C.length>0&&d(F=>({...F,order:[...F.order,...C]}))},[t,c.order]);const v=Ooe(pP(JT,{activationConstraint:{distance:8}}),pP(ZT,{coordinateGetter:sle})),b=A=>{const{active:C,over:F}=A;F&&C.id!==F.id&&d($=>{const I=$.order.indexOf(C.id),Q=$.order.indexOf(F.id);return{...$,order:nA($.order,I,Q)}})},g=A=>{d(C=>({...C,hidden:C.hidden.includes(A)?C.hidden.filter(F=>F!==A):[...C.hidden,A]}))},_=A=>{d(C=>{const F=C.sizes[A]||4,$=F===1?2:F===2?4:1;return{...C,sizes:{...C.sizes,[A]:$}}})},k=()=>{const A={order:t.map(C=>C.id),hidden:t.filter(C=>C.defaultVisible===!1).map(C=>C.id),sizes:l()};d(A),s?.()},P=c.order.map(A=>t.find(C=>C.id===A)).filter(Boolean),N=P.filter(A=>!c.hidden.includes(A.id)),M=P.filter(A=>c.hidden.includes(A.id)),T=o?.({hiddenCount:M.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:k});return a.jsxs("div",{className:"space-y-4",children:[T,!i&&!o&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:k,children:[a.jsx(jo,{className:"w-4 h-4"}),"Reset Layout"]}),M.length>0&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[a.jsx(Dc,{className:"w-4 h-4"}),M.length," Hidden"]})]}),u&&M.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(A=>a.jsxs("button",{onClick:()=>g(A.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[a.jsx(Dc,{className:"w-3 h-3"}),A.title]},A.id))})]}),a.jsx(ele,{sensors:v,collisionDetection:Boe,onDragEnd:b,children:a.jsx(rle,{items:N.map(A=>A.id),strategy:Wz,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`},children:N.map(A=>{const C=c.sizes[A.id]||2,F=Math.min(C,y);return a.jsx(Yet,{id:A.id,title:A.title,component:A.component,isHidden:c.hidden.includes(A.id),size:C,columnSpan:F,onToggleVisibility:()=>g(A.id),onToggleSize:()=>_(A.id)},A.id)})})})}),N.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Ie,{className:"mt-4",onClick:k,children:"Reset Layout"})]})]})}function Qet(t){const e=new Date,n=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate(),s=l=>l.toISOString().split("T")[0],o=s(e);switch(t){case"today":return{dateFrom:o,dateTo:o};case"this-week":{const l=e.getUTCDay(),c=new Date(Date.UTC(n,r,i-(l===0?6:l-1)));return{dateFrom:s(c),dateTo:o}}case"this-month":return{dateFrom:s(new Date(Date.UTC(n,r,1))),dateTo:o};case"last-7":return{dateFrom:s(new Date(Date.UTC(n,r,i-6))),dateTo:o};case"last-30":return{dateFrom:s(new Date(Date.UTC(n,r,i-29))),dateTo:o};case"last-90":return{dateFrom:s(new Date(Date.UTC(n,r,i-89))),dateTo:o};case"this-year":return{dateFrom:s(new Date(Date.UTC(n,0,1))),dateTo:o};case"all-time":return{dateFrom:void 0,dateTo:void 0};case"custom":return{}}}const Zet=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],Jet=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],UL=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],i3=[{key:"<30m",max:1800},{key:"30m-1h",max:3600},{key:"1-2h",max:7200},{key:"2-4h",max:14400},{key:"4-8h",max:28800},{key:"8-12h",max:43200},{key:"12-24h",max:86400},{key:"24h+",max:1/0}],hk={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function ett({stats:t,currency:e}){const{t:n}=Lt(),r=[{icon:Na,color:"text-bambu-green",label:n("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:rr,color:"text-blue-400",label:n("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Na,color:"text-orange-400",label:n("stats.filamentUsed"),value:gh(t?.total_filament_grams||0)},{icon:Zk,color:"text-green-400",label:n("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:Xl,color:"text-yellow-400",label:n("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`},{icon:Zk,color:"text-yellow-500",label:n("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`}];return a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:r.map(i=>a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${i.color}`,children:a.jsx(i.icon,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),a.jsx("p",{className:"text-xl font-bold text-white",children:i.value})]})]},i.label))})}function ttt({stats:t,printerMap:e,size:n=1}){const{t:r}=Lt(),i=(t?.successful_prints||0)+(t?.failed_prints||0),s=i?Math.round(t.successful_prints/i*100):0,o=n===1?112:n===2?128:144,l=o/2-8,c=l*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:o,height:o},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${s/100*c} ${c}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[s,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx($a,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([d,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(d)||`${r("common.printer")} ${d}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},d))})]})]})]})}function ntt({stats:t,printerMap:e,size:n=1}){const{t:r}=Lt(),i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(i),d=i-100,u=n===1?112:n===2?128:144,m=u/2-8,p=m*2*Math.PI,f=n===1?3:n===2?6:999,y=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,f):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:u,height:u},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${d>=0?"text-blue-400":"text-orange-400"}`,children:[d>=0?"+":"",d.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx(_Q,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),y.length>0&&a.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:y.map(([v,b])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),a.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},v))})]})]})}function rtt({printDates:t,dateFrom:e,dateTo:n}){const{days:r,hourlyCounts:i,maxCount:s}=w.useMemo(()=>{const u=new Date(e+"T00:00:00"),m=new Date(n+"T00:00:00"),p=[],f=g=>`${g.getFullYear()}-${String(g.getMonth()+1).padStart(2,"0")}-${String(g.getDate()).padStart(2,"0")}`,y=new Date(u);for(;y<=m;)p.push({key:f(y),label:y.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),y.setDate(y.getDate()+1);const v={};let b=0;return t.forEach(g=>{const _=Qn(g);if(!_)return;const P=`${`${_.getFullYear()}-${String(_.getMonth()+1).padStart(2,"0")}-${String(_.getDate()).padStart(2,"0")}`}-${_.getHours()}`;v[P]=(v[P]||0)+1,v[P]>b&&(b=v[P])}),{days:p,hourlyCounts:v,maxCount:Math.max(1,b)}},[t,e,n]),o=u=>{if(u===0)return"bg-bambu-dark";const m=u/s;return m<=.25?"bg-bambu-green/30":m<=.5?"bg-bambu-green/50":m<=.75?"bg-bambu-green/75":"bg-bambu-green"},l=20,c=2,d=80;return a.jsxs("div",{className:"w-full overflow-x-auto",children:[a.jsxs("div",{className:"inline-flex flex-col",style:{gap:c},children:[a.jsx("div",{className:"flex",style:{gap:c,marginLeft:d+4},children:UL.map((u,m)=>a.jsx("div",{className:"text-bambu-gray text-[10px] text-center",style:{width:l,visibility:m%2===0?"visible":"hidden"},children:u},m))}),r.map(u=>a.jsxs("div",{className:"flex items-center",style:{gap:c},children:[a.jsx("div",{className:"text-bambu-gray text-[10px] flex-shrink-0 truncate",style:{width:d},children:u.label}),Array.from({length:24},(m,p)=>{const f=i[`${u.key}-${p}`]||0;return a.jsx("div",{className:`rounded-sm ${o(f)}`,style:{width:l,height:l},title:`${u.label} ${UL[p]}: ${f} print${f!==1?"s":""}`},p)})]},u.key))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray text-xs",children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:c},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:l,height:l}})]}),a.jsx("span",{children:"More"})]})]})}function att({printDates:t,size:e=2,dateFrom:n,dateTo:r}){const i=w.useMemo(()=>n&&r?Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1:n?Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1:1/0,[n,r]);if(i<=7&&n&&r)return a.jsx(rtt,{printDates:t,dateFrom:n,dateTo:r});const o=i===1/0?e===1?3:e===2?6:12:Math.max(1,Math.ceil(i/30));return a.jsx(Get,{printDates:t,months:o})}function itt({stats:t,archives:e,printerMap:n}){const{t:r}=Lt(),[i,s]=w.useState("weight"),[o,l]=w.useState("weight"),c=w.useMemo(()=>{const g=new Map;return t?.prints_by_printer&&Object.entries(t.prints_by_printer).forEach(([_,k])=>{const P=g.get(_)||{prints:0,weight:0,time:0};P.prints=k,g.set(_,P)}),e.forEach(_=>{if(!_.printer_id)return;const k=String(_.printer_id),P=g.get(k)||{prints:0,weight:0,time:0};P.weight+=_.filament_used_grams||0,P.time+=_.actual_time_seconds||_.print_time_seconds||0,t?.prints_by_printer||P.prints++,g.set(k,P)}),Array.from(g.entries()).map(([_,k])=>({name:n.get(_)||`${r("common.printer")} ${_}`,value:i==="prints"?k.prints:i==="weight"?Math.round(k.weight):Math.round(k.time/3600*10)/10})).sort((_,k)=>k.value-_.value)},[t,e,n,i,r]),d=w.useMemo(()=>{const g=Array.from({length:24},(_,k)=>({hour:k,label:UL[k],total:0,failures:0}));return e.forEach(_=>{if(!_.started_at)return;const k=Qn(_.started_at);if(!k)return;const P=k.getHours();g[P].total++,_.status==="failed"&&g[P].failures++}),g},[e]),u=w.useMemo(()=>{const g=i3.map(_=>({name:_.key,count:0}));return e.forEach(_=>{const k=_.actual_time_seconds||_.print_time_seconds;if(!(!k||k<=0)){for(let P=0;P{const g=[0,0,0,0,0,0,0],_=new Set;e.forEach(P=>{const N=Qn(P.created_at)||new Date(P.created_at);let M=N.getDay()-1;M<0&&(M=6),o==="prints"?g[M]++:o==="weight"?g[M]+=P.filament_used_grams||0:g[M]+=(P.actual_time_seconds||P.print_time_seconds||0)/3600;const T=new Date(N);T.setDate(N.getDate()-(N.getDay()+6)%7),_.add(`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`)});const k=Math.max(_.size,1);return Jet.map((P,N)=>({name:P,avg:Math.round(g[N]/k*10)/10}))},[e,o]),p=g=>({unit:g==="weight"?"g":g==="time"?"h":"",color:g==="weight"?"#00ae42":g==="time"?"#3b82f6":"#f59e0b"}),f=p(i),y=r(i==="weight"?"stats.filamentByWeight":i==="time"?"stats.hours":"common.prints"),v=p(o),b=r(o==="weight"?"stats.avgWeight":o==="time"?"stats.avgTime":"stats.avgPrints");return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printsByPrinter")}),a.jsx(bP,{value:i,onChange:s})]}),c.length>0?a.jsx(Sh,{width:"100%",height:Math.max(140,c.length*40),children:a.jsxs(W1,{data:c,layout:"vertical",margin:{left:10},children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),a.jsx(hf,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),a.jsx(_h,{contentStyle:hk,formatter:g=>[i==="weight"?gh(Number(g??0)):`${g??0}${f.unit}`,y]}),a.jsx(Hb,{dataKey:"value",fill:f.color,radius:[0,4,4,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noPrinterData")})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printDuration")}),e.length>0?a.jsx(Sh,{width:"100%",height:160,children:a.jsxs(W1,{data:u,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(_h,{contentStyle:hk}),a.jsx(Hb,{dataKey:"count",name:r("common.prints"),fill:"#00ae42",radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printHabits")}),a.jsx(bP,{value:o,onChange:l})]}),e.length>0?a.jsx(Sh,{width:"100%",height:160,children:a.jsxs(W1,{data:m,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},unit:v.unit}),a.jsx(_h,{contentStyle:hk,formatter:g=>[`${g??0}${v.unit}`,b]}),a.jsx(Hb,{dataKey:"avg",fill:v.color,radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printTimeOfDay")}),e.length>0?a.jsx(Sh,{width:"100%",height:160,children:a.jsxs(W1,{data:d,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(_h,{contentStyle:hk}),a.jsx(Hb,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),a.jsx(Hb,{dataKey:"failures",name:r("stats.failed"),fill:"#ef4444",radius:[2,2,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]})]})]})}function stt({archives:t,currency:e,dateFrom:n,dateTo:r}){const{t:i}=Lt();return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):a.jsx(Ket,{archives:t,currency:e,dateFrom:n,dateTo:r})}function ott({size:t=1,dateFrom:e,dateTo:n,createdById:r}){const{t:i}=Lt(),s=!!(e||n),{data:o,isLoading:l}=et({queryKey:["failureAnalysis",e,n,r??"all"],queryFn:()=>he.getFailureAnalysis({...s?{dateFrom:e,dateTo:n}:{days:30},createdById:r})});if(l)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!o||o.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i(s?"stats.noPrintDataInRange":"stats.noPrintDataLast30Days")});const c=t===1?5:t===2?8:999,d=Object.entries(o.failures_by_reason).sort(([,p],[,f])=>f-p),u=d.slice(0,c),m=d.length>c;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ln,{className:`w-5 h-5 ${o.failure_rate>20?"text-status-error":o.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[o.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:i("stats.failedPrintsCount",{failed:o.failed_prints,total:o.total_prints})}),o.trend&&o.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(fO,{className:`w-4 h-4 ${o.trend[o.trend.length-1].failure_rate0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?i("stats.failureReasons"):i("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:u.map(([p,f])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:p||i("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:f})]},p))}),m&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("common.more",{count:d.length-c})})]})]})}function ltt({archives:t,currency:e}){const{t:n}=Lt(),r=w.useMemo(()=>{const i=[];if(t.length===0)return i;const s=y=>{let v=null,b=0;return t.forEach(g=>{const _=y(g);_&&_>b&&(b=_,v=g)}),{archive:v,value:b}},o=s(y=>y.actual_time_seconds);o.archive&&i.push({icon:rr,iconColor:"text-blue-400",label:n("stats.longestPrint"),value:ls(o.value),detail:o.archive.print_name||null});const l=s(y=>y.filament_used_grams);l.archive&&i.push({icon:Na,iconColor:"text-orange-400",label:n("stats.heaviestPrint"),value:gh(l.value),detail:l.archive.print_name||null});const c=s(y=>y.cost);c.archive&&i.push({icon:Zk,iconColor:"text-green-400",label:n("stats.mostExpensivePrint"),value:`${e}${c.value.toFixed(2)}`,detail:c.archive.print_name||null});const d=new Map;t.forEach(y=>{const v=Qn(y.created_at)||new Date(y.created_at),b=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`;d.set(b,(d.get(b)||0)+1)});let u="",m=0;d.forEach((y,v)=>{y>m&&(m=y,u=v)}),m>1&&i.push({icon:Wr,iconColor:"text-purple-400",label:n("stats.busiestDay"),value:`${m} ${n("common.prints")}`,detail:(()=>{const[y,v,b]=u.split("-").map(Number);return new Date(y,v-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(y=>y.status==="completed"||y.status==="failed").sort((y,v)=>new Date(v.completed_at||v.created_at).getTime()-new Date(y.completed_at||y.created_at).getTime());let f=0;for(const y of p)if(y.status==="completed")f++;else break;return f>0&&i.push({icon:Xl,iconColor:"text-yellow-400",label:n("stats.successStreak"),value:`${f}`,detail:f===1?n("stats.streakPrint"):n("stats.streakPrints",{count:f})}),i},[t,e,n]);return r.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noArchiveData")}):a.jsx("div",{className:"space-y-3",children:r.map((i,s)=>a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-1.5 rounded-lg bg-bambu-dark ${i.iconColor}`,children:a.jsx(i.icon,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("span",{className:"text-sm font-bold text-white",children:i.value}),i.detail&&a.jsx("span",{className:"text-xs text-bambu-gray truncate",children:i.detail})]})]})]},s))})}function ctt(){const{t}=Lt(),{showToast:e}=xn(),{hasPermission:n,authEnabled:r}=Sr(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(0),[u,m]=w.useState(0),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState(!1),_=r&&n("stats:filter_by_user"),[k,P]=w.useState(()=>{try{const Y=localStorage.getItem("bambusy-stats-timeframe");if(Y){const D=JSON.parse(Y);if(D.preset)return D}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[N,M]=w.useState(!1);w.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(k))},[k]);const T=w.useMemo(()=>k.preset==="custom"?{dateFrom:k.dateFrom,dateTo:k.dateTo}:Qet(k.preset),[k]);w.useEffect(()=>{const Y=()=>{try{const j=localStorage.getItem("bambusy-dashboard-layout-v2");if(j){const z=JSON.parse(j);m(z.hidden?.length||0)}}catch{m(0)}};Y(),window.addEventListener("storage",Y);const D=setInterval(Y,2e3);return()=>{window.removeEventListener("storage",Y),clearInterval(D)}},[c]);const A=y!==null?y:void 0,{data:C,isLoading:F,isFetching:$,refetch:I}=et({queryKey:["archiveStats",T.dateFrom,T.dateTo,A??"all"],queryFn:()=>he.getArchiveStats({dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:A})}),{data:Q}=et({queryKey:["printers"],queryFn:he.getPrinters}),{data:L,isFetching:re,refetch:ae}=et({queryKey:["archivesSlim",T.dateFrom,T.dateTo,A??"all"],queryFn:()=>he.getArchivesSlim(T.dateFrom,T.dateTo,A)}),{data:ee}=et({queryKey:["settings"],queryFn:he.getSettings}),{data:ue}=et({queryKey:["users"],queryFn:he.getUsers,enabled:_}),le=w.useMemo(()=>y===null?t("stats.allUsers","All Users"):y===-1?t("stats.noUser","No User (System)"):ue?.find(Y=>Y.id===y)?.username??"?",[y,ue,t]),de=async Y=>{l(!1),s(!0);try{const{blob:D,filename:j}=await he.exportStats({format:Y,days:90,createdById:A}),z=URL.createObjectURL(D),W=document.createElement("a");W.href=z,W.download=j,W.click(),URL.revokeObjectURL(z),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},K=async()=>{f(!0);try{const Y=await he.recalculateCosts();await Promise.all([I(),ae()]),e(t("stats.recalculatedCosts",{count:Y.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},te=($||re)&&!F,se=yo(ee?.currency||"USD"),be=new Map(Q?.map(Y=>[String(Y.id),Y.name])||[]),Ne=w.useMemo(()=>L?.map(Y=>Y.created_at)||[],[L]);if(F)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const B=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(ett,{stats:C,currency:se}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:Y=>a.jsx(ttt,{stats:C,printerMap:be,size:Y}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:Y=>a.jsx(ntt,{stats:C,printerMap:be,size:Y}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:Y=>a.jsx(ott,{size:Y,dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:A}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:Y=>a.jsx(att,{printDates:Ne,size:Y,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:a.jsx(ltt,{archives:L||[],currency:se}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:a.jsx(itt,{stats:C,archives:L||[],printerMap:be}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(stt,{archives:L||[],currency:se,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),te&&a.jsx(ct,{className:"w-5 h-5 text-bambu-green animate-spin"})]}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Ie,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(Dc,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(Y=>Y+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(jo,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Ie,{variant:"secondary",onClick:K,disabled:p||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(bpe,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eN,{className:"w-4 h-4"}),t("stats.exportStats")]}),o&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>de("csv"),children:[a.jsx(Ms,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>de("xlsx"),children:[a.jsx(eN,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),_&&ue&&ue.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>g(!b),children:[a.jsx(_u,{className:"w-4 h-4"}),le,a.jsx(Fn,{className:"w-3 h-3"})]}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2 max-h-64 overflow-y-auto",children:[a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===null?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(null),g(!1)},children:t("stats.allUsers","All Users")}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===-1?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(-1),g(!1)},children:t("stats.noUser","No User (System)")}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-1"}),ue.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===Y.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(Y.id),g(!1)},children:Y.username},Y.id))]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>M(!N),children:[a.jsx(Wr,{className:"w-4 h-4"}),t(`stats.timeframe.${k.preset}`),a.jsx(Fn,{className:"w-3 h-3"})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>M(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2",children:[Zet.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset===Y?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{P({preset:Y,dateFrom:void 0,dateTo:void 0}),M(!1)},children:t(`stats.timeframe.${Y}`)},Y)),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-2"}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>P(Y=>({...Y,preset:"custom"})),children:t("stats.timeframe.custom")}),k.preset==="custom"&&a.jsxs("div",{className:"mt-2 px-1 pb-1 space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.from")}),a.jsx("input",{type:"date",value:k.dateFrom||"",max:k.dateTo||new Date().toISOString().split("T")[0],onChange:Y=>P(D=>({...D,dateFrom:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.to")}),a.jsx("input",{type:"date",value:k.dateTo||"",min:k.dateFrom,max:new Date().toISOString().split("T")[0],onChange:Y=>P(D=>({...D,dateTo:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsx(Ie,{variant:"primary",onClick:()=>M(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),a.jsx(Xet,{widgets:B,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function lle({summary:t,children:e,defaultOpen:n=!1,className:r="",summaryClassName:i=""}){const[s,o]=w.useState(n);return a.jsxs("div",{className:r,children:[a.jsxs("button",{type:"button",onClick:()=>o(l=>!l),className:`w-full flex items-center justify-between gap-2 text-left ${i}`,"aria-expanded":s,children:[a.jsx("div",{className:"flex-1 min-w-0",children:t}),a.jsx(Fn,{className:`w-4 h-4 text-bambu-gray flex-shrink-0 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsx("div",{className:"mt-3",children:e})]})}function dtt({plug:t,onEdit:e}){const{t:n}=Lt(),r=mn(),{showToast:i}=xn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[d,u]=w.useState(!1),[m,p]=w.useState(!1),{data:f,isLoading:y}=et({queryKey:["smart-plug-status",t.id],queryFn:()=>he.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=et({queryKey:["printers"],queryFn:he.getPrinters}),b=v?.find(F=>F.id===t.printer_id),g=lt({mutationFn:F=>he.controlSmartPlug(t.id,F),onMutate:async F=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const $=r.getQueryData(["smart-plug-status",t.id]),I=F==="on"?"ON":F==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],Q=>({...Q,state:I})),{previousStatus:$}},onError:(F,$,I)=>{I?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],I.previousStatus),i(n("smartPlugs.failedToTurn",{action:$,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=lt({mutationFn:F=>he.updateSmartPlug(t.id,F),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),k=lt({mutationFn:()=>he.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),P=f?.state==="ON",N=t.plug_type==="mqtt"&&f?.energy?.power!==null&&f?.energy?.power!==void 0,M=(f?.reachable??!1)||N,T=g.isPending,C=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const F=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${F}/`:`http://${F}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(Dt,{className:"relative",children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?M?"bg-teal-500/20":"bg-red-500/20":M?P?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(pO,{className:`w-5 h-5 ${M?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Mw,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?a.jsx(yd,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(ql,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.plug_type==="rest"?t.rest_on_url??t.rest_off_url??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.plug_type==="rest"?t.rest_on_url||t.rest_off_url:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[y?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),M&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:M?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?f?.state||"?":n("smartPlugs.offline")})]}):t.plug_type==="rest"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-purple-500/20 text-purple-400 text-[10px] font-medium rounded",children:"REST"}),a.jsx("span",{className:M?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?f?.state||"?":n("smartPlugs.offline")})]}):M?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(vf,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:P?"text-status-ok":"text-bambu-gray",children:f?.state||n("smartPlugs.unknown")})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(Wu,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),C&&a.jsxs("a",{href:C,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[a.jsx(sa,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),b&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("smartPlugs.linkedTo")," "]}),a.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[a.jsx(Dc,{className:"w-3 h-3"}),n("smartPlugs.monitorOnly")]}),t.power_alert_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[a.jsx(Th,{className:"w-3 h-3"}),n("smartPlugs.alerts")]}),t.schedule_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[a.jsx(Wr,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?n("smartPlugs.scheduleOn",{time:t.schedule_on_time}):n("smartPlugs.scheduleOff",{time:t.schedule_off_time})]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Ie,{size:"sm",variant:P?"primary":"secondary",disabled:!M||T,onClick:()=>c(!0),className:"flex-1",children:[T?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(am,{className:"w-4 h-4"}),n("smartPlugs.on")]}),a.jsxs(Ie,{size:"sm",variant:P?"secondary":"primary",disabled:!M||T,onClick:()=>u(!0),className:"flex-1",children:[T?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Rw,{className:"w-4 h-4"}),n("smartPlugs.off")]})]}),t.plug_type==="mqtt"&&f?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[f.energy.power!==null&&f.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(f.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.power")})]}),f.energy.today!==null&&f.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:f.energy.today.toFixed(3)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.kwhToday")})]})]}),a.jsxs("button",{onClick:()=>p(!m),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Nd,{className:"w-4 h-4"}),t.plug_type==="mqtt"?n("smartPlugs.settings"):n("smartPlugs.automationSettings")]}),a.jsx("span",{children:m?"-":"+"})]}),m&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:F=>_.mutate({show_in_switchbar:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.enableAutomation")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:F=>_.mutate({enabled:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOn")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOnDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:F=>_.mutate({auto_on:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOff")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:F=>_.mutate({auto_off:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOffPersistent")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffPersistentDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off_persistent,onChange:F=>_.mutate({auto_off_persistent:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:n("smartPlugs.turnOffDelayMode")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(rr,{className:"w-4 h-4"}),n("smartPlugs.time")]}),a.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(PP,{className:"w-4 h-4"}),n("smartPlugs.temp")]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.delayMinutes")}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:F=>_.mutate({off_delay_minutes:parseInt(F.target.value)||5}),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"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.tempThreshold")}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:F=>_.mutate({off_temp_threshold:parseInt(F.target.value)||70}),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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.tempThresholdDescription")})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bh,{className:"w-4 h-4"}),n("smartPlugs.edit")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(kn,{title:n("smartPlugs.deleteSmartPlug"),message:n("smartPlugs.deleteConfirm",{name:t.name}),confirmText:n("smartPlugs.delete"),variant:"danger",onConfirm:()=>{k.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(kn,{title:n("smartPlugs.turnOnSmartPlug"),message:n("smartPlugs.turnOnConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{g.mutate("on"),c(!1)},onCancel:()=>c(!1)}),d&&a.jsx(kn,{title:n("smartPlugs.turnOffSmartPlug"),message:n("smartPlugs.turnOffConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{g.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function utt({plug:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[d,u]=w.useState(t?.ip_address||""),[m,p]=w.useState(t?.username||""),[f,y]=w.useState(t?.password||""),[v,b]=w.useState(t?.ha_entity_id||""),[g,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[k,P]=w.useState(t?.mqtt_power_path||""),[N,M]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[T,A]=w.useState(t?.mqtt_energy_topic||""),[C,F]=w.useState(t?.mqtt_energy_path||""),[$,I]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[Q,L]=w.useState(t?.mqtt_state_topic||""),[re,ae]=w.useState(t?.mqtt_state_path||""),[ee,ue]=w.useState(t?.mqtt_state_on_value||""),[le,de]=w.useState(t?.rest_on_url||""),[K,te]=w.useState(t?.rest_on_body||""),[se,be]=w.useState(t?.rest_off_url||""),[Ne,B]=w.useState(t?.rest_off_body||""),[Y,D]=w.useState(t?.rest_method||"POST"),[j,z]=w.useState(t?.rest_headers||""),[W,q]=w.useState(t?.rest_status_url||""),[ce,O]=w.useState(t?.rest_status_path||""),[G,X]=w.useState(t?.rest_status_on_value||""),[V,J]=w.useState(t?.rest_power_url||""),[ie,me]=w.useState(t?.rest_power_path||""),[pe,oe]=w.useState((t?.rest_power_multiplier??1).toString()),[U,R]=w.useState(t?.rest_energy_url||""),[ne,xe]=w.useState(t?.rest_energy_path||""),[Se,ye]=w.useState((t?.rest_energy_multiplier??1).toString()),[ve,fe]=w.useState(t?.ha_power_entity||""),[ke,Ee]=w.useState(t?.ha_energy_today_entity||""),[Ae,_e]=w.useState(t?.ha_energy_total_entity||""),[je,Be]=w.useState(""),[Re,Ye]=w.useState(""),[we,$e]=w.useState(!1),De=w.useRef(null),[Xe,Ve]=w.useState(""),[Te,Me]=w.useState(!1),qe=w.useRef(null),[tt,ut]=w.useState(""),[xt,wt]=w.useState(!1),Ht=w.useRef(null),[Xt,Kt]=w.useState(""),[Ut,en]=w.useState(!1),We=w.useRef(null),[Ft,Nt]=w.useState(t?.printer_id||null),[ht,Mt]=w.useState(null),[Qt,Wt]=w.useState(null),[ze,dt]=w.useState(t?.power_alert_enabled||!1),[pt,Fe]=w.useState(t?.power_alert_high?.toString()||""),[Le,at]=w.useState(t?.power_alert_low?.toString()||""),[Pe,Ge]=w.useState(t?.schedule_enabled||!1),[Ke,Qe]=w.useState(t?.schedule_on_time||""),[Ze,rt]=w.useState(t?.schedule_off_time||""),[bt,Pt]=w.useState(t?.show_in_switchbar||!1),[vt,He]=w.useState(t?.show_on_printer_card??!0),[St,Ct]=w.useState(!1),[Zt,Jt]=w.useState({scanned:0,total:0}),[Nn,vn]=w.useState([]),yn=w.useRef(null),{data:an}=et({queryKey:["printers"],queryFn:he.getPrinters}),{data:rn}=et({queryKey:["smart-plugs"],queryFn:he.getSmartPlugs}),{data:bn}=et({queryKey:["settings"],queryFn:he.getSettings}),Gn=!!(bn?.ha_enabled&&bn?.ha_url&&bn?.ha_token);w.useEffect(()=>{const jt=setTimeout(()=>{Ye(je)},300);return()=>clearTimeout(jt)},[je]),w.useEffect(()=>{const jt=Wn=>{De.current&&!De.current.contains(Wn.target)&&$e(!1),qe.current&&!qe.current.contains(Wn.target)&&Me(!1),Ht.current&&!Ht.current.contains(Wn.target)&&wt(!1),We.current&&!We.current.contains(Wn.target)&&en(!1)};return document.addEventListener("mousedown",jt),()=>document.removeEventListener("mousedown",jt)},[]);const{data:ar,isLoading:On,error:mi}=et({queryKey:["ha-entities",Re],queryFn:()=>he.getHAEntities(Re||void 0),enabled:s==="homeassistant"&&Gn,retry:!1,staleTime:0}),{data:Rn}=et({queryKey:["ha-sensor-entities"],queryFn:he.getHASensorEntities,enabled:s==="homeassistant"&&Gn,retry:!1,staleTime:0});w.useEffect(()=>{const jt=Wn=>{Wn.key==="Escape"&&e()};return window.addEventListener("keydown",jt),()=>{window.removeEventListener("keydown",jt),yn.current&&clearInterval(yn.current)}},[e]);const na=async()=>{Ct(!0),vn([]),Jt({scanned:0,total:0}),Wt(null);try{await he.startTasmotaScan();const jt=async()=>{try{const Wn=await he.getTasmotaScanStatus();Jt({scanned:Wn.scanned,total:Wn.total});const En=await he.getDiscoveredTasmotaDevices();vn(En),Wn.running||(Ct(!1),yn.current&&(clearInterval(yn.current),yn.current=null))}catch(Wn){console.error("Polling error:",Wn)}};await jt(),yn.current=setInterval(jt,500)}catch(jt){Ct(!1);const Wn=jt instanceof Error?jt.message:typeof jt=="string"?jt:JSON.stringify(jt);Wt(Wn||n("smartPlugs.failedToStartScan"))}},ra=async()=>{try{await he.stopTasmotaScan()}catch{}Ct(!1),yn.current&&(clearInterval(yn.current),yn.current=null)},jr=jt=>{u(jt.ip_address),c(jt.name),Mt(null)},In=lt({mutationFn:()=>he.testSmartPlugConnection(d,m||null,f||null),onSuccess:jt=>{Mt(jt),Wt(null),!l&&jt.device_name&&c(jt.device_name)},onError:jt=>{Mt(null),Wt(jt.message)}}),Bi=lt({mutationFn:jt=>he.createSmartPlug(jt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:jt=>{Wt(jt.message)}}),Hi=lt({mutationFn:jt=>he.updateSmartPlug(t.id,jt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:jt=>{Wt(jt.message)}}),Ci=an?.filter(jt=>s==="tasmota"?!rn?.some(En=>En.printer_id===jt.id&&En.id!==t?.id&&En.plug_type==="tasmota"):!0),Hc=jt=>{if(jt.preventDefault(),Wt(null),!l.trim()){Wt(n("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Wt("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Wt(n("smartPlugs.entityRequired"));return}if(s==="mqtt"){const En=g.trim(),Vt=T.trim(),sc=Q.trim();if(!En&&!Vt&&!sc){Wt(n("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!le.trim()&&!se.trim()){Wt(n("smartPlugs.restUrlRequired"));return}const Wn={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?d.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&ve||null,ha_energy_today_entity:s==="homeassistant"&&ke||null,ha_energy_total_entity:s==="homeassistant"&&Ae||null,mqtt_power_topic:s==="mqtt"&&g.trim()||null,mqtt_power_path:s==="mqtt"&&k.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(N)||1,mqtt_energy_topic:s==="mqtt"&&T.trim()||null,mqtt_energy_path:s==="mqtt"&&C.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat($)||1,mqtt_state_topic:s==="mqtt"&&Q.trim()||null,mqtt_state_path:s==="mqtt"&&re.trim()||null,mqtt_state_on_value:s==="mqtt"&&ee.trim()||null,rest_on_url:s==="rest"&&le.trim()||null,rest_on_body:s==="rest"&&K.trim()||null,rest_off_url:s==="rest"&&se.trim()||null,rest_off_body:s==="rest"&&Ne.trim()||null,rest_method:s==="rest"?Y:null,rest_headers:s==="rest"&&j.trim()||null,rest_status_url:s==="rest"&&W.trim()||null,rest_status_path:s==="rest"&&ce.trim()||null,rest_status_on_value:s==="rest"&&G.trim()||null,rest_power_url:s==="rest"&&V.trim()||null,rest_power_path:s==="rest"&&ie.trim()||null,rest_power_multiplier:s==="rest"&&parseFloat(pe)||1,rest_energy_url:s==="rest"&&U.trim()||null,rest_energy_path:s==="rest"&&ne.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(Se)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:Ft,power_alert_enabled:ze,power_alert_high:pt?parseFloat(pt):null,power_alert_low:Le?parseFloat(Le):null,schedule_enabled:Pe,schedule_on_time:Ke||null,schedule_off_time:Ze||null,show_in_switchbar:bt,show_on_printer_card:vt};i?Hi.mutate(Wn):Bi.mutate(Wn)},pa=Bi.isPending||Hi.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:jt=>jt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"smartPlugs.editTitle":"smartPlugs.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Hc,className:"p-6 space-y-4 overflow-y-auto",children:[Qt&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Qt}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(ql,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(Mw,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(pO,{className:"w-4 h-4"}),"MQTT"]}),a.jsxs("button",{type:"button",onClick:()=>{o("rest"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="rest"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(yd,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[St?a.jsxs(Ie,{type:"button",variant:"secondary",onClick:ra,className:"w-full",children:[a.jsx(Bt,{className:"w-4 h-4"}),n("smartPlugs.stopScanning")]}):a.jsxs(Ie,{type:"button",variant:"primary",onClick:na,className:"w-full",children:[a.jsx(Cr,{className:"w-4 h-4"}),n("smartPlugs.discoverTasmota")]}),St&&Zt.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Zt.scanned," / ",Zt.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Zt.scanned/Zt.total*100}%`}})})]}),Nn.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.foundDevices",{count:Nn.length})}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Nn.map(jt=>a.jsxs("button",{type:"button",onClick:()=>jr(jt),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ql,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:jt.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:jt.ip_address})]})]}),jt.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${jt.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(am,{className:"w-3 h-3"}),jt.state]})]},jt.ip_address))})]}),!St&&Nn.length===0&&Zt.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:n("smartPlugs.noDevicesFound")})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!Gn&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.haNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.haSettingsPath")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:n("smartPlugs.selectEntity")}),a.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),Gn&&a.jsxs(a.Fragment,{children:[On&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),n("smartPlugs.loadingEntities")]}),mi&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:n("smartPlugs.failedToLoadEntities",{error:mi.message})}),(()=>{const jt=rn?.filter(Vt=>Vt.ha_entity_id&&Vt.id!==t?.id).map(Vt=>Vt.ha_entity_id)||[],Wn=(ar||[]).filter(Vt=>!jt.includes(Vt.entity_id)),En=ar?.find(Vt=>Vt.entity_id===v);return a.jsxs("div",{ref:De,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.selectEntity")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:we?je:En?`${En.friendly_name} (${En.entity_id})`:"",onChange:Vt=>{Be(Vt.target.value),we||$e(!0)},onFocus:()=>{$e(!0),Be("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),v&&!we&&a.jsx("button",{type:"button",onClick:()=>{b(""),Be("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),On&&a.jsx(ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),we&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[On&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("smartPlugs.loading")]}),!On&&Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Re?n("smartPlugs.noEntitiesMatching",{search:Re}):n("smartPlugs.noEntitiesAvailable")}),!On&&Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{b(Vt.entity_id),$e(!1),Be(""),l||c(Vt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Vt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:Vt.entity_id}),a.jsx("span",{className:Vt.state==="on"?"text-bambu-green":"",children:Vt.state})]})]},Vt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re?n("smartPlugs.searchingEntities",{count:Wn.length}):n("smartPlugs.showingEntities",{count:Wn.length})})]})})(),v&&Rn&&Rn.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:n("smartPlugs.energyMonitoringOptional")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:n("smartPlugs.energyMonitoringHint")})]}),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="W"||Vt.unit_of_measurement==="kW"||Vt.unit_of_measurement==="mW"),Wn=Xe?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(Xe.toLowerCase())||Vt.friendly_name.toLowerCase().includes(Xe.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===ve);return a.jsxs("div",{ref:qe,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.powerSensorW")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:Te?Xe:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{Ve(Vt.target.value),Te||Me(!0)},onFocus:()=>{Me(!0),Ve("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ve&&!Te&&a.jsx("button",{type:"button",onClick:()=>{fe(""),Ve("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Te&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{fe(""),Me(!1),Ve("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{fe(Vt.entity_id),Me(!1),Ve("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===ve?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="kWh"||Vt.unit_of_measurement==="Wh"||Vt.unit_of_measurement==="MWh"),Wn=tt?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(tt.toLowerCase())||Vt.friendly_name.toLowerCase().includes(tt.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===ke);return a.jsxs("div",{ref:Ht,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.energyTodayKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:xt?tt:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{ut(Vt.target.value),xt||wt(!0)},onFocus:()=>{wt(!0),ut("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ke&&!xt&&a.jsx("button",{type:"button",onClick:()=>{Ee(""),ut("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),xt&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{Ee(""),wt(!1),ut("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{Ee(Vt.entity_id),wt(!1),ut("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===ke?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="kWh"||Vt.unit_of_measurement==="Wh"||Vt.unit_of_measurement==="MWh"),Wn=Xt?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(Xt.toLowerCase())||Vt.friendly_name.toLowerCase().includes(Xt.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===Ae);return a.jsxs("div",{ref:We,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.totalEnergyKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:Ut?Xt:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{Kt(Vt.target.value),Ut||en(!0)},onFocus:()=>{en(!0),Kt("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Ae&&!Ut&&a.jsx("button",{type:"button",onClick:()=>{_e(""),Kt("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Ut&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{_e(""),en(!1),Kt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{_e(Vt.entity_id),en(!1),Kt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===Ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!bn?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.mqttNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.mqttSettingsPath")})," ",n("smartPlugs.mqttNotConfiguredSuffix")]}),bn?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:n("smartPlugs.monitorOnly")}),a.jsx("p",{className:"text-xs opacity-80",children:n("smartPlugs.mqttMonitorOnlyDescription")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.powerMonitoring")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:g,onChange:jt=>_(jt.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:k,onChange:jt=>P(jt.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:N,onChange:jt=>M(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttPowerHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:T,onChange:jt=>A(jt.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:C,onChange:jt=>F(jt.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:$,onChange:jt=>I(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttEnergyHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:Q,onChange:jt=>L(jt.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:re,onChange:jt=>ae(jt.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.onValue")}),a.jsx("input",{type:"text",value:ee,onChange:jt=>ue(jt.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttStateHint")})]})]})]}),s==="rest"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.restControl")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restMethod")}),a.jsxs("select",{value:Y,onChange:jt=>D(jt.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"GET",children:"GET"}),a.jsx("option",{value:"POST",children:"POST"}),a.jsx("option",{value:"PUT",children:"PUT"}),a.jsx("option",{value:"PATCH",children:"PATCH"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOnUrl")}),a.jsx("input",{type:"text",value:le,onChange:jt=>{de(jt.target.value),Mt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOnBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:K,onChange:jt=>te(jt.target.value),placeholder:n("smartPlugs.restBodyHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOffUrl")}),a.jsx("input",{type:"text",value:se,onChange:jt=>{be(jt.target.value),Mt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOffBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:Ne,onChange:jt=>B(jt.target.value),placeholder:n("smartPlugs.restBodyHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.restHeaders")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("div",{children:a.jsx("textarea",{value:j,onChange:jt=>z(jt.target.value),placeholder:n("smartPlugs.restHeadersHint"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none font-mono text-sm"})})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusUrl")}),a.jsx("input",{type:"text",value:W,onChange:jt=>q(jt.target.value),placeholder:n("smartPlugs.restStatusHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusPath")}),a.jsx("input",{type:"text",value:ce,onChange:jt=>O(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusOnValue")}),a.jsx("input",{type:"text",value:G,onChange:jt=>X(jt.target.value),placeholder:"ON",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restPowerUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:V,onChange:jt=>J(jt.target.value),placeholder:n("smartPlugs.restPowerUrlHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerPath")}),a.jsx("input",{type:"text",value:ie,onChange:jt=>me(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerMultiplier")}),a.jsx("input",{type:"text",value:pe,onChange:jt=>oe(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restEnergyUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:U,onChange:jt=>R(jt.target.value),placeholder:n("smartPlugs.restEnergyUrlHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyPath")}),a.jsx("input",{type:"text",value:ne,onChange:jt=>xe(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyMultiplier")}),a.jsx("input",{type:"text",value:Se,onChange:jt=>ye(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.restEnergyHint")})]}),(le.trim()||se.trim())&&a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ie,{type:"button",variant:"secondary",onClick:async()=>{Mt(null);try{const jt=le.trim()||se.trim(),Wn=await he.testRESTConnection(jt,Y,j.trim()||null);Mt({success:Wn.success}),Wn.success||Wt(Wn.error||n("smartPlugs.addSmartPlug.connectionFailed"))}catch{Mt({success:!1}),Wt(n("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[a.jsx(vf,{className:"w-4 h-4"}),n("smartPlugs.testConnection")]})}),ht&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${ht.success?"text-green-400":"text-red-400"}`,children:[ht.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx(Wu,{className:"w-4 h-4"}),ht.success?n("smartPlugs.connectionSuccess"):n("smartPlugs.addSmartPlug.connectionFailed")]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.ipAddress")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:d,onChange:jt=>{u(jt.target.value),Mt(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs(Ie,{type:"button",variant:"secondary",onClick:()=>In.mutate(),disabled:!d.trim()||In.isPending,children:[In.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vf,{className:"w-4 h-4"}),n("smartPlugs.test")]})]})]}),s==="tasmota"&&ht&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ht.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:ht.success?a.jsxs(a.Fragment,{children:[a.jsx(fr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:n("smartPlugs.connectedResult")}),a.jsxs("p",{className:"text-sm opacity-80",children:[ht.device_name&&n("smartPlugs.deviceLabel",{name:ht.device_name}),n("smartPlugs.stateLabel",{state:ht.state})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Wu,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.nameLabel")}),a.jsx("input",{type:"text",value:l,onChange:jt=>c(jt.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),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"})]}),s==="tasmota"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.username")}),a.jsx("input",{type:"text",value:m,onChange:jt=>p(jt.target.value),placeholder:"admin",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.password")}),a.jsx("input",{type:"password",value:f,onChange:jt=>y(jt.target.value),placeholder:"********",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:n("smartPlugs.authHint")})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.linkToPrinter")}),a.jsxs("select",{value:Ft??"",onChange:jt=>Nt(jt.target.value?Number(jt.target.value):null),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:[a.jsx("option",{value:"",children:n("smartPlugs.noPrinter")}),Ci?.map(jt=>a.jsx("option",{value:jt.id,children:jt.name},jt.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.linkingDescription")})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.powerAlerts")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ze,onChange:jt=>dt(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ze&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertAbove")}),a.jsx("input",{type:"number",value:pt,onChange:jt=>Fe(jt.target.value),placeholder:"e.g. 200",min:"0",max:"5000",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertBelow")}),a.jsx("input",{type:"number",value:Le,onChange:jt=>at(jt.target.value),placeholder:"e.g. 10",min:"0",max:"5000",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.alertDescription")})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.dailySchedule")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Pe,onChange:jt=>Ge(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Pe&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOnAt")}),a.jsx("input",{type:"time",value:Ke,onChange:jt=>Qe(jt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOffAt")}),a.jsx("input",{type:"time",value:Ze,onChange:jt=>rt(jt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.scheduleDescription")})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:bt,onChange:jt=>Pt(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Dc,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showOnPrinterCard")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.displayOnPrinterCard")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:vt,onChange:jt=>He(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("smartPlugs.cancel")}),a.jsxs(Ie,{type:"submit",disabled:pa,className:"flex-1",children:[pa?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),n(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function Vn({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:a.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}function mtt({provider:t,onEdit:e}){const{t:n}=Lt(),r=mn(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(null),{data:u}=et({queryKey:["printers"],queryFn:he.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=lt({mutationFn:b=>he.updateNotificationProvider(t.id,b),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=lt({mutationFn:()=>he.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),y=lt({mutationFn:()=>he.testNotificationProvider(t.id),onSuccess:b=>{d(b),r.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{d({success:!1,message:b.message})}}),v=b=>b||"";return a.jsxs(a.Fragment,{children:[a.jsx(Dt,{className:"relative",children:a.jsxs(Rt,{className:"p-3",children:[a.jsxs("div",{className:`flex items-start justify-between ${t.enabled?"mb-3":"mb-0"}`,children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(Th,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n(`notifications.providerTypes.${t.provider_type}`,t.provider_type)})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsx("span",{className:"text-xs text-status-ok hidden sm:inline",children:n("notifications.lastSuccess",{date:Uf(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Qn(t.last_error_at)?.getTime()||0)>(Qn(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:n("notifications.error")}),a.jsx(Vn,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]})]}),t.enabled&&a.jsxs(a.Fragment,{children:[m&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("notifications.printer")," "]}),a.jsx("span",{className:"text-sm text-white",children:m.name})]}),!m&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.allPrinters")})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:n("notifications.start")}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:n("notifications.plateCheck")}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:n("notifications.complete")}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:n("notifications.failed")}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:n("notifications.stopped")}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:n("notifications.progress")}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:n("notifications.offline")}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:n("notifications.error")}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:n("notifications.lowFilament")}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:n("notifications.maintenance")}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:n("notifications.amsHumidity")}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:n("notifications.amsTemp")}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:n("notifications.amsHtHumidity")}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:n("notifications.amsHtTemp")}),t.on_bed_cooled&&a.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:n("notifications.bedCooled")}),t.on_first_layer_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-emerald-600/20 text-emerald-300 text-xs rounded",children:n("notifications.firstLayer")}),t.on_print_missing_spool_assignment&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-500/20 text-amber-300 text-xs rounded",children:n("notifications.missingSpoolAssignmentLabel")}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(aN,{className:"w-3 h-3"}),n("notifications.quiet")]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(Wr,{className:"w-3 h-3"}),n("notifications.digest",{time:t.daily_digest_time})]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Ie,{size:"sm",variant:"secondary",disabled:y.isPending,onClick:()=>{d(null),y.mutate()},className:"w-full",children:[y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),n("notifications.sendTestNotification")]})}),c&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${c.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[c.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx($a,{className:"w-4 h-4"}),a.jsx("span",{children:c.message})]})]}),a.jsxs("button",{onClick:()=>l(!o),className:`w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors ${t.enabled?"border-t border-bambu-dark-tertiary":"mt-2 border-t border-bambu-dark-tertiary"}`,children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Nd,{className:"w-4 h-4"}),n("notifications.eventSettings")]}),o?a.jsx(Yl,{className:"w-4 h-4"}):a.jsx(Fn,{className:"w-4 h-4"})]}),o&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.sendFromProvider")})]}),a.jsx(Vn,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printEvents")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStarted")}),a.jsx(Vn,{checked:t.on_print_start,onChange:b=>p.mutate({on_print_start:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.plateNotEmpty")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.plateNotEmptyDescription")})]}),a.jsx(Vn,{checked:t.on_plate_not_empty??!0,onChange:b=>p.mutate({on_plate_not_empty:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printCompleted")}),a.jsx(Vn,{checked:t.on_print_complete,onChange:b=>p.mutate({on_print_complete:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.bedCooledLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.bedCooledDescription")})]}),a.jsx(Vn,{checked:t.on_bed_cooled??!1,onChange:b=>p.mutate({on_bed_cooled:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(Vn,{checked:t.on_first_layer_complete??!1,onChange:b=>p.mutate({on_first_layer_complete:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.missingSpoolAssignmentLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.missingSpoolAssignmentDescription")})]}),a.jsx(Vn,{checked:t.on_print_missing_spool_assignment??!1,onChange:b=>p.mutate({on_print_missing_spool_assignment:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printFailed")}),a.jsx(Vn,{checked:t.on_print_failed,onChange:b=>p.mutate({on_print_failed:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStopped")}),a.jsx(Vn,{checked:t.on_print_stopped,onChange:b=>p.mutate({on_print_stopped:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.progressMilestones")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.progressMilestonesDescription")})]}),a.jsx(Vn,{checked:t.on_print_progress,onChange:b=>p.mutate({on_print_progress:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerOffline")}),a.jsx(Vn,{checked:t.on_printer_offline,onChange:b=>p.mutate({on_printer_offline:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerError")}),a.jsx(Vn,{checked:t.on_printer_error,onChange:b=>p.mutate({on_printer_error:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.lowFilamentLabel")}),a.jsx(Vn,{checked:t.on_filament_low,onChange:b=>p.mutate({on_filament_low:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.maintenanceDue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.maintenanceDueDescription")})]}),a.jsx(Vn,{checked:t.on_maintenance_due??!1,onChange:b=>p.mutate({on_maintenance_due:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHumidityHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_humidity_high??!1,onChange:b=>p.mutate({on_ams_humidity_high:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsTemperatureHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_temperature_high??!1,onChange:b=>p.mutate({on_ams_temperature_high:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsHtAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtHumidityHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>p.mutate({on_ams_ht_humidity_high:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtTemperatureHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>p.mutate({on_ams_ht_temperature_high:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printQueue")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAdded")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAddedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_added??!1,onChange:b=>p.mutate({on_queue_job_added:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAssigned")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAssignedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_assigned??!1,onChange:b=>p.mutate({on_queue_job_assigned:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobStarted")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobStartedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_started??!1,onChange:b=>p.mutate({on_queue_job_started:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobWaiting")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobWaitingDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_waiting??!0,onChange:b=>p.mutate({on_queue_job_waiting:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobSkipped")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobSkippedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_skipped??!0,onChange:b=>p.mutate({on_queue_job_skipped:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobFailed")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobFailedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_failed??!0,onChange:b=>p.mutate({on_queue_job_failed:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.queueComplete")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.queueCompleteDescription")})]}),a.jsx(Vn,{checked:t.on_queue_completed??!1,onChange:b=>p.mutate({on_queue_completed:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(aN,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.quietHours")})]}),a.jsx(Vn,{checked:t.quiet_hours_enabled,onChange:b=>p.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.noNotificationsDuring")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[v(t.quiet_hours_start)||"22:00"," - ",v(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeQuietHours")})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wr,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.dailyDigest")})]}),a.jsx(Vn,{checked:t.daily_digest_enabled,onChange:b=>p.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:n("notifications.sendAt",{time:v(t.daily_digest_time)||"08:00"})})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeDigestTime")})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bh,{className:"w-4 h-4"}),n("notifications.edit")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})}),i&&a.jsx(kn,{title:n("notifications.deleteProvider"),message:n("notifications.deleteConfirm",{name:t.name}),confirmText:n("notifications.delete"),variant:"danger",onConfirm:()=>{f.mutate(),s(!1)},onCancel:()=>s(!1)})]})}const htt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function ptt({provider:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.provider_type||"email"),[d,u]=w.useState(t?.printer_id||null),[m,p]=w.useState(t?.quiet_hours_enabled||!1),[f,y]=w.useState(t?.quiet_hours_start||"22:00"),[v,b]=w.useState(t?.quiet_hours_end||"07:00"),[g,_]=w.useState(t?.daily_digest_enabled||!1),[k,P]=w.useState(t?.daily_digest_time||"08:00"),[N,M]=w.useState(t?.on_print_start??!1),[T,A]=w.useState(t?.on_print_complete??!0),[C,F]=w.useState(t?.on_print_failed??!0),[$,I]=w.useState(t?.on_print_stopped??!0),[Q,L]=w.useState(t?.on_print_progress??!1),[re,ae]=w.useState(t?.on_printer_offline??!1),[ee,ue]=w.useState(t?.on_printer_error??!1),[le,de]=w.useState(t?.on_filament_low??!1),[K,te]=w.useState(t?.on_maintenance_due??!1),[se,be]=w.useState(t?.on_bed_cooled??!1),[Ne,B]=w.useState(t?.on_first_layer_complete??!1),[Y,D]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([oe,U])=>[oe,String(U)])):{}),[j,z]=w.useState(null),[W,q]=w.useState(null),{data:ce}=et({queryKey:["printers"],queryFn:he.getPrinters});w.useEffect(()=>{const oe=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[e]);const O=lt({mutationFn:()=>he.testNotificationConfig({provider_type:l,config:Y}),onSuccess:oe=>{z(oe),q(null)},onError:oe=>{z({success:!1,message:oe.message})}}),G=lt({mutationFn:oe=>he.createNotificationProvider(oe),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:oe=>{q(oe.message)}}),X=lt({mutationFn:oe=>he.updateNotificationProvider(t.id,oe),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:oe=>{q(oe.message)}}),V=oe=>{if(oe.preventDefault(),q(null),!s.trim()){q(n("notifications.nameRequired"));return}const U=me(l);for(const ne of U)if(!Y[ne.key]?.trim()){q(n("notifications.fieldRequired",{field:ne.label}));return}const R={name:s.trim(),provider_type:l,config:Y,printer_id:d,quiet_hours_enabled:m,quiet_hours_start:m?f:null,quiet_hours_end:m?v:null,daily_digest_enabled:g,daily_digest_time:g?k:null,on_print_start:N,on_print_complete:T,on_print_failed:C,on_print_stopped:$,on_print_progress:Q,on_printer_offline:re,on_printer_error:ee,on_filament_low:le,on_maintenance_due:K,on_bed_cooled:se,on_first_layer_complete:Ne};i?X.mutate(R):G.mutate(R)},J=G.isPending||X.isPending,ie=oe=>{switch(oe){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:U=>U.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:U=>U.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},me=oe=>ie(oe).filter(U=>U.required),pe=ie(l);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:oe=>oe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"notifications.editTitle":"notifications.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:V,className:"p-6 space-y-4",children:[W&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:W}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.nameLabel")}),a.jsx("input",{type:"text",value:s,onChange:oe=>o(oe.target.value),placeholder:n("notifications.namePlaceholder"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.providerTypeLabel")}),a.jsx("select",{value:l,onChange:oe=>{c(oe.target.value),D({}),z(null)},disabled:i,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 disabled:opacity-50",children:htt.map(oe=>a.jsx("option",{value:oe,children:n(`notifications.providerTypes.${oe}`,oe)},oe))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n(`notifications.providerDescriptions.${l}`,"")})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.configuration")}),pe.filter(oe=>!("showIf"in oe)||oe.showIf?.(Y)!==!1).map(oe=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[oe.label," ",oe.required&&"*"]}),oe.type==="select"&&"options"in oe&&oe.options?a.jsx("select",{value:Y[oe.key]||oe.options[0]?.value||"",onChange:U=>{D({...Y,[oe.key]:U.target.value}),z(null)},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:oe.options.map(U=>a.jsx("option",{value:U.value,children:U.label},U.value))}):a.jsx("input",{type:oe.type,value:Y[oe.key]||"",onChange:U=>{D({...Y,[oe.key]:U.target.value}),z(null)},placeholder:oe.placeholder,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"})]},oe.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ie,{type:"button",variant:"secondary",onClick:()=>{z(null),O.mutate()},disabled:O.isPending||me(l).length>0&&!Y[me(l)[0]?.key],className:"flex-1",children:[O.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),n("notifications.testConfiguration")]})}),j&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${j.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:j.success?a.jsxs(a.Fragment,{children:[a.jsx(fr,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]}):a.jsxs(a.Fragment,{children:[a.jsx($a,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.printerFilter")}),a.jsxs("select",{value:d??"",onChange:oe=>u(oe.target.value?Number(oe.target.value):null),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:[a.jsx("option",{value:"",children:n("notifications.allPrinters")}),ce?.map(oe=>a.jsx("option",{value:oe.id,children:oe.name},oe.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.onlyFromPrinter")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.quietHoursDnd")}),a.jsx(Vn,{checked:m,onChange:p})]}),m&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietStart")}),a.jsx("input",{type:"time",value:f,onChange:oe=>y(oe.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietEnd")}),a.jsx("input",{type:"time",value:v,onChange:oe=>b(oe.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"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.dailyDigestLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")})]}),a.jsx(Vn,{checked:g,onChange:_})]}),g&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.sendDigestAt")}),a.jsx("input",{type:"time",value:k,onChange:oe=>P(oe.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.digestCollected")})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.notificationEvents")}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printEvents")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.start")}),a.jsx(Vn,{checked:N,onChange:M})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.complete")}),a.jsx(Vn,{checked:T,onChange:A})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.failed")}),a.jsx(Vn,{checked:C,onChange:F})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.stopped")}),a.jsx(Vn,{checked:$,onChange:I})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.progress")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.progressPercent")})]}),a.jsx(Vn,{checked:Q,onChange:L})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.bedCooled")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.bedCooledAfterPrint")})]}),a.jsx(Vn,{checked:se,onChange:be})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(Vn,{checked:Ne,onChange:B})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.offline")}),a.jsx(Vn,{checked:re,onChange:ae})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.error")}),a.jsx(Vn,{checked:ee,onChange:ue})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.lowFilament")}),a.jsx(Vn,{checked:le,onChange:de})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.maintenance")}),a.jsx(Vn,{checked:K,onChange:te})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("notifications.cancel")}),a.jsxs(Ie,{type:"submit",disabled:J,className:"flex-1",children:[J?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),n(i?"notifications.save":"notifications.add")]})]})]})]})})}function ftt({template:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=w.useRef(null),[s,o]=w.useState(t.title_template),[l,c]=w.useState(t.body_template),[d,u]=w.useState(null),[m,p]=w.useState(!0),{data:f}=et({queryKey:["template-variables"],queryFn:he.getTemplateVariables}),y=f?.find(M=>M.event_type===t.event_type),{data:v,isLoading:b}=et({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>he.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});w.useEffect(()=>{const M=T=>{T.key==="Escape"&&e()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e]);const g=lt({mutationFn:M=>he.updateNotificationTemplate(t.id,M),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:M=>{u(M.message)}}),_=lt({mutationFn:()=>he.resetNotificationTemplate(t.id),onSuccess:M=>{o(M.title_template),c(M.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:M=>{u(M.message)}}),k=M=>{if(M.preventDefault(),u(null),!s.trim()){u(n("notifications.titleRequired"));return}if(!l.trim()){u(n("notifications.bodyRequired"));return}g.mutate({title_template:s,body_template:l})},P=M=>{const T=i.current;if(!T)return;const A=T.selectionStart,C=T.selectionEnd,F=l,$=F.substring(0,A),I=F.substring(C),Q=$+`{${M}}`+I;c(Q),setTimeout(()=>{T.focus();const L=A+M.length+2;T.setSelectionRange(L,L)},0)},N=s!==t.title_template||l!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("notifications.editTemplate",{name:t.name})}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:k,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[d&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:d}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.titleLabel")}),a.jsx("input",{type:"text",value:s,onChange:M=>o(M.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:n("notifications.titlePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.bodyLabel")}),a.jsx("textarea",{ref:i,value:l,onChange:M=>c(M.target.value),rows:4,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none",placeholder:n("notifications.bodyPlaceholder")})]}),y&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:n("notifications.availableVariables")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:y.variables.map(M=>a.jsxs("button",{type:"button",onClick:()=>P(M),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(ur,{className:"w-3 h-3"}),M]},M))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:n("notifications.clickToInsert")})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(Dc,{className:"w-4 h-4"}),n("notifications.livePreview")]}),a.jsx("button",{type:"button",onClick:()=>p(!m),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:n(m?"notifications.hide":"notifications.show")})]}),m&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("notifications.loadingPreview")]}):v?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.titlePreview")}),a.jsx("div",{className:"text-white font-medium",children:v.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.bodyPreview")}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:v.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:n("notifications.enterTemplateContent")})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Ie,{type:"button",variant:"ghost",onClick:()=>_.mutate(),disabled:_.isPending,className:"text-orange-400 hover:text-orange-300",children:[_.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(jo,{className:"w-4 h-4 mr-2"}),n("notifications.resetToDefault")]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:n("notifications.cancel")}),a.jsxs(Ie,{onClick:k,disabled:g.isPending||!N,children:[g.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(cs,{className:"w-4 h-4 mr-2"}),n("notifications.save")]})]})]})]})})}const gtt={print_start:"text-blue-400",print_complete:"text-bambu-green",print_failed:"text-red-400",print_stopped:"text-orange-400",print_progress:"text-yellow-400",printer_offline:"text-gray-400",printer_error:"text-rose-400",filament_low:"text-cyan-400",maintenance_due:"text-purple-400",test:"text-bambu-gray"};function btt({onClose:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),[i,s]=w.useState(7),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=et({queryKey:["settings"],queryFn:he.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:y,isRefetching:v}=et({queryKey:["notification-logs",i,c],queryFn:()=>he.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=et({queryKey:["notification-log-stats",i],queryFn:()=>he.getNotificationLogStats(i)}),g=lt({mutationFn:()=>he.clearNotificationLogs(30),onSuccess:k=>{r(k.message,"success"),n.invalidateQueries({queryKey:["notification-logs"]}),n.invalidateQueries({queryKey:["notification-log-stats"]})},onError:k=>{r(`Failed to clear logs: ${k.message}`,"error")}}),_=k=>{const P=Qn(k);if(!P)return"";const M=new Date().getTime()-P.getTime();return M<6e4?e("notifications.justNow"):M<36e5?`${Math.floor(M/6e4)}m ago`:M<864e5?`${Math.floor(M/36e5)}h ago`:P.toLocaleDateString()+" "+DQ(P,m)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(L0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("notifications.notificationLog")})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:[e("notifications.statsSummary",{days:i})," ",a.jsx("span",{className:"text-white font-medium",children:b.total})," ",e("notifications.statsNotifications")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(fr,{className:"w-4 h-4"}),e("notifications.statsSent",{count:b.success_count})]}),b.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx($a,{className:"w-4 h-4"}),e("notifications.statsFailed",{count:b.failure_count})]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:i,onChange:k=>s(Number(k.target.value)),className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:[a.jsx("option",{value:1,children:e("notifications.last24Hours")}),a.jsx("option",{value:7,children:e("notifications.last7Days")}),a.jsx("option",{value:30,children:e("notifications.last30Days")}),a.jsx("option",{value:90,children:e("notifications.last90Days")})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:k=>d(k.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),e("notifications.showFailedOnly")]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>y(),disabled:v,children:[v?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),e("notifications.refresh")]}),a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>g.mutate(),disabled:g.isPending,className:"text-red-400 hover:text-red-300",children:[g.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),e("notifications.clearOld")]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?a.jsx("div",{className:"space-y-2",children:p.map(k=>a.jsx(xtt,{log:k,isExpanded:o===k.id,onToggle:()=>l(o===k.id?null:k.id),formatDate:_,formatFullDate:P=>Bf(P,m)},k.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(L0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:e(c?"notifications.noFailedNotifications":"notifications.noNotificationsLogged")})]})})]})})}function xtt({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){const{t:s}=Lt();return a.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[a.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?a.jsx(fr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx($a,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${gtt[t.event_type]||"text-bambu-gray"}`,children:s(`notifications.eventTypes.${t.event_type}`,t.event_type)}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||s("notifications.unknownProvider")}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(Yl,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logTitle")}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logMessage")}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:s("notifications.logError")}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsx("span",{children:s("notifications.logProvider",{type:t.provider_type})}),a.jsx("span",{children:s("notifications.logTime",{time:i(t.created_at)})})]})]})]})}function ytt({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Lt();w.useEffect(()=>{const d=u=>{u.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const c=d=>{e({...t,group_ids:t.group_ids.includes(d)?t.group_ids.filter(u=>u!==d):[...t.group_ids,d]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(_u,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Rt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:d=>e({...t,username:d.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:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:d=>e({...t,email:d.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:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(d=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(d.id),onChange:()=>c(d.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:d.name}),d.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},d.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Ie,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(ur,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function vtt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[d,u]=w.useState(!1),[m,p]=w.useState(!0),[f,y]=w.useState("all"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,P]=w.useState(!1),{data:N,isLoading:M}=et({queryKey:["spoolman-settings"],queryFn:he.getSpoolmanSettings}),{data:T,isLoading:A,refetch:C}=et({queryKey:["spoolman-status"],queryFn:he.getSpoolmanStatus,refetchInterval:3e4}),{data:F}=et({queryKey:["printers"],queryFn:he.getPrinters});w.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),u(N.spoolman_disable_weight_sync==="true"),p(N.spoolman_report_partial_usage!=="false"),b(!0))},[N]),w.useEffect(()=>{if(!v||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==d||N.spoolman_report_partial_usage!=="false"!==m){const te=setTimeout(()=>{$.mutate()},500);return()=>clearTimeout(te)}},[r,s,l,d,m,v]);const $=lt({mutationFn:()=>he.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:d?"true":"false",spoolman_report_partial_usage:m?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),e.invalidateQueries({queryKey:["settings"]}),n(t("settings.toast.settingsSaved"))}}),I=lt({mutationFn:he.connectSpoolman,onSuccess:()=>{C()}}),Q=lt({mutationFn:he.disconnectSpoolman,onSuccess:()=>{C()}}),L=lt({mutationFn:he.syncAllPrintersAms,onSuccess:K=>{K.success}}),re=lt({mutationFn:K=>he.syncPrinterAms(K),onSuccess:K=>{K.success}}),ae=()=>{f==="all"?L.mutate():re.mutate(f)},ee=lt({mutationFn:he.syncWeightsFromAms,onSuccess:K=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:K.synced,skipped:K.skipped}),"success"),P(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),P(!1)}}),ue=L.isPending||re.isPending,le=f==="all"?L.data:re.data,de=f==="all"?L.isSuccess:re.isSuccess;return M?a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),$.isPending&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(Na,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),a.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(sa,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[a.jsx("li",{children:t("settings.builtInFeatureRfid")}),a.jsx("li",{children:t("settings.builtInFeatureUsage")}),a.jsx("li",{children:t("settings.builtInFeatureCatalog")}),a.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>P(!0),disabled:ee.isPending,children:[ee.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(vr,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:t("settings.syncInfoRfidOnly")}),a.jsx("li",{children:t("settings.syncInfoAutoCreate")}),a.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),a.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:K=>o(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),a.jsxs("select",{value:l,onChange:K=>c(K.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",children:[a.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),a.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:d,onChange:K=>u(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),d&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:m,onChange:K=>p(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),A?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):T?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx(Kr,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Bt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),a.jsx("div",{className:"flex gap-2",children:T?.connected?a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Q.mutate(),disabled:Q.isPending,children:[Q.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Sge,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(Ie,{size:"sm",onClick:()=>I.mutate(),disabled:I.isPending||!s,children:[I.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ru,{className:"w-4 h-4"}),t("settings.connect")]})})]}),I.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:I.error.message}),T?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:f,onChange:K=>y(K.target.value==="all"?"all":Number(K.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"all",children:t("settings.allPrinters")}),F?.map(K=>a.jsx("option",{value:K.id,children:K.name},K.id))]}),a.jsx(Fn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ae,disabled:ue,children:[ue?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),de&&le&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${le.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:le.success?`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} successfully`:`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} with ${le.errors.length} error${le.errors.length!==1?"s":""}`}),le.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[le.skipped_count," spool",le.skipped_count!==1?"s":""," skipped"]})]}),le.skipped_count>5&&a.jsx("button",{onClick:()=>_(!g),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:g?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(g?le.skipped:le.skipped.slice(0,5)).map((K,te)=>a.jsxs("li",{className:"flex items-center gap-2",children:[K.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${K.color}`}}),a.jsx("span",{children:K.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",K.reason]})]},te)),!g&&le.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",le.skipped_count-5," more"]})]})]}),le.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:le.errors.map((K,te)=>a.jsx("li",{children:K},te))})]})]})]})]})]}),k&&a.jsx(kn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:ee.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>ee.mutate(),onCancel:()=>P(!1)})]})}function wtt(){const{t}=Lt(),{showToast:e}=xn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[d,u]=w.useState(!1),[m,p]=w.useState(null),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(!1),[k,P]=w.useState(new Set),[N,M]=w.useState(!1),[T,A]=w.useState(null),[C,F]=w.useState(!1),$=w.useCallback(async()=>{try{const be=await he.getSpoolCatalog();r(be)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{$()},[$]);const I=n.filter(be=>be.name.toLowerCase().includes(o.toLowerCase())),Q=async()=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const be=await he.addCatalogEntry({name:f.trim(),weight:parseInt(v)});r(Ne=>[...Ne,be].sort((B,Y)=>B.name.localeCompare(Y.name))),u(!1),y(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},L=be=>{p(be.id),y(be.name),b(be.weight.toString())},re=()=>{p(null),y(""),b("")},ae=async be=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const Ne=await he.updateCatalogEntry(be,{name:f.trim(),weight:parseInt(v)});r(B=>B.map(Y=>Y.id===be?Ne:Y).sort((Y,D)=>Y.name.localeCompare(D.name))),p(null),y(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},ee=async()=>{if(T)try{await he.deleteCatalogEntry(T.id),r(be=>be.filter(Ne=>Ne.id!==T.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{A(null)}},ue=async()=>{F(!1),s(!0);try{await he.resetSpoolCatalog(),await $(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},le=be=>{P(Ne=>{const B=new Set(Ne);return B.has(be)?B.delete(be):B.add(be),B})},de=()=>{k.size===I.length?P(new Set):P(new Set(I.map(be=>be.id)))},K=async()=>{if(M(!1),k.size!==0)try{const be=await he.bulkDeleteCatalogEntries([...k]);r(Ne=>Ne.filter(B=>!k.has(B.id))),P(new Set),e(t("settings.catalog.bulkDeleted",{count:be.deleted}),"success")}catch{e(t("settings.catalog.bulkDeleteFailed"),"error")}},te=()=>{const be=n.map(({name:D,weight:j})=>({name:D,weight:j})),Ne=new Blob([JSON.stringify(be,null,2)],{type:"application/json"}),B=URL.createObjectURL(Ne),Y=document.createElement("a");Y.href=B,Y.download="spool-catalog.json",document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),URL.revokeObjectURL(B),e(t("settings.catalog.exported",{count:n.length}),"success")},se=async be=>{const Ne=be.target.files?.[0];if(Ne){try{const B=await Ne.text(),Y=JSON.parse(B);if(!Array.isArray(Y))throw new Error("Invalid format");let D=0,j=0;for(const z of Y){if(!z.name||typeof z.weight!="number"){j++;continue}if(n.some(q=>q.name.toLowerCase()===z.name.toLowerCase())){j++;continue}try{const q=await he.addCatalogEntry({name:z.name,weight:z.weight});r(ce=>[...ce,q].sort((O,G)=>O.name.localeCompare(G.name))),D++}catch{j++}}e(t("settings.catalog.imported",{added:D,skipped:j}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(Dt,{children:[a.jsxs(Dn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:te,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[a.jsx(va,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[a.jsx(Ca,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:se}),a.jsxs("button",{onClick:()=>F(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[a.jsx(jo,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>u(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(ur,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),k.size>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[a.jsx("span",{className:"text-sm text-red-400",children:t("settings.catalog.selectedCount",{count:k.size})}),a.jsxs("button",{onClick:()=>M(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[a.jsx(un,{className:"w-4 h-4"}),t("settings.catalog.deleteSelected")]}),a.jsx("button",{onClick:()=>P(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:be=>l(be.target.value)})]}),d&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:f,onChange:be=>y(be.target.value)})}),a.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:v,onChange:be=>b(be.target.value)}),a.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),a.jsxs("button",{onClick:Q,disabled:g,className:"px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center gap-1 shrink-0",children:[g?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{u(!1),y(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-2 py-2 w-10",children:a.jsx("input",{type:"checkbox",checked:I.length>0&&k.size===I.length,onChange:de,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),a.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),a.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),a.jsx("th",{className:"px-4 py-2 w-24"})]})}),a.jsx("tbody",{children:I.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:5,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):I.map(be=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${k.has(be.id)?"bg-bambu-dark":""}`,children:m===be.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(be.id),onChange:()=>le(be.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:f,onChange:Ne=>y(Ne.target.value)})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:v,onChange:Ne=>b(Ne.target.value)})}),a.jsx("td",{className:"px-4 py-2 text-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>ae(be.id),disabled:g,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:g?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:re,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Bt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(be.id),onChange:()=>le(be.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2 text-white",children:be.name}),a.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[be.weight,"g"]}),a.jsx("td",{className:"px-4 py-2 text-center",children:be.is_default?a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>L(be),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>A(be),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(un,{className:"w-4 h-4"})})]})})]})},be.id))})]})})]}),T&&a.jsx(kn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:T.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:ee,onCancel:()=>A(null)}),N&&a.jsx(kn,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:k.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:K,onCancel:()=>M(!1)}),C&&a.jsx(kn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:ue,onCancel:()=>F(!1)})]})}function Stt(){const{t}=Lt(),{showToast:e}=xn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),[c,d]=w.useState("Bambu Lab"),u=w.useRef(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),[v,b]=w.useState(""),[g,_]=w.useState(""),[k,P]=w.useState("#FFFFFF"),[N,M]=w.useState(""),[T,A]=w.useState(!1),[C,F]=w.useState(new Set),[$,I]=w.useState(!1),[Q,L]=w.useState(!1),[re,ae]=w.useState(null),[ee,ue]=w.useState(null),[le,de]=w.useState(!1),K=w.useCallback(async()=>{try{const V=await he.getColorCatalog();r(V)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{K()},[K]);const te=[...new Set(n.map(V=>V.manufacturer))].sort(),se=n.filter(V=>{const J=o===""||V.manufacturer.toLowerCase().includes(o.toLowerCase())||V.color_name.toLowerCase().includes(o.toLowerCase())||(V.material?.toLowerCase().includes(o.toLowerCase())??!1),ie=c===""||V.manufacturer===c;return J&&ie}),be=()=>{b(""),_(""),P("#FFFFFF"),M("")},Ne=async()=>{if(!v.trim()||!g.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}A(!0);try{const V=await he.addColorEntry({manufacturer:v.trim(),color_name:g.trim(),hex_color:k,material:N.trim()||null});r(J=>[...J,V].sort((ie,me)=>ie.manufacturer.localeCompare(me.manufacturer)||(ie.material||"").localeCompare(me.material||"")||ie.color_name.localeCompare(me.color_name))),p(!1),be(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{A(!1)}},B=V=>{y(V.id),b(V.manufacturer),_(V.color_name),P(V.hex_color),M(V.material||"")},Y=()=>{y(null),be()},D=async V=>{if(!v.trim()||!g.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}A(!0);try{const J=await he.updateColorEntry(V,{manufacturer:v.trim(),color_name:g.trim(),hex_color:k,material:N.trim()||null});r(ie=>ie.map(me=>me.id===V?J:me).sort((me,pe)=>me.manufacturer.localeCompare(pe.manufacturer)||(me.material||"").localeCompare(pe.material||"")||me.color_name.localeCompare(pe.color_name))),y(null),be(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{A(!1)}},j=async()=>{if(ee)try{await he.deleteColorEntry(ee.id),r(V=>V.filter(J=>J.id!==ee.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{ue(null)}},z=async()=>{de(!1),s(!0);try{await he.resetColorCatalog(),await K(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},W=async()=>{L(!0),ae(null);try{const V={},J=Ku();J&&(V.Authorization=`Bearer ${J}`);const ie=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:V});if(!ie.ok)throw new Error("Failed to start sync");const me=ie.body?.getReader();if(!me)throw new Error("No response body");const pe=new TextDecoder;let oe="";for(;;){const{done:U,value:R}=await me.read();if(U)break;oe+=pe.decode(R,{stream:!0});const ne=oe.split(`
+ `,onClick:ae?()=>{window.innerWidth<640&&u()}:void 0,children:[ae&&d&&a.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),a.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[L&&u&&a.jsx("button",{onClick:ee=>{ee.stopPropagation(),u()},className:`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${d?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:d&&a.jsx(Kr,{className:"w-4 h-4"})}),L?a.jsx("div",{...M,...T,className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation shrink-0",children:a.jsx(jh,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?a.jsxs("div",{className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium shrink-0",children:["#",e]}):a.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),a.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?a.jsx("img",{src:t.plate_id!=null?he.getArchivePlateThumbnail(t.archive_id,t.plate_id):he.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?he.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):he.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(ea,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsxs("p",{className:"text-sm sm:text-base text-white font-medium truncate",children:[t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,(k?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${P.find(ee=>ee.index===t.plate_id)?.name||y("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?a.jsx(vo,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:y("queue.viewArchive"),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(vo,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:y("queue.viewInFileManager"),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):null,t.batch_name&&a.jsx("span",{className:"flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-purple-500/20 text-purple-300 rounded border border-purple-500/30",children:t.batch_name})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[a.jsxs("span",{className:`flex items-center gap-1 sm:gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model&&!t.printer_id?"text-blue-400":""}`,children:[a.jsx(Pr,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),a.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model&&!t.printer_id?`${y("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?y("queue.filter.unassigned"):t.printer_name||`${y("common.printer")} #${t.printer_id}`})]}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(Pc,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),ls(t.print_time_seconds)]}),t.filament_used_grams&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(CQ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Het(t.filament_used_grams)]}),t.created_by_username&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:y("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(Gu,{className:"w-3.5 h-3.5"}),t.created_by_username]}),L&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),t.scheduled_time?(Qn(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?y?.("queue.time.overdue")??"Overdue":Sx(t.scheduled_time,c,y):y?.("queue.time.asap")??"ASAP"]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[a.jsx(gQ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.staged")]}),t.require_previous_success&&a.jsx("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:y("queue.badges.requiresPrevious")}),t.auto_off_after&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[a.jsx(am,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.autoPowerOff")]}),t.gcode_injection&&a.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-500/10 text-emerald-400 rounded-full border border-emerald-500/20 flex items-center gap-1",children:[a.jsx(ey,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),y("queue.badges.gcodeInjection")]})]}),Q&&v&&a.jsxs("div",{className:"mt-2 sm:mt-3",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[a.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:a.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${v.progress||0}%`}})}),a.jsxs("span",{className:"text-white",children:[Math.round(v.progress||0),"%"]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mt-1.5 sm:mt-2 text-[10px] sm:text-xs text-bambu-gray",children:[v.remaining_time!=null&&v.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),ls(v.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:y("printers.estimatedCompletion"),children:["ETA ",vO(v.remaining_time,c,y)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(ea,{className:"w-3 h-3"}),v.layer_num,"/",v.total_layers]})]})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[a.jsx(qa,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[a.jsx(qa,{className:"w-3 h-3"}),t.error_message]})]}),a.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:ee=>ee.stopPropagation(),children:[a.jsx(qet,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:y}),a.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[Q&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("printers:control")?y("queue.actions.stopPrint"):y("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:a.jsx(Upe,{className:"w-4 h-4"})}),L&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Ie,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("printers:control")?y("queue.actions.startPrint"):y("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2",children:a.jsx(Ds,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?y("common.edit"):y("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?y("common.cancel"):y("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),re&&a.jsxs(a.Fragment,{children:[a.jsx(Ie,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("queue:create")?y("queue.actions.requeue"):y("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2",children:a.jsx(vr,{className:"w-4 h-4"})}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?y("common.remove"):y("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})]})]})}function Vet(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=Sr(),[o,l]=w.useState(null),[c,d]=w.useState(""),[u,m]=w.useState(""),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState(null),[_,k]=w.useState(null),[P,N]=w.useState([]),[M,T]=w.useState(!1),[A,C]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[F,$]=w.useState(()=>{const ve=localStorage.getItem("queue.historySortAsc");return ve!==null?ve==="true":!1}),[I,Q]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[L,re]=w.useState(()=>{const ve=localStorage.getItem("queue.pendingSortAsc");return ve!==null?ve==="true":!0}),[ae,ee]=w.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[ue,le]=w.useState(()=>localStorage.getItem("queue.viewMode")||"list");w.useEffect(()=>{localStorage.setItem("queue.historySortBy",A)},[A]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(F))},[F]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",I)},[I]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(L))},[L]),w.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ae))},[ae]),w.useEffect(()=>{localStorage.setItem("queue.viewMode",ue)},[ue]);const de=Ooe(pP(JT,{activationConstraint:{distance:8}}),pP(ZT,{coordinateGetter:sle})),{data:K}=et({queryKey:["settings"],queryFn:he.getSettings}),te=K?.time_format||"system",{data:se,isLoading:be}=et({queryKey:["queue",o,c],queryFn:()=>he.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:Ne}=et({queryKey:["printers"],queryFn:()=>he.getPrinters()}),B=lt({mutationFn:ve=>he.updateSettings({queue_shortest_first:ve}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),Y=lt({mutationFn:ve=>he.cancelQueueItem(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),D=lt({mutationFn:ve=>he.removeFromQueue(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),j=lt({mutationFn:ve=>he.stopQueueItem(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),z=lt({mutationFn:ve=>he.startQueueItem(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),W=lt({mutationFn:ve=>he.reorderQueue(ve),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),q=lt({mutationFn:async()=>{const ve=se?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];for(const fe of ve)await he.removeFromQueue(fe.id);return ve.length},onSuccess:ve=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:ve}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),ce=lt({mutationFn:ve=>he.bulkUpdateQueue(ve),onSuccess:ve=>{e.invalidateQueries({queryKey:["queue"]}),N([]),T(!1),n(ve.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),O=lt({mutationFn:async ve=>{for(const fe of ve)await he.cancelQueueItem(fe);return ve.length},onSuccess:ve=>{e.invalidateQueries({queryKey:["queue"]}),N([]),n(t("queue.toast.bulkCancelled",{count:ve}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),G=ve=>{N(fe=>fe.includes(ve)?fe.filter(ke=>ke!==ve):[...fe,ve])},X=w.useMemo(()=>{const ve=new Set;return Ne?.forEach(fe=>{fe.location&&ve.add(fe.location)}),se?.forEach(fe=>{fe.target_location&&ve.add(fe.target_location)}),Array.from(ve).sort()},[Ne,se]),V=w.useCallback(ve=>u?ve.target_location?ve.target_location===u:ve.printer_id?Ne?.find(ke=>ke.id===ve.printer_id)?.location===u:!1:!0,[u,Ne]),J=w.useMemo(()=>{let ve=se?.filter(ke=>ke.status==="pending")||[];u&&(ve=ve.filter(V));const fe=ke=>{if(!ke.scheduled_time)return 0;const Ee=Qn(ke.scheduled_time)?.getTime()??0,Ae=Date.now()+4320*60*60*1e3;return Ee>Ae?0:Ee};return K?.queue_shortest_first?[...ve].sort((ke,Ee)=>{const Ae=ke.printer_id??-(ke.target_model?.charCodeAt(0)??0),_e=Ee.printer_id??-(Ee.target_model?.charCodeAt(0)??0);if(Ae!==_e)return Ae-_e;const je=ke.been_jumped?1:0,Be=Ee.been_jumped?1:0;if(je!==Be)return Be-je;const Re=ke.print_time_seconds??1/0,Ye=Ee.print_time_seconds??1/0;return Re!==Ye?Re-Ye:ke.position-Ee.position}):[...ve].sort((ke,Ee)=>{let Ae;if(I==="name"){const _e=ke.archive_name||ke.library_file_name||"",je=Ee.archive_name||Ee.library_file_name||"";Ae=_e.localeCompare(je)}else I==="printer"?Ae=(ke.printer_name||"").localeCompare(Ee.printer_name||""):I==="time"?Ae=fe(ke)-fe(Ee):Ae=ke.position-Ee.position;return L?Ae:-Ae})},[se,I,L,V,u,K?.queue_shortest_first]),ie=()=>{const ve=J.map(fe=>fe.id);P.length===ve.length?N([]):N(ve)},me=w.useMemo(()=>{let ve=se?.filter(fe=>fe.status==="printing")||[];return u&&(ve=ve.filter(V)),ve},[se,u,V]),pe=w.useMemo(()=>{const ve=new Set;return me.forEach(fe=>{fe.printer_id&&ve.add(fe.printer_id)}),Array.from(ve)},[me]),oe=ep({queries:pe.map(ve=>({queryKey:["printerStatus",ve],queryFn:()=>he.getPrinterStatus(ve),refetchInterval:5e3}))}),U=w.useMemo(()=>{const ve={};return pe.forEach((fe,ke)=>{const Ee=oe[ke];Ee?.data?.state&&(ve[fe]=Ee.data.state)}),ve},[pe,oe]),R=w.useMemo(()=>{const ve={};return pe.forEach((fe,ke)=>{const Ee=oe[ke];Ee?.data&&(ve[fe]={progress:Ee.data.progress??void 0,remaining_time:Ee.data.remaining_time??void 0,state:Ee.data.state??void 0})}),ve},[pe,oe]),ne=w.useMemo(()=>{let ve=se?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];return u&&(ve=ve.filter(V)),[...ve].sort((fe,ke)=>{let Ee;if(A==="name"){const Ae=fe.archive_name||fe.library_file_name||"",_e=ke.archive_name||ke.library_file_name||"";Ee=Ae.localeCompare(_e)}else A==="printer"?Ee=(fe.printer_name||"").localeCompare(ke.printer_name||""):Ee=(Qn(ke.completed_at||ke.created_at)?.getTime()??0)-(Qn(fe.completed_at||fe.created_at)?.getTime()??0);return F?-Ee:Ee})},[se,A,F,V,u]),xe=w.useMemo(()=>J.reduce((ve,fe)=>ve+(fe.print_time_seconds||0),0),[J]),Se=w.useMemo(()=>J.reduce((ve,fe)=>ve+(fe.filament_used_grams||0),0),[J]),ye=ve=>{const{active:fe,over:ke}=ve;if(!ke||fe.id===ke.id)return;const Ee=J.findIndex(_e=>_e.id===fe.id),Ae=J.findIndex(_e=>_e.id===ke.id);if(Ee!==-1&&Ae!==-1){const je=nA(J,Ee,Ae).map((Be,Re)=>({id:Be.id,position:Re+1}));W.mutate(je)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(nN,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsx(Fet,{activeCount:me.length,pendingCount:J.length,totalTime:xe,totalWeight:Se,historyCount:ne.length,t}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:o===-1?"unassigned":o||"",onChange:ve=>{const fe=ve.target.value;l(fe==="unassigned"?-1:fe===""?null:Number(fe))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),Ne?.map(ve=>a.jsx("option",{value:ve.id,children:ve.name},ve.id))]}),a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:c,onChange:ve=>d(ve.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),X.length>0&&a.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:u,onChange:ve=>m(ve.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),X.map(ve=>a.jsx("option",{value:ve,children:ve},ve))]}),a.jsx("div",{className:"hidden sm:block flex-1"}),ne.length>0&&a.jsxs(Ie,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>f(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(un,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[a.jsxs("div",{className:"hidden sm:flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsx("button",{className:`p-2 transition-colors ${ue==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("list"),title:t("queue.timeline.listView"),children:a.jsx(Ew,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 transition-colors ${ue==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>le("timeline"),title:t("queue.timeline.timelineView"),children:a.jsx(Npe,{className:"w-4 h-4"})})]}),a.jsxs("button",{onClick:()=>{const ve=!(K?.queue_shortest_first??!1);B.mutate(ve)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${K?.queue_shortest_first?"bg-bambu-green/20 border-bambu-green text-bambu-green":"bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,title:t("queue.sjf.tooltip","Shortest Job First — scheduler prioritizes shorter prints"),children:[a.jsx(Pc,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.sjf.label","SJF")}),a.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?.queue_shortest_first?"bg-bambu-green":"bg-bambu-gray"}`})]})]}),be?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):se?.length===0?a.jsxs(Dt,{className:"p-12 text-center border-dashed",children:[a.jsx(Wr,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):ue==="timeline"?a.jsx(Bet,{queueItems:se||[],printerStatuses:R,onItemClick:ve=>{["completed","failed","skipped","cancelled"].includes(ve.status)?g(ve):ve.status==="pending"?v(ve):ve.status==="printing"&&k({type:"stop",item:ve})},t}):a.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[me.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-2 sm:space-y-3",children:me.map(ve=>a.jsx(KY,{item:ve,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>k({type:"stop",item:ve}),onRequeue:()=>{},onStart:()=>{},timeFormat:te,hasPermission:r,canModify:s,printerState:ve.printer_id?U[ve.printer_id]:null,t},ve.id))})]}),J.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:J.length}),")"]}),a.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:I,onChange:ve=>Q(ve.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>re(!L),title:t(L?"common.ascending":"common.descending"),className:"px-2",children:L?a.jsx(Lf,{className:"w-4 h-4"}):a.jsx(bx,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-3 sm:mb-4 p-2 sm:p-3 bg-bambu-dark rounded-lg",children:[a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:ie,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[P.length===J.length&&J.length>0?a.jsx(us,{className:"w-4 h-4 text-bambu-green"}):a.jsx(eo,{className:"w-4 h-4"}),P.length===J.length&&J.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),P.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:P.length})}),a.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>T(!0),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light",disabled:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?t("queue.bulkEdit.editSelected"):t("queue.permissions.noEditItems"),children:[a.jsx(Za,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>O.mutate(P),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:O.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?t("queue.bulkEdit.cancelSelected"):t("queue.permissions.noCancelItems"),children:[a.jsx(Bt,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),a.jsx(ele,{sensors:de,collisionDetection:Boe,onDragEnd:ye,children:a.jsx(rle,{items:J.map(ve=>ve.id),strategy:wet,children:a.jsx("div",{className:"space-y-2 sm:space-y-3",children:J.map((ve,fe)=>a.jsx(KY,{item:ve,position:fe+1,onEdit:()=>v(ve),onCancel:()=>k({type:"cancel",item:ve}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>z.mutate(ve.id),timeFormat:te,isSelected:P.includes(ve.id),onToggleSelect:()=>G(ve.id),hasPermission:r,canModify:s,t},ve.id))})})})]}),ne.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[a.jsxs("button",{onClick:()=>ee(!ae),className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2 hover:text-bambu-green transition-colors",children:[ae?a.jsx(Va,{className:"w-4 h-4 sm:w-5 sm:h-5"}):a.jsx(Fn,{className:"w-4 h-4 sm:w-5 sm:h-5"}),t("queue.sections.history"),a.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:ne.length}),")"]})]}),!ae&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:A,onChange:ve=>C(ve.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>$(!F),title:t(F?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:F?a.jsx(Lf,{className:"w-4 h-4"}):a.jsx(bx,{className:"w-4 h-4"})})]})]}),!ae&&a.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:ne.slice(0,50).map(ve=>a.jsx(Ret,{item:ve,onRemove:()=>k({type:"remove",item:ve}),onRequeue:()=>g(ve),timeFormat:te,hasPermission:r,canModify:s,t},ve.id))})]})]}),y&&a.jsx(kd,{mode:"edit-queue-item",archiveId:y.archive_id??void 0,libraryFileId:y.library_file_id??void 0,archiveName:y.archive_name||y.library_file_name||`File #${y.archive_id||y.library_file_id}`,queueItem:y,onClose:()=>v(null)}),b&&a.jsx(kd,{mode:"add-to-queue",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,onClose:()=>g(null)}),_&&a.jsx(kn,{title:_.type==="cancel"?t("queue.confirm.cancelTitle"):_.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:_.type==="cancel"?t("queue.confirm.cancelMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):_.type==="stop"?t("queue.confirm.stopMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:_.item.archive_name||_.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:_.type==="cancel"?t("queue.confirm.cancelButton"):_.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{_.type==="cancel"?Y.mutate(_.item.id):_.type==="stop"?j.mutate(_.item.id):D.mutate(_.item.id),k(null)},onCancel:()=>k(null)}),p&&a.jsx(kn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:ne.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{q.mutate(),f(!1)},onCancel:()=>f(!1)}),M&&a.jsx($et,{selectedCount:P.length,printers:Ne?.map(ve=>({id:ve.id,name:ve.name}))||[],onSave:ve=>{Object.keys(ve).length>0&&ce.mutate({item_ids:P,...ve})},onClose:()=>T(!1),isSaving:ce.isPending,canControlPrinter:r("printers:control"),t})]})}function Get({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const k=new ResizeObserver(P=>{const N=P[0]?.contentRect.width||0;i(N)});return k.observe(_),()=>k.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach($=>{const I=$.split("T")[0];_[I]=(_[I]||0)+1});const k=new Date,P=new Date(k);P.setMonth(P.getMonth()-e),P.setDate(P.getDate()-P.getDay());const N=[],M=[];let T=[],A=-1;const C=new Date(P);let F=0;for(;C<=k;)C.getDay()===0&&T.length>0&&(N.push(T),T=[],F++),C.getMonth()!==A&&(M.push({month:C.toLocaleDateString("en-US",{month:"short"}),weekIndex:F}),A=C.getMonth()),T.push(new Date(C)),C.setDate(C.getDate()+1);return T.length>0&&N.push(T),{weeks:N,monthLabels:M,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),d=_=>{if(_===0)return"bg-bambu-dark";const k=_/c;return k<=.25?"bg-bambu-green/30":k<=.5?"bg-bambu-green/50":k<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,y=r-p-16,v=m>0?Math.floor((y-(m-1)*f)/m):12,b=Math.max(8,Math.min(20,v)),g=b<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:_,weekIndex:k},P)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:g,marginLeft:P===0?0:`${(k-(o[P-1]?.weekIndex||0))*(b+f)-24}px`},children:_},P))}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"flex flex-col",style:{gap:f,marginRight:4,width:p},children:u.map((_,k)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:g,visibility:k%2===1?"visible":"hidden"},children:_},_))}),s.map((_,k)=>a.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(P=>{const N=_.find(C=>C.getDay()===P);if(!N)return a.jsx("div",{style:{width:b,height:b}},P);const M=N.toISOString().split("T")[0],T=l[M]||0,A=M===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${d(T)} ${A?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${N.toLocaleDateString()}: ${T} print${T!==1?"s":""}`},P)})},k))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:g},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:f},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),a.jsx("span",{children:"More"})]})]})})}const YY=["weight","prints","time"];function bP({value:t,onChange:e,exclude:n}){const{t:r}=Lt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=n?YY.filter(o=>!n.includes(o)):YY;return a.jsx("div",{className:"flex gap-0.5 bg-bambu-dark rounded-lg p-0.5",children:s.map(o=>a.jsx("button",{onClick:()=>e(o),className:`px-2 py-0.5 text-xs rounded-md transition-colors ${t===o?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:i[o]},o))})}function gh(t){if(t>=1e6){const e=t/1e6;return`${e%1===0?e.toFixed(0):e.toFixed(1)}t`}if(t>=1e3){const e=t/1e3;return`${e%1===0?e.toFixed(0):e.toFixed(1)}kg`}return`${Math.round(t)}g`}const mk=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],Wet=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],XY=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"];function Ket({archives:t,currency:e="$",dateFrom:n,dateTo:r}){const{t:i}=Lt(),[s,o]=w.useState("weight"),[l,c]=w.useState("weight"),d=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{const F=Qn(C.completed_at||C.created_at)||new Date,$=`${F.getFullYear()}-${String(F.getMonth()+1).padStart(2,"0")}-${String(F.getDate()).padStart(2,"0")}`,I=A.get($)||{date:$,filament:0,cost:0,prints:0};I.filament+=C.filament_used_grams||0,I.cost+=C.cost||0,I.prints+=C.quantity||1,A.set($,I)}),Array.from(A.values()).sort((C,F)=>C.date.localeCompare(F.date)).map(C=>({...C,dateLabel:new Date(C.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[t]),u=w.useMemo(()=>{if(n&&r)return Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1;if(n)return Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1;if(t.length<2)return 0;const A=t.map(C=>new Date(C.completed_at||C.created_at).getTime());return(Math.max(...A)-Math.min(...A))/864e5},[t,n,r]),m=w.useMemo(()=>{if(u>7)return[];const A=new Map,C=u>1;return t.forEach(F=>{const $=Qn(F.completed_at||F.created_at)||new Date,I=$.getHours(),Q=`${$.getFullYear()}-${String($.getMonth()+1).padStart(2,"0")}-${String($.getDate()).padStart(2,"0")}T${String(I).padStart(2,"0")}`,L=A.get(Q)||{date:Q,filament:0,cost:0,prints:0};L.filament+=F.filament_used_grams||0,L.cost+=F.cost||0,L.prints+=F.quantity||1,A.set(Q,L)}),Array.from(A.values()).sort((F,$)=>F.date.localeCompare($.date)).map(F=>{const[$,I]=F.date.split("T"),Q=new Date($),L=parseInt(I,10),re=C?`${Wet[Q.getDay()]} ${XY[L]}`:XY[L];return{...F,dateLabel:re}})},[t,u]),p=w.useMemo(()=>{if(d.length<=60)return d;const A=new Map;return d.forEach(C=>{const F=new Date(C.date),$=new Date(F);$.setDate(F.getDate()-F.getDay());const I=`${$.getFullYear()}-${String($.getMonth()+1).padStart(2,"0")}-${String($.getDate()).padStart(2,"0")}`,Q=A.get(I)||{week:I,filament:0,cost:0,prints:0};Q.filament+=C.filament,Q.cost+=C.cost,Q.prints+=C.prints,A.set(I,Q)}),Array.from(A.values()).sort((C,F)=>C.week.localeCompare(F.week)).map(C=>({date:C.week,dateLabel:`Week of ${new Date(C.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...C}))},[d]),f=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{const $=(C.filament_type||"Unknown").split(", ");$.forEach(I=>{const Q=(C.filament_used_grams||0)/$.length;A.set(I,(A.get(I)||0)+Q)})}),Array.from(A.entries()).map(([C,F])=>({name:C,value:Math.round(F)})).sort((C,F)=>F.value-C.value)},[t]),y=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{(C.filament_type||"Unknown").split(", ").forEach(I=>{A.set(I,(A.get(I)||0)+1)})}),Array.from(A.entries()).map(([C,F])=>({name:C,value:F})).sort((C,F)=>F.value-C.value)},[t]),v=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{const $=(C.filament_type||"Unknown").split(", "),I=(C.actual_time_seconds||C.print_time_seconds||0)/$.length;$.forEach(Q=>{A.set(Q,(A.get(Q)||0)+I)})}),Array.from(A.entries()).map(([C,F])=>({name:C,value:Math.round(F/3600*10)/10})).sort((C,F)=>F.value-C.value)},[t]),b=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{if(C.status!=="completed"&&C.status!=="failed")return;(C.filament_type||"Unknown").split(", ").forEach($=>{const I=A.get($)||{completed:0,failed:0};C.status==="completed"?I.completed++:I.failed++,A.set($,I)})}),Array.from(A.entries()).filter(([,C])=>C.completed+C.failed>=2).map(([C,F])=>{const $=F.completed+F.failed,I=Math.round(F.completed/$*100);return{name:C,rate:I,total:$}}).sort((C,F)=>F.rate-C.rate)},[t]),g=w.useMemo(()=>{const A=new Map;return t.forEach(C=>{if(!C.filament_color)return;const F=C.filament_color.split(",").map(I=>I.trim()),$=(C.filament_used_grams||0)/F.length;F.forEach(I=>{const Q=A.get(I)||{count:0,weight:0};Q.count++,Q.weight+=$,A.set(I,Q)})}),Array.from(A.entries()).map(([C,F])=>({hex:C,value:l==="prints"?F.count:Math.round(F.weight)})).sort((C,F)=>F.value-C.value)},[t,l]),_=s==="weight"?f:s==="prints"?y:v,k=u<=7&&m.length>0?m:p,P=t.reduce((A,C)=>A+(C.filament_used_grams||0),0),N=t.reduce((A,C)=>A+(C.cost||0),0),M=t.reduce((A,C)=>A+(C.quantity||1),0),T=new Set(t.map(A=>A.printer_id).filter(Boolean)).size;return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-2 max-[640px]:grid-cols-1",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodFilament")}),a.jsx("p",{className:"text-2xl font-bold text-white leading-none",children:gh(P)})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[T," ",i("nav.printers").toLowerCase()]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodCost")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,N.toFixed(2)]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[M," ",i("common.prints")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.avgPerPrint")}),a.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[M>0?(P/M).toFixed(0):0,"g"]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,M>0?(N/M).toFixed(2):"0.00"," avg"]})]})]}),k.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.usageOverTime")}),a.jsx(Sh,{width:"100%",height:250,children:a.jsxs(bVe,{data:k,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:A=>`${A}g`}),a.jsx(_h,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:A=>[`${Number(A??0).toFixed(0)}g`,"Filament"]}),a.jsx(Jre,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:i("stats.noPrintDataInRange")}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.byMaterial")}),a.jsx(bP,{value:s,onChange:o})]}),_.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Sh,{width:160,height:160,children:a.jsxs(PW,{children:[a.jsx(qR,{data:_,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:_.map((A,C)=>a.jsx(zx,{fill:mk[C%mk.length]},`cell-${C}`))}),a.jsx(_h,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:A=>[s==="weight"?gh(Number(A??0)):s==="time"?`${Number(A??0)}h`:`${A??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:_.map((A,C)=>{const F=_.reduce((I,Q)=>I+Q.value,0),$=F>0?(A.value/F*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:mk[C%mk.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:A.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?gh(A.value):s==="time"?`${A.value}h`:A.value," · ",$,"%"]})]},A.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noFilamentData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.filamentSuccess")}),b.length>0?a.jsx("div",{className:"space-y-1.5",children:b.map(A=>a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:"text-white truncate w-20 flex-shrink-0",children:A.name}),a.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-secondary rounded-full",children:a.jsx("div",{className:`h-full rounded-full transition-all ${A.rate>=90?"bg-status-ok":A.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${A.rate}%`}})}),a.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${A.rate>=90?"text-status-ok":A.rate>=70?"text-status-warning":"text-status-error"}`,children:[A.rate,"%"]}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",A.total,")"]})]},A.name))}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.colorDistribution")}),a.jsx(bP,{value:l,onChange:c,exclude:["time"]})]}),g.length>0?(()=>{const A=g.reduce((C,F)=>C+F.value,0);return a.jsxs("div",{children:[a.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[a.jsx(Sh,{width:"100%",height:"100%",children:a.jsxs(PW,{children:[a.jsx(qR,{data:g,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:g.map((C,F)=>a.jsx(zx,{fill:C.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${F}`))}),a.jsx(_h,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:C=>[l==="weight"?gh(Number(C??0)):`${C??0}`,i(l==="weight"?"stats.filamentByWeight":"stats.filamentByPrints")]})]})}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsx("span",{className:"text-lg font-bold text-white",children:l==="weight"?gh(A):A}),a.jsxs("span",{className:"text-[10px] text-bambu-gray",children:[g.length," ",g.length===1?"color":"colors"]})]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1 mt-2",children:g.slice(0,8).map(C=>{const F=A>0?(C.value/A*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-1.5 text-xs min-w-0",children:[a.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20",style:{backgroundColor:C.hex}}),a.jsxs("span",{className:"text-bambu-gray truncate",children:[F,"%"]})]},C.hex)})}),g.length>8&&a.jsxs("p",{className:"text-[10px] text-bambu-gray mt-1 text-center",children:["+",g.length-8," more"]})]})})():a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noColorData")})]})]})]})}function Yet({id:t,title:e,component:n,isHidden:r,size:i,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:f}=ile({id:t}),y={transform:Kx.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...y,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...c,...d,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:l,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(hO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(NP,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(Tw,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function Xet({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const A={};return t.forEach(C=>{A[C.id]=C.defaultSize||4}),A},[c,d]=w.useState(()=>{const A=localStorage.getItem(e);if(A)try{const C=JSON.parse(A);if(!C.sizes)C.sizes=l();else{const F=l();for(const $ in F)$ in C.sizes||(C.sizes[$]=F[$])}return C}catch{}return{order:t.map(C=>C.id),hidden:t.filter(C=>C.defaultVisible===!1).map(C=>C.id),sizes:l()}}),[u,m]=w.useState(!1),[p,f]=w.useState(!1);w.useEffect(()=>{if(!r)return;const A=window.matchMedia(`(max-width: ${r}px)`),C=$=>{f($.matches)};C(A);const F=$=>C($);return A.addEventListener?A.addEventListener("change",F):A.addListener(F),()=>{A.removeEventListener?A.removeEventListener("change",F):A.removeListener(F)}},[r]);const y=r&&p?1:n;w.useEffect(()=>{const A=()=>m(C=>!C);return window.addEventListener("toggle-hidden-panel",A),()=>window.removeEventListener("toggle-hidden-panel",A)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const C=t.map(F=>F.id).filter(F=>!c.order.includes(F));C.length>0&&d(F=>({...F,order:[...F.order,...C]}))},[t,c.order]);const v=Ooe(pP(JT,{activationConstraint:{distance:8}}),pP(ZT,{coordinateGetter:sle})),b=A=>{const{active:C,over:F}=A;F&&C.id!==F.id&&d($=>{const I=$.order.indexOf(C.id),Q=$.order.indexOf(F.id);return{...$,order:nA($.order,I,Q)}})},g=A=>{d(C=>({...C,hidden:C.hidden.includes(A)?C.hidden.filter(F=>F!==A):[...C.hidden,A]}))},_=A=>{d(C=>{const F=C.sizes[A]||4,$=F===1?2:F===2?4:1;return{...C,sizes:{...C.sizes,[A]:$}}})},k=()=>{const A={order:t.map(C=>C.id),hidden:t.filter(C=>C.defaultVisible===!1).map(C=>C.id),sizes:l()};d(A),s?.()},P=c.order.map(A=>t.find(C=>C.id===A)).filter(Boolean),N=P.filter(A=>!c.hidden.includes(A.id)),M=P.filter(A=>c.hidden.includes(A.id)),T=o?.({hiddenCount:M.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:k});return a.jsxs("div",{className:"space-y-4",children:[T,!i&&!o&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:k,children:[a.jsx(jo,{className:"w-4 h-4"}),"Reset Layout"]}),M.length>0&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[a.jsx(Dc,{className:"w-4 h-4"}),M.length," Hidden"]})]}),u&&M.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(A=>a.jsxs("button",{onClick:()=>g(A.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[a.jsx(Dc,{className:"w-3 h-3"}),A.title]},A.id))})]}),a.jsx(ele,{sensors:v,collisionDetection:Boe,onDragEnd:b,children:a.jsx(rle,{items:N.map(A=>A.id),strategy:Wz,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${y}, minmax(0, 1fr))`},children:N.map(A=>{const C=c.sizes[A.id]||2,F=Math.min(C,y);return a.jsx(Yet,{id:A.id,title:A.title,component:A.component,isHidden:c.hidden.includes(A.id),size:C,columnSpan:F,onToggleVisibility:()=>g(A.id),onToggleSize:()=>_(A.id)},A.id)})})})}),N.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Ie,{className:"mt-4",onClick:k,children:"Reset Layout"})]})]})}function Qet(t){const e=new Date,n=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate(),s=l=>l.toISOString().split("T")[0],o=s(e);switch(t){case"today":return{dateFrom:o,dateTo:o};case"this-week":{const l=e.getUTCDay(),c=new Date(Date.UTC(n,r,i-(l===0?6:l-1)));return{dateFrom:s(c),dateTo:o}}case"this-month":return{dateFrom:s(new Date(Date.UTC(n,r,1))),dateTo:o};case"last-7":return{dateFrom:s(new Date(Date.UTC(n,r,i-6))),dateTo:o};case"last-30":return{dateFrom:s(new Date(Date.UTC(n,r,i-29))),dateTo:o};case"last-90":return{dateFrom:s(new Date(Date.UTC(n,r,i-89))),dateTo:o};case"this-year":return{dateFrom:s(new Date(Date.UTC(n,0,1))),dateTo:o};case"all-time":return{dateFrom:void 0,dateTo:void 0};case"custom":return{}}}const Zet=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],Jet=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],UL=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],i3=[{key:"<30m",max:1800},{key:"30m-1h",max:3600},{key:"1-2h",max:7200},{key:"2-4h",max:14400},{key:"4-8h",max:28800},{key:"8-12h",max:43200},{key:"12-24h",max:86400},{key:"24h+",max:1/0}],hk={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function ett({stats:t,currency:e}){const{t:n}=Lt(),r=[{icon:Na,color:"text-bambu-green",label:n("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:rr,color:"text-blue-400",label:n("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Na,color:"text-orange-400",label:n("stats.filamentUsed"),value:gh(t?.total_filament_grams||0)},{icon:Zk,color:"text-green-400",label:n("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:Xl,color:"text-yellow-400",label:n("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`},{icon:Zk,color:"text-yellow-500",label:n("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`}];return a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:r.map(i=>a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${i.color}`,children:a.jsx(i.icon,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),a.jsx("p",{className:"text-xl font-bold text-white",children:i.value})]})]},i.label))})}function ttt({stats:t,printerMap:e,size:n=1}){const{t:r}=Lt(),i=(t?.successful_prints||0)+(t?.failed_prints||0),s=i?Math.round(t.successful_prints/i*100):0,o=n===1?112:n===2?128:144,l=o/2-8,c=l*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:o,height:o},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${s/100*c} ${c}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[s,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx($a,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([d,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(d)||`${r("common.printer")} ${d}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},d))})]})]})]})}function ntt({stats:t,printerMap:e,size:n=1}){const{t:r}=Lt(),i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(i),d=i-100,u=n===1?112:n===2?128:144,m=u/2-8,p=m*2*Math.PI,f=n===1?3:n===2?6:999,y=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,f):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:u,height:u},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${d>=0?"text-blue-400":"text-orange-400"}`,children:[d>=0?"+":"",d.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx(_Q,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),y.length>0&&a.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:y.map(([v,b])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),a.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},v))})]})]})}function rtt({printDates:t,dateFrom:e,dateTo:n}){const{days:r,hourlyCounts:i,maxCount:s}=w.useMemo(()=>{const u=new Date(e+"T00:00:00"),m=new Date(n+"T00:00:00"),p=[],f=g=>`${g.getFullYear()}-${String(g.getMonth()+1).padStart(2,"0")}-${String(g.getDate()).padStart(2,"0")}`,y=new Date(u);for(;y<=m;)p.push({key:f(y),label:y.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),y.setDate(y.getDate()+1);const v={};let b=0;return t.forEach(g=>{const _=Qn(g);if(!_)return;const P=`${`${_.getFullYear()}-${String(_.getMonth()+1).padStart(2,"0")}-${String(_.getDate()).padStart(2,"0")}`}-${_.getHours()}`;v[P]=(v[P]||0)+1,v[P]>b&&(b=v[P])}),{days:p,hourlyCounts:v,maxCount:Math.max(1,b)}},[t,e,n]),o=u=>{if(u===0)return"bg-bambu-dark";const m=u/s;return m<=.25?"bg-bambu-green/30":m<=.5?"bg-bambu-green/50":m<=.75?"bg-bambu-green/75":"bg-bambu-green"},l=20,c=2,d=80;return a.jsxs("div",{className:"w-full overflow-x-auto",children:[a.jsxs("div",{className:"inline-flex flex-col",style:{gap:c},children:[a.jsx("div",{className:"flex",style:{gap:c,marginLeft:d+4},children:UL.map((u,m)=>a.jsx("div",{className:"text-bambu-gray text-[10px] text-center",style:{width:l,visibility:m%2===0?"visible":"hidden"},children:u},m))}),r.map(u=>a.jsxs("div",{className:"flex items-center",style:{gap:c},children:[a.jsx("div",{className:"text-bambu-gray text-[10px] flex-shrink-0 truncate",style:{width:d},children:u.label}),Array.from({length:24},(m,p)=>{const f=i[`${u.key}-${p}`]||0;return a.jsx("div",{className:`rounded-sm ${o(f)}`,style:{width:l,height:l},title:`${u.label} ${UL[p]}: ${f} print${f!==1?"s":""}`},p)})]},u.key))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray text-xs",children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:c},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:l,height:l}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:l,height:l}})]}),a.jsx("span",{children:"More"})]})]})}function att({printDates:t,size:e=2,dateFrom:n,dateTo:r}){const i=w.useMemo(()=>n&&r?Math.max((new Date(r).getTime()-new Date(n).getTime())/864e5,0)+1:n?Math.max((Date.now()-new Date(n).getTime())/864e5,0)+1:1/0,[n,r]);if(i<=7&&n&&r)return a.jsx(rtt,{printDates:t,dateFrom:n,dateTo:r});const o=i===1/0?e===1?3:e===2?6:12:Math.max(1,Math.ceil(i/30));return a.jsx(Get,{printDates:t,months:o})}function itt({stats:t,archives:e,printerMap:n}){const{t:r}=Lt(),[i,s]=w.useState("weight"),[o,l]=w.useState("weight"),c=w.useMemo(()=>{const g=new Map;return t?.prints_by_printer&&Object.entries(t.prints_by_printer).forEach(([_,k])=>{const P=g.get(_)||{prints:0,weight:0,time:0};P.prints=k,g.set(_,P)}),e.forEach(_=>{if(!_.printer_id)return;const k=String(_.printer_id),P=g.get(k)||{prints:0,weight:0,time:0};P.weight+=_.filament_used_grams||0,P.time+=_.actual_time_seconds||_.print_time_seconds||0,t?.prints_by_printer||P.prints++,g.set(k,P)}),Array.from(g.entries()).map(([_,k])=>({name:n.get(_)||`${r("common.printer")} ${_}`,value:i==="prints"?k.prints:i==="weight"?Math.round(k.weight):Math.round(k.time/3600*10)/10})).sort((_,k)=>k.value-_.value)},[t,e,n,i,r]),d=w.useMemo(()=>{const g=Array.from({length:24},(_,k)=>({hour:k,label:UL[k],total:0,failures:0}));return e.forEach(_=>{if(!_.started_at)return;const k=Qn(_.started_at);if(!k)return;const P=k.getHours();g[P].total++,_.status==="failed"&&g[P].failures++}),g},[e]),u=w.useMemo(()=>{const g=i3.map(_=>({name:_.key,count:0}));return e.forEach(_=>{const k=_.actual_time_seconds||_.print_time_seconds;if(!(!k||k<=0)){for(let P=0;P{const g=[0,0,0,0,0,0,0],_=new Set;e.forEach(P=>{const N=Qn(P.created_at)||new Date(P.created_at);let M=N.getDay()-1;M<0&&(M=6),o==="prints"?g[M]++:o==="weight"?g[M]+=P.filament_used_grams||0:g[M]+=(P.actual_time_seconds||P.print_time_seconds||0)/3600;const T=new Date(N);T.setDate(N.getDate()-(N.getDay()+6)%7),_.add(`${T.getFullYear()}-${String(T.getMonth()+1).padStart(2,"0")}-${String(T.getDate()).padStart(2,"0")}`)});const k=Math.max(_.size,1);return Jet.map((P,N)=>({name:P,avg:Math.round(g[N]/k*10)/10}))},[e,o]),p=g=>({unit:g==="weight"?"g":g==="time"?"h":"",color:g==="weight"?"#00ae42":g==="time"?"#3b82f6":"#f59e0b"}),f=p(i),y=r(i==="weight"?"stats.filamentByWeight":i==="time"?"stats.hours":"common.prints"),v=p(o),b=r(o==="weight"?"stats.avgWeight":o==="time"?"stats.avgTime":"stats.avgPrints");return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printsByPrinter")}),a.jsx(bP,{value:i,onChange:s})]}),c.length>0?a.jsx(Sh,{width:"100%",height:Math.max(140,c.length*40),children:a.jsxs(W1,{data:c,layout:"vertical",margin:{left:10},children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),a.jsx(hf,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),a.jsx(_h,{contentStyle:hk,formatter:g=>[i==="weight"?gh(Number(g??0)):`${g??0}${f.unit}`,y]}),a.jsx(Hb,{dataKey:"value",fill:f.color,radius:[0,4,4,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noPrinterData")})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printDuration")}),e.length>0?a.jsx(Sh,{width:"100%",height:160,children:a.jsxs(W1,{data:u,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(_h,{contentStyle:hk}),a.jsx(Hb,{dataKey:"count",name:r("common.prints"),fill:"#00ae42",radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printHabits")}),a.jsx(bP,{value:o,onChange:l})]}),e.length>0?a.jsx(Sh,{width:"100%",height:160,children:a.jsxs(W1,{data:m,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},unit:v.unit}),a.jsx(_h,{contentStyle:hk,formatter:g=>[`${g??0}${v.unit}`,b]}),a.jsx(Hb,{dataKey:"avg",fill:v.color,radius:[4,4,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printTimeOfDay")}),e.length>0?a.jsx(Sh,{width:"100%",height:160,children:a.jsxs(W1,{data:d,children:[a.jsx(uf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(mf,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),a.jsx(hf,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(_h,{contentStyle:hk}),a.jsx(Hb,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),a.jsx(Hb,{dataKey:"failures",name:r("stats.failed"),fill:"#ef4444",radius:[2,2,0,0]})]})}):a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]})]})]})}function stt({archives:t,currency:e,dateFrom:n,dateTo:r}){const{t:i}=Lt();return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):a.jsx(Ket,{archives:t,currency:e,dateFrom:n,dateTo:r})}function ott({size:t=1,dateFrom:e,dateTo:n,createdById:r}){const{t:i}=Lt(),s=!!(e||n),{data:o,isLoading:l}=et({queryKey:["failureAnalysis",e,n,r??"all"],queryFn:()=>he.getFailureAnalysis({...s?{dateFrom:e,dateTo:n}:{days:30},createdById:r})});if(l)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!o||o.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i(s?"stats.noPrintDataInRange":"stats.noPrintDataLast30Days")});const c=t===1?5:t===2?8:999,d=Object.entries(o.failures_by_reason).sort(([,p],[,f])=>f-p),u=d.slice(0,c),m=d.length>c;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ln,{className:`w-5 h-5 ${o.failure_rate>20?"text-status-error":o.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[o.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:i("stats.failedPrintsCount",{failed:o.failed_prints,total:o.total_prints})}),o.trend&&o.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(fO,{className:`w-4 h-4 ${o.trend[o.trend.length-1].failure_rate0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?i("stats.failureReasons"):i("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:u.map(([p,f])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:p||i("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:f})]},p))}),m&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("common.more",{count:d.length-c})})]})]})}function ltt({archives:t,currency:e}){const{t:n}=Lt(),r=w.useMemo(()=>{const i=[];if(t.length===0)return i;const s=y=>{let v=null,b=0;return t.forEach(g=>{const _=y(g);_&&_>b&&(b=_,v=g)}),{archive:v,value:b}},o=s(y=>y.actual_time_seconds);o.archive&&i.push({icon:rr,iconColor:"text-blue-400",label:n("stats.longestPrint"),value:ls(o.value),detail:o.archive.print_name||null});const l=s(y=>y.filament_used_grams);l.archive&&i.push({icon:Na,iconColor:"text-orange-400",label:n("stats.heaviestPrint"),value:gh(l.value),detail:l.archive.print_name||null});const c=s(y=>y.cost);c.archive&&i.push({icon:Zk,iconColor:"text-green-400",label:n("stats.mostExpensivePrint"),value:`${e}${c.value.toFixed(2)}`,detail:c.archive.print_name||null});const d=new Map;t.forEach(y=>{const v=Qn(y.created_at)||new Date(y.created_at),b=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`;d.set(b,(d.get(b)||0)+1)});let u="",m=0;d.forEach((y,v)=>{y>m&&(m=y,u=v)}),m>1&&i.push({icon:Wr,iconColor:"text-purple-400",label:n("stats.busiestDay"),value:`${m} ${n("common.prints")}`,detail:(()=>{const[y,v,b]=u.split("-").map(Number);return new Date(y,v-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(y=>y.status==="completed"||y.status==="failed").sort((y,v)=>new Date(v.completed_at||v.created_at).getTime()-new Date(y.completed_at||y.created_at).getTime());let f=0;for(const y of p)if(y.status==="completed")f++;else break;return f>0&&i.push({icon:Xl,iconColor:"text-yellow-400",label:n("stats.successStreak"),value:`${f}`,detail:f===1?n("stats.streakPrint"):n("stats.streakPrints",{count:f})}),i},[t,e,n]);return r.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noArchiveData")}):a.jsx("div",{className:"space-y-3",children:r.map((i,s)=>a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-1.5 rounded-lg bg-bambu-dark ${i.iconColor}`,children:a.jsx(i.icon,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),a.jsxs("div",{className:"flex items-baseline gap-2",children:[a.jsx("span",{className:"text-sm font-bold text-white",children:i.value}),i.detail&&a.jsx("span",{className:"text-xs text-bambu-gray truncate",children:i.detail})]})]})]},s))})}function ctt(){const{t}=Lt(),{showToast:e}=xn(),{hasPermission:n,authEnabled:r}=Sr(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(0),[u,m]=w.useState(0),[p,f]=w.useState(!1),[y,v]=w.useState(null),[b,g]=w.useState(!1),_=r&&n("stats:filter_by_user"),[k,P]=w.useState(()=>{try{const Y=localStorage.getItem("bambusy-stats-timeframe");if(Y){const D=JSON.parse(Y);if(D.preset)return D}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[N,M]=w.useState(!1);w.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(k))},[k]);const T=w.useMemo(()=>k.preset==="custom"?{dateFrom:k.dateFrom,dateTo:k.dateTo}:Qet(k.preset),[k]);w.useEffect(()=>{const Y=()=>{try{const j=localStorage.getItem("bambusy-dashboard-layout-v2");if(j){const z=JSON.parse(j);m(z.hidden?.length||0)}}catch{m(0)}};Y(),window.addEventListener("storage",Y);const D=setInterval(Y,2e3);return()=>{window.removeEventListener("storage",Y),clearInterval(D)}},[c]);const A=y!==null?y:void 0,{data:C,isLoading:F,isFetching:$,refetch:I}=et({queryKey:["archiveStats",T.dateFrom,T.dateTo,A??"all"],queryFn:()=>he.getArchiveStats({dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:A})}),{data:Q}=et({queryKey:["printers"],queryFn:he.getPrinters}),{data:L,isFetching:re,refetch:ae}=et({queryKey:["archivesSlim",T.dateFrom,T.dateTo,A??"all"],queryFn:()=>he.getArchivesSlim(T.dateFrom,T.dateTo,A)}),{data:ee}=et({queryKey:["settings"],queryFn:he.getSettings}),{data:ue}=et({queryKey:["users"],queryFn:he.getUsers,enabled:_}),le=w.useMemo(()=>y===null?t("stats.allUsers","All Users"):y===-1?t("stats.noUser","No User (System)"):ue?.find(Y=>Y.id===y)?.username??"?",[y,ue,t]),de=async Y=>{l(!1),s(!0);try{const{blob:D,filename:j}=await he.exportStats({format:Y,days:90,createdById:A}),z=URL.createObjectURL(D),W=document.createElement("a");W.href=z,W.download=j,W.click(),URL.revokeObjectURL(z),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},K=async()=>{f(!0);try{const Y=await he.recalculateCosts();await Promise.all([I(),ae()]),e(t("stats.recalculatedCosts",{count:Y.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},te=($||re)&&!F,se=yo(ee?.currency||"USD"),be=new Map(Q?.map(Y=>[String(Y.id),Y.name])||[]),Ne=w.useMemo(()=>L?.map(Y=>Y.created_at)||[],[L]);if(F)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const B=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(ett,{stats:C,currency:se}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:Y=>a.jsx(ttt,{stats:C,printerMap:be,size:Y}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:Y=>a.jsx(ntt,{stats:C,printerMap:be,size:Y}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:Y=>a.jsx(ott,{size:Y,dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:A}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:Y=>a.jsx(att,{printDates:Ne,size:Y,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:a.jsx(ltt,{archives:L||[],currency:se}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:a.jsx(itt,{stats:C,archives:L||[],printerMap:be}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(stt,{archives:L||[],currency:se,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),te&&a.jsx(ct,{className:"w-5 h-5 text-bambu-green animate-spin"})]}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Ie,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(Dc,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(Y=>Y+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(jo,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Ie,{variant:"secondary",onClick:K,disabled:p||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(bpe,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(eN,{className:"w-4 h-4"}),t("stats.exportStats")]}),o&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>de("csv"),children:[a.jsx(Ms,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>de("xlsx"),children:[a.jsx(eN,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),_&&ue&&ue.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>g(!b),children:[a.jsx(_u,{className:"w-4 h-4"}),le,a.jsx(Fn,{className:"w-3 h-3"})]}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2 max-h-64 overflow-y-auto",children:[a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===null?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(null),g(!1)},children:t("stats.allUsers","All Users")}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===-1?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(-1),g(!1)},children:t("stats.noUser","No User (System)")}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-1"}),ue.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${y===Y.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(Y.id),g(!1)},children:Y.username},Y.id))]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>M(!N),children:[a.jsx(Wr,{className:"w-4 h-4"}),t(`stats.timeframe.${k.preset}`),a.jsx(Fn,{className:"w-3 h-3"})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>M(!1)}),a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2",children:[Zet.map(Y=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset===Y?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{P({preset:Y,dateFrom:void 0,dateTo:void 0}),M(!1)},children:t(`stats.timeframe.${Y}`)},Y)),a.jsx("div",{className:"border-t border-bambu-dark-tertiary my-2"}),a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${k.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>P(Y=>({...Y,preset:"custom"})),children:t("stats.timeframe.custom")}),k.preset==="custom"&&a.jsxs("div",{className:"mt-2 px-1 pb-1 space-y-2",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.from")}),a.jsx("input",{type:"date",value:k.dateFrom||"",max:k.dateTo||new Date().toISOString().split("T")[0],onChange:Y=>P(D=>({...D,dateFrom:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.to")}),a.jsx("input",{type:"date",value:k.dateTo||"",min:k.dateFrom,max:new Date().toISOString().split("T")[0],onChange:Y=>P(D=>({...D,dateTo:Y.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),a.jsx(Ie,{variant:"primary",onClick:()=>M(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),a.jsx(Xet,{widgets:B,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function lle({summary:t,children:e,defaultOpen:n=!1,className:r="",summaryClassName:i=""}){const[s,o]=w.useState(n);return a.jsxs("div",{className:r,children:[a.jsxs("button",{type:"button",onClick:()=>o(l=>!l),className:`w-full flex items-center justify-between gap-2 text-left ${i}`,"aria-expanded":s,children:[a.jsx("div",{className:"flex-1 min-w-0",children:t}),a.jsx(Fn,{className:`w-4 h-4 text-bambu-gray flex-shrink-0 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsx("div",{className:"mt-3",children:e})]})}function dtt({plug:t,onEdit:e}){const{t:n}=Lt(),r=mn(),{showToast:i}=xn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[d,u]=w.useState(!1),[m,p]=w.useState(!1),{data:f,isLoading:y}=et({queryKey:["smart-plug-status",t.id],queryFn:()=>he.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=et({queryKey:["printers"],queryFn:he.getPrinters}),b=v?.find(F=>F.id===t.printer_id),g=lt({mutationFn:F=>he.controlSmartPlug(t.id,F),onMutate:async F=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const $=r.getQueryData(["smart-plug-status",t.id]),I=F==="on"?"ON":F==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],Q=>({...Q,state:I})),{previousStatus:$}},onError:(F,$,I)=>{I?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],I.previousStatus),i(n("smartPlugs.failedToTurn",{action:$,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=lt({mutationFn:F=>he.updateSmartPlug(t.id,F),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),k=lt({mutationFn:()=>he.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),P=f?.state==="ON",N=t.plug_type==="mqtt"&&f?.energy?.power!==null&&f?.energy?.power!==void 0,M=(f?.reachable??!1)||N,T=g.isPending,C=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const F=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${F}/`:`http://${F}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(Dt,{className:"relative",children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?M?"bg-teal-500/20":"bg-red-500/20":M?P?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(pO,{className:`w-5 h-5 ${M?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Mw,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?a.jsx(yd,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(ql,{className:`w-5 h-5 ${M?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.plug_type==="rest"?t.rest_on_url??t.rest_off_url??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.plug_type==="rest"?t.rest_on_url||t.rest_off_url:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[y?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),M&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:M?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?f?.state||"?":n("smartPlugs.offline")})]}):t.plug_type==="rest"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-purple-500/20 text-purple-400 text-[10px] font-medium rounded",children:"REST"}),a.jsx("span",{className:M?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?f?.state||"?":n("smartPlugs.offline")})]}):M?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(vf,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:P?"text-status-ok":"text-bambu-gray",children:f?.state||n("smartPlugs.unknown")})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(Wu,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),C&&a.jsxs("a",{href:C,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[a.jsx(sa,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),b&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("smartPlugs.linkedTo")," "]}),a.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[a.jsx(Dc,{className:"w-3 h-3"}),n("smartPlugs.monitorOnly")]}),t.power_alert_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[a.jsx(Th,{className:"w-3 h-3"}),n("smartPlugs.alerts")]}),t.schedule_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[a.jsx(Wr,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?n("smartPlugs.scheduleOn",{time:t.schedule_on_time}):n("smartPlugs.scheduleOff",{time:t.schedule_off_time})]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Ie,{size:"sm",variant:P?"primary":"secondary",disabled:!M||T,onClick:()=>c(!0),className:"flex-1",children:[T?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(am,{className:"w-4 h-4"}),n("smartPlugs.on")]}),a.jsxs(Ie,{size:"sm",variant:P?"secondary":"primary",disabled:!M||T,onClick:()=>u(!0),className:"flex-1",children:[T?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Rw,{className:"w-4 h-4"}),n("smartPlugs.off")]})]}),t.plug_type==="mqtt"&&f?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[f.energy.power!==null&&f.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(f.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.power")})]}),f.energy.today!==null&&f.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:f.energy.today.toFixed(3)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.kwhToday")})]})]}),a.jsxs("button",{onClick:()=>p(!m),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Nd,{className:"w-4 h-4"}),t.plug_type==="mqtt"?n("smartPlugs.settings"):n("smartPlugs.automationSettings")]}),a.jsx("span",{children:m?"-":"+"})]}),m&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:F=>_.mutate({show_in_switchbar:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.enableAutomation")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:F=>_.mutate({enabled:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOn")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOnDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:F=>_.mutate({auto_on:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOff")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:F=>_.mutate({auto_off:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("smartPlugs.autoOffPersistent")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.autoOffPersistentDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off_persistent,onChange:F=>_.mutate({auto_off_persistent:F.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:n("smartPlugs.turnOffDelayMode")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(rr,{className:"w-4 h-4"}),n("smartPlugs.time")]}),a.jsxs("button",{onClick:()=>_.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(PP,{className:"w-4 h-4"}),n("smartPlugs.temp")]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.delayMinutes")}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:F=>_.mutate({off_delay_minutes:parseInt(F.target.value)||5}),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"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("smartPlugs.tempThreshold")}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:F=>_.mutate({off_temp_threshold:parseInt(F.target.value)||70}),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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.tempThresholdDescription")})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bh,{className:"w-4 h-4"}),n("smartPlugs.edit")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(kn,{title:n("smartPlugs.deleteSmartPlug"),message:n("smartPlugs.deleteConfirm",{name:t.name}),confirmText:n("smartPlugs.delete"),variant:"danger",onConfirm:()=>{k.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(kn,{title:n("smartPlugs.turnOnSmartPlug"),message:n("smartPlugs.turnOnConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{g.mutate("on"),c(!1)},onCancel:()=>c(!1)}),d&&a.jsx(kn,{title:n("smartPlugs.turnOffSmartPlug"),message:n("smartPlugs.turnOffConfirm",{name:t.name}),confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{g.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function utt({plug:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[d,u]=w.useState(t?.ip_address||""),[m,p]=w.useState(t?.username||""),[f,y]=w.useState(t?.password||""),[v,b]=w.useState(t?.ha_entity_id||""),[g,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[k,P]=w.useState(t?.mqtt_power_path||""),[N,M]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[T,A]=w.useState(t?.mqtt_energy_topic||""),[C,F]=w.useState(t?.mqtt_energy_path||""),[$,I]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[Q,L]=w.useState(t?.mqtt_state_topic||""),[re,ae]=w.useState(t?.mqtt_state_path||""),[ee,ue]=w.useState(t?.mqtt_state_on_value||""),[le,de]=w.useState(t?.rest_on_url||""),[K,te]=w.useState(t?.rest_on_body||""),[se,be]=w.useState(t?.rest_off_url||""),[Ne,B]=w.useState(t?.rest_off_body||""),[Y,D]=w.useState(t?.rest_method||"POST"),[j,z]=w.useState(t?.rest_headers||""),[W,q]=w.useState(t?.rest_status_url||""),[ce,O]=w.useState(t?.rest_status_path||""),[G,X]=w.useState(t?.rest_status_on_value||""),[V,J]=w.useState(t?.rest_power_url||""),[ie,me]=w.useState(t?.rest_power_path||""),[pe,oe]=w.useState((t?.rest_power_multiplier??1).toString()),[U,R]=w.useState(t?.rest_energy_url||""),[ne,xe]=w.useState(t?.rest_energy_path||""),[Se,ye]=w.useState((t?.rest_energy_multiplier??1).toString()),[ve,fe]=w.useState(t?.ha_power_entity||""),[ke,Ee]=w.useState(t?.ha_energy_today_entity||""),[Ae,_e]=w.useState(t?.ha_energy_total_entity||""),[je,Be]=w.useState(""),[Re,Ye]=w.useState(""),[we,$e]=w.useState(!1),De=w.useRef(null),[Xe,Ve]=w.useState(""),[Te,Me]=w.useState(!1),qe=w.useRef(null),[tt,ut]=w.useState(""),[xt,wt]=w.useState(!1),Ht=w.useRef(null),[Xt,Kt]=w.useState(""),[Ut,en]=w.useState(!1),We=w.useRef(null),[Ft,Nt]=w.useState(t?.printer_id||null),[ht,Mt]=w.useState(null),[Qt,Wt]=w.useState(null),[ze,dt]=w.useState(t?.power_alert_enabled||!1),[pt,Fe]=w.useState(t?.power_alert_high?.toString()||""),[Le,at]=w.useState(t?.power_alert_low?.toString()||""),[Pe,Ge]=w.useState(t?.schedule_enabled||!1),[Ke,Qe]=w.useState(t?.schedule_on_time||""),[Ze,rt]=w.useState(t?.schedule_off_time||""),[bt,Pt]=w.useState(t?.show_in_switchbar||!1),[vt,He]=w.useState(t?.show_on_printer_card??!0),[St,Ct]=w.useState(!1),[Zt,Jt]=w.useState({scanned:0,total:0}),[Nn,vn]=w.useState([]),yn=w.useRef(null),{data:an}=et({queryKey:["printers"],queryFn:he.getPrinters}),{data:rn}=et({queryKey:["smart-plugs"],queryFn:he.getSmartPlugs}),{data:bn}=et({queryKey:["settings"],queryFn:he.getSettings}),Gn=!!(bn?.ha_enabled&&bn?.ha_url&&bn?.ha_token);w.useEffect(()=>{const jt=setTimeout(()=>{Ye(je)},300);return()=>clearTimeout(jt)},[je]),w.useEffect(()=>{const jt=Wn=>{De.current&&!De.current.contains(Wn.target)&&$e(!1),qe.current&&!qe.current.contains(Wn.target)&&Me(!1),Ht.current&&!Ht.current.contains(Wn.target)&&wt(!1),We.current&&!We.current.contains(Wn.target)&&en(!1)};return document.addEventListener("mousedown",jt),()=>document.removeEventListener("mousedown",jt)},[]);const{data:ar,isLoading:On,error:mi}=et({queryKey:["ha-entities",Re],queryFn:()=>he.getHAEntities(Re||void 0),enabled:s==="homeassistant"&&Gn,retry:!1,staleTime:0}),{data:Rn}=et({queryKey:["ha-sensor-entities"],queryFn:he.getHASensorEntities,enabled:s==="homeassistant"&&Gn,retry:!1,staleTime:0});w.useEffect(()=>{const jt=Wn=>{Wn.key==="Escape"&&e()};return window.addEventListener("keydown",jt),()=>{window.removeEventListener("keydown",jt),yn.current&&clearInterval(yn.current)}},[e]);const na=async()=>{Ct(!0),vn([]),Jt({scanned:0,total:0}),Wt(null);try{await he.startTasmotaScan();const jt=async()=>{try{const Wn=await he.getTasmotaScanStatus();Jt({scanned:Wn.scanned,total:Wn.total});const En=await he.getDiscoveredTasmotaDevices();vn(En),Wn.running||(Ct(!1),yn.current&&(clearInterval(yn.current),yn.current=null))}catch(Wn){console.error("Polling error:",Wn)}};await jt(),yn.current=setInterval(jt,500)}catch(jt){Ct(!1);const Wn=jt instanceof Error?jt.message:typeof jt=="string"?jt:JSON.stringify(jt);Wt(Wn||n("smartPlugs.failedToStartScan"))}},ra=async()=>{try{await he.stopTasmotaScan()}catch{}Ct(!1),yn.current&&(clearInterval(yn.current),yn.current=null)},jr=jt=>{u(jt.ip_address),c(jt.name),Mt(null)},In=lt({mutationFn:()=>he.testSmartPlugConnection(d,m||null,f||null),onSuccess:jt=>{Mt(jt),Wt(null),!l&&jt.device_name&&c(jt.device_name)},onError:jt=>{Mt(null),Wt(jt.message)}}),Bi=lt({mutationFn:jt=>he.createSmartPlug(jt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:jt=>{Wt(jt.message)}}),Hi=lt({mutationFn:jt=>he.updateSmartPlug(t.id,jt),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:jt=>{Wt(jt.message)}}),Ci=an?.filter(jt=>s==="tasmota"?!rn?.some(En=>En.printer_id===jt.id&&En.id!==t?.id&&En.plug_type==="tasmota"):!0),Hc=jt=>{if(jt.preventDefault(),Wt(null),!l.trim()){Wt(n("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Wt("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Wt(n("smartPlugs.entityRequired"));return}if(s==="mqtt"){const En=g.trim(),Vt=T.trim(),sc=Q.trim();if(!En&&!Vt&&!sc){Wt(n("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!le.trim()&&!se.trim()){Wt(n("smartPlugs.restUrlRequired"));return}const Wn={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?d.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&ve||null,ha_energy_today_entity:s==="homeassistant"&&ke||null,ha_energy_total_entity:s==="homeassistant"&&Ae||null,mqtt_power_topic:s==="mqtt"&&g.trim()||null,mqtt_power_path:s==="mqtt"&&k.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(N)||1,mqtt_energy_topic:s==="mqtt"&&T.trim()||null,mqtt_energy_path:s==="mqtt"&&C.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat($)||1,mqtt_state_topic:s==="mqtt"&&Q.trim()||null,mqtt_state_path:s==="mqtt"&&re.trim()||null,mqtt_state_on_value:s==="mqtt"&&ee.trim()||null,rest_on_url:s==="rest"&&le.trim()||null,rest_on_body:s==="rest"&&K.trim()||null,rest_off_url:s==="rest"&&se.trim()||null,rest_off_body:s==="rest"&&Ne.trim()||null,rest_method:s==="rest"?Y:null,rest_headers:s==="rest"&&j.trim()||null,rest_status_url:s==="rest"&&W.trim()||null,rest_status_path:s==="rest"&&ce.trim()||null,rest_status_on_value:s==="rest"&&G.trim()||null,rest_power_url:s==="rest"&&V.trim()||null,rest_power_path:s==="rest"&&ie.trim()||null,rest_power_multiplier:s==="rest"&&parseFloat(pe)||1,rest_energy_url:s==="rest"&&U.trim()||null,rest_energy_path:s==="rest"&&ne.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(Se)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:Ft,power_alert_enabled:ze,power_alert_high:pt?parseFloat(pt):null,power_alert_low:Le?parseFloat(Le):null,schedule_enabled:Pe,schedule_on_time:Ke||null,schedule_off_time:Ze||null,show_in_switchbar:bt,show_on_printer_card:vt};i?Hi.mutate(Wn):Bi.mutate(Wn)},pa=Bi.isPending||Hi.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:jt=>jt.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"smartPlugs.editTitle":"smartPlugs.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Hc,className:"p-6 space-y-4 overflow-y-auto",children:[Qt&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Qt}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(ql,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(Mw,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(pO,{className:"w-4 h-4"}),"MQTT"]}),a.jsxs("button",{type:"button",onClick:()=>{o("rest"),Mt(null),Wt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="rest"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(yd,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[St?a.jsxs(Ie,{type:"button",variant:"secondary",onClick:ra,className:"w-full",children:[a.jsx(Bt,{className:"w-4 h-4"}),n("smartPlugs.stopScanning")]}):a.jsxs(Ie,{type:"button",variant:"primary",onClick:na,className:"w-full",children:[a.jsx(Cr,{className:"w-4 h-4"}),n("smartPlugs.discoverTasmota")]}),St&&Zt.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Zt.scanned," / ",Zt.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Zt.scanned/Zt.total*100}%`}})})]}),Nn.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.foundDevices",{count:Nn.length})}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Nn.map(jt=>a.jsxs("button",{type:"button",onClick:()=>jr(jt),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ql,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:jt.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:jt.ip_address})]})]}),jt.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${jt.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(am,{className:"w-3 h-3"}),jt.state]})]},jt.ip_address))})]}),!St&&Nn.length===0&&Zt.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:n("smartPlugs.noDevicesFound")})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!Gn&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.haNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.haSettingsPath")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:n("smartPlugs.selectEntity")}),a.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),Gn&&a.jsxs(a.Fragment,{children:[On&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),n("smartPlugs.loadingEntities")]}),mi&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:n("smartPlugs.failedToLoadEntities",{error:mi.message})}),(()=>{const jt=rn?.filter(Vt=>Vt.ha_entity_id&&Vt.id!==t?.id).map(Vt=>Vt.ha_entity_id)||[],Wn=(ar||[]).filter(Vt=>!jt.includes(Vt.entity_id)),En=ar?.find(Vt=>Vt.entity_id===v);return a.jsxs("div",{ref:De,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.selectEntity")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:we?je:En?`${En.friendly_name} (${En.entity_id})`:"",onChange:Vt=>{Be(Vt.target.value),we||$e(!0)},onFocus:()=>{$e(!0),Be("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),v&&!we&&a.jsx("button",{type:"button",onClick:()=>{b(""),Be("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),On&&a.jsx(ct,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),we&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[On&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("smartPlugs.loading")]}),!On&&Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Re?n("smartPlugs.noEntitiesMatching",{search:Re}):n("smartPlugs.noEntitiesAvailable")}),!On&&Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{b(Vt.entity_id),$e(!1),Be(""),l||c(Vt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Vt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:Vt.entity_id}),a.jsx("span",{className:Vt.state==="on"?"text-bambu-green":"",children:Vt.state})]})]},Vt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Re?n("smartPlugs.searchingEntities",{count:Wn.length}):n("smartPlugs.showingEntities",{count:Wn.length})})]})})(),v&&Rn&&Rn.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:n("smartPlugs.energyMonitoringOptional")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:n("smartPlugs.energyMonitoringHint")})]}),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="W"||Vt.unit_of_measurement==="kW"||Vt.unit_of_measurement==="mW"),Wn=Xe?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(Xe.toLowerCase())||Vt.friendly_name.toLowerCase().includes(Xe.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===ve);return a.jsxs("div",{ref:qe,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.powerSensorW")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:Te?Xe:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{Ve(Vt.target.value),Te||Me(!0)},onFocus:()=>{Me(!0),Ve("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ve&&!Te&&a.jsx("button",{type:"button",onClick:()=>{fe(""),Ve("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Te&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{fe(""),Me(!1),Ve("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{fe(Vt.entity_id),Me(!1),Ve("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===ve?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="kWh"||Vt.unit_of_measurement==="Wh"||Vt.unit_of_measurement==="MWh"),Wn=tt?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(tt.toLowerCase())||Vt.friendly_name.toLowerCase().includes(tt.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===ke);return a.jsxs("div",{ref:Ht,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.energyTodayKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:xt?tt:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{ut(Vt.target.value),xt||wt(!0)},onFocus:()=>{wt(!0),ut("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ke&&!xt&&a.jsx("button",{type:"button",onClick:()=>{Ee(""),ut("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),xt&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{Ee(""),wt(!1),ut("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{Ee(Vt.entity_id),wt(!1),ut("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===ke?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const jt=Rn.filter(Vt=>Vt.unit_of_measurement==="kWh"||Vt.unit_of_measurement==="Wh"||Vt.unit_of_measurement==="MWh"),Wn=Xt?jt.filter(Vt=>Vt.entity_id.toLowerCase().includes(Xt.toLowerCase())||Vt.friendly_name.toLowerCase().includes(Xt.toLowerCase())):jt,En=Rn.find(Vt=>Vt.entity_id===Ae);return a.jsxs("div",{ref:We,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.totalEnergyKwh")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:Ut?Xt:En?`${En.friendly_name} (${En.state} ${En.unit_of_measurement})`:"",onChange:Vt=>{Kt(Vt.target.value),Ut||en(!0)},onFocus:()=>{en(!0),Kt("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Ae&&!Ut&&a.jsx("button",{type:"button",onClick:()=>{_e(""),Kt("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Bt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Ut&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{_e(""),en(!1),Kt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Wn.map(Vt=>a.jsxs("button",{type:"button",onClick:()=>{_e(Vt.entity_id),en(!1),Kt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Vt.entity_id===Ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:Vt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[Vt.entity_id," • ",Vt.state," ",Vt.unit_of_measurement]})]},Vt.entity_id)),Wn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!bn?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[n("smartPlugs.mqttNotConfigured")," ",a.jsx("span",{className:"font-medium",children:n("smartPlugs.mqttSettingsPath")})," ",n("smartPlugs.mqttNotConfiguredSuffix")]}),bn?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:n("smartPlugs.monitorOnly")}),a.jsx("p",{className:"text-xs opacity-80",children:n("smartPlugs.mqttMonitorOnlyDescription")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.powerMonitoring")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:g,onChange:jt=>_(jt.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:k,onChange:jt=>P(jt.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:N,onChange:jt=>M(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttPowerHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:T,onChange:jt=>A(jt.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:C,onChange:jt=>F(jt.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.multiplier")}),a.jsx("input",{type:"text",value:$,onChange:jt=>I(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttEnergyHint")})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.topic")}),a.jsx("input",{type:"text",value:Q,onChange:jt=>L(jt.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.jsonPath")}),a.jsx("input",{type:"text",value:re,onChange:jt=>ae(jt.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.onValue")}),a.jsx("input",{type:"text",value:ee,onChange:jt=>ue(jt.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:n("smartPlugs.mqttStateHint")})]})]})]}),s==="rest"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:n("smartPlugs.restControl")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restMethod")}),a.jsxs("select",{value:Y,onChange:jt=>D(jt.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"GET",children:"GET"}),a.jsx("option",{value:"POST",children:"POST"}),a.jsx("option",{value:"PUT",children:"PUT"}),a.jsx("option",{value:"PATCH",children:"PATCH"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOnUrl")}),a.jsx("input",{type:"text",value:le,onChange:jt=>{de(jt.target.value),Mt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOnBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:K,onChange:jt=>te(jt.target.value),placeholder:n("smartPlugs.restBodyHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restOffUrl")}),a.jsx("input",{type:"text",value:se,onChange:jt=>{be(jt.target.value),Mt(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restOffBody")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:Ne,onChange:jt=>B(jt.target.value),placeholder:n("smartPlugs.restBodyHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.restHeaders")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("div",{children:a.jsx("textarea",{value:j,onChange:jt=>z(jt.target.value),placeholder:n("smartPlugs.restHeadersHint"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none font-mono text-sm"})})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.stateMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusUrl")}),a.jsx("input",{type:"text",value:W,onChange:jt=>q(jt.target.value),placeholder:n("smartPlugs.restStatusHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusPath")}),a.jsx("input",{type:"text",value:ce,onChange:jt=>O(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restStatusOnValue")}),a.jsx("input",{type:"text",value:G,onChange:jt=>X(jt.target.value),placeholder:"ON",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:[n("smartPlugs.energyMonitoring")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restPowerUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:V,onChange:jt=>J(jt.target.value),placeholder:n("smartPlugs.restPowerUrlHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerPath")}),a.jsx("input",{type:"text",value:ie,onChange:jt=>me(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restPowerMultiplier")}),a.jsx("input",{type:"text",value:pe,onChange:jt=>oe(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("smartPlugs.restEnergyUrl")," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",n("smartPlugs.optional"),")"]})]}),a.jsx("input",{type:"text",value:U,onChange:jt=>R(jt.target.value),placeholder:n("smartPlugs.restEnergyUrlHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyPath")}),a.jsx("input",{type:"text",value:ne,onChange:jt=>xe(jt.target.value),placeholder:n("smartPlugs.restPathHint"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.restEnergyMultiplier")}),a.jsx("input",{type:"text",value:Se,onChange:jt=>ye(jt.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.restEnergyHint")})]}),(le.trim()||se.trim())&&a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ie,{type:"button",variant:"secondary",onClick:async()=>{Mt(null);try{const jt=le.trim()||se.trim(),Wn=await he.testRESTConnection(jt,Y,j.trim()||null);Mt({success:Wn.success}),Wn.success||Wt(Wn.error||n("smartPlugs.addSmartPlug.connectionFailed"))}catch{Mt({success:!1}),Wt(n("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[a.jsx(vf,{className:"w-4 h-4"}),n("smartPlugs.testConnection")]})}),ht&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${ht.success?"text-green-400":"text-red-400"}`,children:[ht.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx(Wu,{className:"w-4 h-4"}),ht.success?n("smartPlugs.connectionSuccess"):n("smartPlugs.addSmartPlug.connectionFailed")]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.ipAddress")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:d,onChange:jt=>{u(jt.target.value),Mt(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs(Ie,{type:"button",variant:"secondary",onClick:()=>In.mutate(),disabled:!d.trim()||In.isPending,children:[In.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vf,{className:"w-4 h-4"}),n("smartPlugs.test")]})]})]}),s==="tasmota"&&ht&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ht.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:ht.success?a.jsxs(a.Fragment,{children:[a.jsx(fr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:n("smartPlugs.connectedResult")}),a.jsxs("p",{className:"text-sm opacity-80",children:[ht.device_name&&n("smartPlugs.deviceLabel",{name:ht.device_name}),n("smartPlugs.stateLabel",{state:ht.state})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Wu,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.nameLabel")}),a.jsx("input",{type:"text",value:l,onChange:jt=>c(jt.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),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"})]}),s==="tasmota"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.username")}),a.jsx("input",{type:"text",value:m,onChange:jt=>p(jt.target.value),placeholder:"admin",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.password")}),a.jsx("input",{type:"password",value:f,onChange:jt=>y(jt.target.value),placeholder:"********",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:n("smartPlugs.authHint")})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.linkToPrinter")}),a.jsxs("select",{value:Ft??"",onChange:jt=>Nt(jt.target.value?Number(jt.target.value):null),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:[a.jsx("option",{value:"",children:n("smartPlugs.noPrinter")}),Ci?.map(jt=>a.jsx("option",{value:jt.id,children:jt.name},jt.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("smartPlugs.linkingDescription")})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Th,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.powerAlerts")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ze,onChange:jt=>dt(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ze&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertAbove")}),a.jsx("input",{type:"number",value:pt,onChange:jt=>Fe(jt.target.value),placeholder:"e.g. 200",min:"0",max:"5000",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.alertBelow")}),a.jsx("input",{type:"number",value:Le,onChange:jt=>at(jt.target.value),placeholder:"e.g. 10",min:"0",max:"5000",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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.alertDescription")})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.dailySchedule")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Pe,onChange:jt=>Ge(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Pe&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOnAt")}),a.jsx("input",{type:"time",value:Ke,onChange:jt=>Qe(jt.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("smartPlugs.turnOffAt")}),a.jsx("input",{type:"time",value:Ze,onChange:jt=>rt(jt.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"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.scheduleDescription")})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(jw,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showInSwitchbar")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.quickAccessSidebar")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:bt,onChange:jt=>Pt(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Dc,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:n("smartPlugs.showOnPrinterCard")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.displayOnPrinterCard")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:vt,onChange:jt=>He(jt.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("smartPlugs.cancel")}),a.jsxs(Ie,{type:"submit",disabled:pa,className:"flex-1",children:[pa?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),n(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function Vn({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:a.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}function mtt({provider:t,onEdit:e}){const{t:n}=Lt(),r=mn(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(null),{data:u}=et({queryKey:["printers"],queryFn:he.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=lt({mutationFn:b=>he.updateNotificationProvider(t.id,b),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=lt({mutationFn:()=>he.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),y=lt({mutationFn:()=>he.testNotificationProvider(t.id),onSuccess:b=>{d(b),r.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{d({success:!1,message:b.message})}}),v=b=>b||"";return a.jsxs(a.Fragment,{children:[a.jsx(Dt,{className:"relative",children:a.jsxs(Rt,{className:"p-3",children:[a.jsxs("div",{className:`flex items-start justify-between ${t.enabled?"mb-3":"mb-0"}`,children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(Th,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n(`notifications.providerTypes.${t.provider_type}`,t.provider_type)})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsx("span",{className:"text-xs text-status-ok hidden sm:inline",children:n("notifications.lastSuccess",{date:Uf(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Qn(t.last_error_at)?.getTime()||0)>(Qn(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:n("notifications.error")}),a.jsx(Vn,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]})]}),t.enabled&&a.jsxs(a.Fragment,{children:[m&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsxs("span",{className:"text-xs text-bambu-gray",children:[n("notifications.printer")," "]}),a.jsx("span",{className:"text-sm text-white",children:m.name})]}),!m&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.allPrinters")})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:n("notifications.start")}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:n("notifications.plateCheck")}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:n("notifications.complete")}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:n("notifications.failed")}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:n("notifications.stopped")}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:n("notifications.progress")}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:n("notifications.offline")}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:n("notifications.error")}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:n("notifications.lowFilament")}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:n("notifications.maintenance")}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:n("notifications.amsHumidity")}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:n("notifications.amsTemp")}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:n("notifications.amsHtHumidity")}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:n("notifications.amsHtTemp")}),t.on_bed_cooled&&a.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:n("notifications.bedCooled")}),t.on_first_layer_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-emerald-600/20 text-emerald-300 text-xs rounded",children:n("notifications.firstLayer")}),t.on_print_missing_spool_assignment&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-500/20 text-amber-300 text-xs rounded",children:n("notifications.missingSpoolAssignmentLabel")}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(aN,{className:"w-3 h-3"}),n("notifications.quiet")]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(Wr,{className:"w-3 h-3"}),n("notifications.digest",{time:t.daily_digest_time})]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Ie,{size:"sm",variant:"secondary",disabled:y.isPending,onClick:()=>{d(null),y.mutate()},className:"w-full",children:[y.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),n("notifications.sendTestNotification")]})}),c&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${c.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[c.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx($a,{className:"w-4 h-4"}),a.jsx("span",{children:c.message})]})]}),a.jsxs("button",{onClick:()=>l(!o),className:`w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors ${t.enabled?"border-t border-bambu-dark-tertiary":"mt-2 border-t border-bambu-dark-tertiary"}`,children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(Nd,{className:"w-4 h-4"}),n("notifications.eventSettings")]}),o?a.jsx(Yl,{className:"w-4 h-4"}):a.jsx(Fn,{className:"w-4 h-4"})]}),o&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.enabled")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.sendFromProvider")})]}),a.jsx(Vn,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printEvents")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStarted")}),a.jsx(Vn,{checked:t.on_print_start,onChange:b=>p.mutate({on_print_start:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.plateNotEmpty")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.plateNotEmptyDescription")})]}),a.jsx(Vn,{checked:t.on_plate_not_empty??!0,onChange:b=>p.mutate({on_plate_not_empty:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printCompleted")}),a.jsx(Vn,{checked:t.on_print_complete,onChange:b=>p.mutate({on_print_complete:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.bedCooledLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.bedCooledDescription")})]}),a.jsx(Vn,{checked:t.on_bed_cooled??!1,onChange:b=>p.mutate({on_bed_cooled:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(Vn,{checked:t.on_first_layer_complete??!1,onChange:b=>p.mutate({on_first_layer_complete:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.missingSpoolAssignmentLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.missingSpoolAssignmentDescription")})]}),a.jsx(Vn,{checked:t.on_print_missing_spool_assignment??!1,onChange:b=>p.mutate({on_print_missing_spool_assignment:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printFailed")}),a.jsx(Vn,{checked:t.on_print_failed,onChange:b=>p.mutate({on_print_failed:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printStopped")}),a.jsx(Vn,{checked:t.on_print_stopped,onChange:b=>p.mutate({on_print_stopped:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.progressMilestones")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.progressMilestonesDescription")})]}),a.jsx(Vn,{checked:t.on_print_progress,onChange:b=>p.mutate({on_print_progress:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerOffline")}),a.jsx(Vn,{checked:t.on_printer_offline,onChange:b=>p.mutate({on_printer_offline:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.printerError")}),a.jsx(Vn,{checked:t.on_printer_error,onChange:b=>p.mutate({on_printer_error:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.lowFilamentLabel")}),a.jsx(Vn,{checked:t.on_filament_low,onChange:b=>p.mutate({on_filament_low:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.maintenanceDue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.maintenanceDueDescription")})]}),a.jsx(Vn,{checked:t.on_maintenance_due??!1,onChange:b=>p.mutate({on_maintenance_due:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHumidityHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_humidity_high??!1,onChange:b=>p.mutate({on_ams_humidity_high:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsTemperatureHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_temperature_high??!1,onChange:b=>p.mutate({on_ams_temperature_high:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.amsHtAlarms")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtHumidityHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtHumidityHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>p.mutate({on_ams_ht_humidity_high:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.amsHtTemperatureHigh")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.amsHtTemperatureHighDescription")})]}),a.jsx(Vn,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>p.mutate({on_ams_ht_temperature_high:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:n("notifications.printQueue")}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAdded")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAddedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_added??!1,onChange:b=>p.mutate({on_queue_job_added:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobAssigned")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobAssignedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_assigned??!1,onChange:b=>p.mutate({on_queue_job_assigned:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobStarted")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobStartedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_started??!1,onChange:b=>p.mutate({on_queue_job_started:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobWaiting")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobWaitingDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_waiting??!0,onChange:b=>p.mutate({on_queue_job_waiting:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobSkipped")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobSkippedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_skipped??!0,onChange:b=>p.mutate({on_queue_job_skipped:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.jobFailed")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.jobFailedDescription")})]}),a.jsx(Vn,{checked:t.on_queue_job_failed??!0,onChange:b=>p.mutate({on_queue_job_failed:b})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:n("notifications.queueComplete")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.queueCompleteDescription")})]}),a.jsx(Vn,{checked:t.on_queue_completed??!1,onChange:b=>p.mutate({on_queue_completed:b})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(aN,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.quietHours")})]}),a.jsx(Vn,{checked:t.quiet_hours_enabled,onChange:b=>p.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.noNotificationsDuring")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[v(t.quiet_hours_start)||"22:00"," - ",v(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeQuietHours")})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wr,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.dailyDigest")})]}),a.jsx(Vn,{checked:t.daily_digest_enabled,onChange:b=>p.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rr,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:n("notifications.sendAt",{time:v(t.daily_digest_time)||"08:00"})})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.editProviderToChangeDigestTime")})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(bh,{className:"w-4 h-4"}),n("notifications.edit")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(un,{className:"w-4 h-4"})})]})]})]})}),i&&a.jsx(kn,{title:n("notifications.deleteProvider"),message:n("notifications.deleteConfirm",{name:t.name}),confirmText:n("notifications.delete"),variant:"danger",onConfirm:()=>{f.mutate(),s(!1)},onCancel:()=>s(!1)})]})}const htt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function ptt({provider:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.provider_type||"email"),[d,u]=w.useState(t?.printer_id||null),[m,p]=w.useState(t?.quiet_hours_enabled||!1),[f,y]=w.useState(t?.quiet_hours_start||"22:00"),[v,b]=w.useState(t?.quiet_hours_end||"07:00"),[g,_]=w.useState(t?.daily_digest_enabled||!1),[k,P]=w.useState(t?.daily_digest_time||"08:00"),[N,M]=w.useState(t?.on_print_start??!1),[T,A]=w.useState(t?.on_print_complete??!0),[C,F]=w.useState(t?.on_print_failed??!0),[$,I]=w.useState(t?.on_print_stopped??!0),[Q,L]=w.useState(t?.on_print_progress??!1),[re,ae]=w.useState(t?.on_printer_offline??!1),[ee,ue]=w.useState(t?.on_printer_error??!1),[le,de]=w.useState(t?.on_filament_low??!1),[K,te]=w.useState(t?.on_maintenance_due??!1),[se,be]=w.useState(t?.on_bed_cooled??!1),[Ne,B]=w.useState(t?.on_first_layer_complete??!1),[Y,D]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([oe,U])=>[oe,String(U)])):{}),[j,z]=w.useState(null),[W,q]=w.useState(null),{data:ce}=et({queryKey:["printers"],queryFn:he.getPrinters});w.useEffect(()=>{const oe=U=>{U.key==="Escape"&&e()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[e]);const O=lt({mutationFn:()=>he.testNotificationConfig({provider_type:l,config:Y}),onSuccess:oe=>{z(oe),q(null)},onError:oe=>{z({success:!1,message:oe.message})}}),G=lt({mutationFn:oe=>he.createNotificationProvider(oe),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:oe=>{q(oe.message)}}),X=lt({mutationFn:oe=>he.updateNotificationProvider(t.id,oe),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:oe=>{q(oe.message)}}),V=oe=>{if(oe.preventDefault(),q(null),!s.trim()){q(n("notifications.nameRequired"));return}const U=me(l);for(const ne of U)if(!Y[ne.key]?.trim()){q(n("notifications.fieldRequired",{field:ne.label}));return}const R={name:s.trim(),provider_type:l,config:Y,printer_id:d,quiet_hours_enabled:m,quiet_hours_start:m?f:null,quiet_hours_end:m?v:null,daily_digest_enabled:g,daily_digest_time:g?k:null,on_print_start:N,on_print_complete:T,on_print_failed:C,on_print_stopped:$,on_print_progress:Q,on_printer_offline:re,on_printer_error:ee,on_filament_low:le,on_maintenance_due:K,on_bed_cooled:se,on_first_layer_complete:Ne};i?X.mutate(R):G.mutate(R)},J=G.isPending||X.isPending,ie=oe=>{switch(oe){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:U=>U.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:U=>U.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},me=oe=>ie(oe).filter(U=>U.required),pe=ie(l);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:oe=>oe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n(i?"notifications.editTitle":"notifications.addTitle")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:V,className:"p-6 space-y-4",children:[W&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:W}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.nameLabel")}),a.jsx("input",{type:"text",value:s,onChange:oe=>o(oe.target.value),placeholder:n("notifications.namePlaceholder"),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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.providerTypeLabel")}),a.jsx("select",{value:l,onChange:oe=>{c(oe.target.value),D({}),z(null)},disabled:i,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 disabled:opacity-50",children:htt.map(oe=>a.jsx("option",{value:oe,children:n(`notifications.providerTypes.${oe}`,oe)},oe))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n(`notifications.providerDescriptions.${l}`,"")})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.configuration")}),pe.filter(oe=>!("showIf"in oe)||oe.showIf?.(Y)!==!1).map(oe=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[oe.label," ",oe.required&&"*"]}),oe.type==="select"&&"options"in oe&&oe.options?a.jsx("select",{value:Y[oe.key]||oe.options[0]?.value||"",onChange:U=>{D({...Y,[oe.key]:U.target.value}),z(null)},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:oe.options.map(U=>a.jsx("option",{value:U.value,children:U.label},U.value))}):a.jsx("input",{type:oe.type,value:Y[oe.key]||"",onChange:U=>{D({...Y,[oe.key]:U.target.value}),z(null)},placeholder:oe.placeholder,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"})]},oe.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Ie,{type:"button",variant:"secondary",onClick:()=>{z(null),O.mutate()},disabled:O.isPending||me(l).length>0&&!Y[me(l)[0]?.key],className:"flex-1",children:[O.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Lw,{className:"w-4 h-4"}),n("notifications.testConfiguration")]})}),j&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${j.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:j.success?a.jsxs(a.Fragment,{children:[a.jsx(fr,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]}):a.jsxs(a.Fragment,{children:[a.jsx($a,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("notifications.printerFilter")}),a.jsxs("select",{value:d??"",onChange:oe=>u(oe.target.value?Number(oe.target.value):null),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:[a.jsx("option",{value:"",children:n("notifications.allPrinters")}),ce?.map(oe=>a.jsx("option",{value:oe.id,children:oe.name},oe.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.onlyFromPrinter")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.quietHoursDnd")}),a.jsx(Vn,{checked:m,onChange:p})]}),m&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietStart")}),a.jsx("input",{type:"time",value:f,onChange:oe=>y(oe.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.quietEnd")}),a.jsx("input",{type:"time",value:v,onChange:oe=>b(oe.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"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:n("notifications.dailyDigestLabel")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("notifications.batchNotifications")})]}),a.jsx(Vn,{checked:g,onChange:_})]}),g&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:n("notifications.sendDigestAt")}),a.jsx("input",{type:"time",value:k,onChange:oe=>P(oe.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("notifications.digestCollected")})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("notifications.notificationEvents")}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printEvents")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.start")}),a.jsx(Vn,{checked:N,onChange:M})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.complete")}),a.jsx(Vn,{checked:T,onChange:A})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.failed")}),a.jsx(Vn,{checked:C,onChange:F})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.stopped")}),a.jsx(Vn,{checked:$,onChange:I})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.progress")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.progressPercent")})]}),a.jsx(Vn,{checked:Q,onChange:L})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.bedCooled")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.bedCooledAfterPrint")})]}),a.jsx(Vn,{checked:se,onChange:be})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.firstLayerCompleteLabel")}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:n("notifications.firstLayerCompleteDescription")})]}),a.jsx(Vn,{checked:Ne,onChange:B})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:n("notifications.printerStatus")}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.offline")}),a.jsx(Vn,{checked:re,onChange:ae})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.error")}),a.jsx(Vn,{checked:ee,onChange:ue})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.lowFilament")}),a.jsx(Vn,{checked:le,onChange:de})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.maintenance")}),a.jsx(Vn,{checked:K,onChange:te})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("notifications.cancel")}),a.jsxs(Ie,{type:"submit",disabled:J,className:"flex-1",children:[J?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),n(i?"notifications.save":"notifications.add")]})]})]})]})})}function ftt({template:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=w.useRef(null),[s,o]=w.useState(t.title_template),[l,c]=w.useState(t.body_template),[d,u]=w.useState(null),[m,p]=w.useState(!0),{data:f}=et({queryKey:["template-variables"],queryFn:he.getTemplateVariables}),y=f?.find(M=>M.event_type===t.event_type),{data:v,isLoading:b}=et({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>he.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});w.useEffect(()=>{const M=T=>{T.key==="Escape"&&e()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[e]);const g=lt({mutationFn:M=>he.updateNotificationTemplate(t.id,M),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:M=>{u(M.message)}}),_=lt({mutationFn:()=>he.resetNotificationTemplate(t.id),onSuccess:M=>{o(M.title_template),c(M.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:M=>{u(M.message)}}),k=M=>{if(M.preventDefault(),u(null),!s.trim()){u(n("notifications.titleRequired"));return}if(!l.trim()){u(n("notifications.bodyRequired"));return}g.mutate({title_template:s,body_template:l})},P=M=>{const T=i.current;if(!T)return;const A=T.selectionStart,C=T.selectionEnd,F=l,$=F.substring(0,A),I=F.substring(C),Q=$+`{${M}}`+I;c(Q),setTimeout(()=>{T.focus();const L=A+M.length+2;T.setSelectionRange(L,L)},0)},N=s!==t.title_template||l!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("notifications.editTemplate",{name:t.name})}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:k,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[d&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:d}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.titleLabel")}),a.jsx("input",{type:"text",value:s,onChange:M=>o(M.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:n("notifications.titlePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:n("notifications.bodyLabel")}),a.jsx("textarea",{ref:i,value:l,onChange:M=>c(M.target.value),rows:4,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none",placeholder:n("notifications.bodyPlaceholder")})]}),y&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:n("notifications.availableVariables")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:y.variables.map(M=>a.jsxs("button",{type:"button",onClick:()=>P(M),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(ur,{className:"w-3 h-3"}),M]},M))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:n("notifications.clickToInsert")})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(Dc,{className:"w-4 h-4"}),n("notifications.livePreview")]}),a.jsx("button",{type:"button",onClick:()=>p(!m),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:n(m?"notifications.hide":"notifications.show")})]}),m&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),n("notifications.loadingPreview")]}):v?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.titlePreview")}),a.jsx("div",{className:"text-white font-medium",children:v.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:n("notifications.bodyPreview")}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:v.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:n("notifications.enterTemplateContent")})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Ie,{type:"button",variant:"ghost",onClick:()=>_.mutate(),disabled:_.isPending,className:"text-orange-400 hover:text-orange-300",children:[_.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(jo,{className:"w-4 h-4 mr-2"}),n("notifications.resetToDefault")]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:n("notifications.cancel")}),a.jsxs(Ie,{onClick:k,disabled:g.isPending||!N,children:[g.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(cs,{className:"w-4 h-4 mr-2"}),n("notifications.save")]})]})]})]})})}const gtt={print_start:"text-blue-400",print_complete:"text-bambu-green",print_failed:"text-red-400",print_stopped:"text-orange-400",print_progress:"text-yellow-400",printer_offline:"text-gray-400",printer_error:"text-rose-400",filament_low:"text-cyan-400",maintenance_due:"text-purple-400",test:"text-bambu-gray"};function btt({onClose:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),[i,s]=w.useState(7),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=et({queryKey:["settings"],queryFn:he.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:y,isRefetching:v}=et({queryKey:["notification-logs",i,c],queryFn:()=>he.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=et({queryKey:["notification-log-stats",i],queryFn:()=>he.getNotificationLogStats(i)}),g=lt({mutationFn:()=>he.clearNotificationLogs(30),onSuccess:k=>{r(k.message,"success"),n.invalidateQueries({queryKey:["notification-logs"]}),n.invalidateQueries({queryKey:["notification-log-stats"]})},onError:k=>{r(`Failed to clear logs: ${k.message}`,"error")}}),_=k=>{const P=Qn(k);if(!P)return"";const M=new Date().getTime()-P.getTime();return M<6e4?e("notifications.justNow"):M<36e5?`${Math.floor(M/6e4)}m ago`:M<864e5?`${Math.floor(M/36e5)}h ago`:P.toLocaleDateString()+" "+DQ(P,m)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(L0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:e("notifications.notificationLog")})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:[e("notifications.statsSummary",{days:i})," ",a.jsx("span",{className:"text-white font-medium",children:b.total})," ",e("notifications.statsNotifications")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(fr,{className:"w-4 h-4"}),e("notifications.statsSent",{count:b.success_count})]}),b.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx($a,{className:"w-4 h-4"}),e("notifications.statsFailed",{count:b.failure_count})]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:i,onChange:k=>s(Number(k.target.value)),className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:[a.jsx("option",{value:1,children:e("notifications.last24Hours")}),a.jsx("option",{value:7,children:e("notifications.last7Days")}),a.jsx("option",{value:30,children:e("notifications.last30Days")}),a.jsx("option",{value:90,children:e("notifications.last90Days")})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:c,onChange:k=>d(k.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),e("notifications.showFailedOnly")]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>y(),disabled:v,children:[v?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),e("notifications.refresh")]}),a.jsxs(Ie,{size:"sm",variant:"secondary",onClick:()=>g.mutate(),disabled:g.isPending,className:"text-red-400 hover:text-red-300",children:[g.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),e("notifications.clearOld")]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?a.jsx("div",{className:"space-y-2",children:p.map(k=>a.jsx(xtt,{log:k,isExpanded:o===k.id,onToggle:()=>l(o===k.id?null:k.id),formatDate:_,formatFullDate:P=>Bf(P,m)},k.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(L0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:e(c?"notifications.noFailedNotifications":"notifications.noNotificationsLogged")})]})})]})})}function xtt({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){const{t:s}=Lt();return a.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[a.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?a.jsx(fr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx($a,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${gtt[t.event_type]||"text-bambu-gray"}`,children:s(`notifications.eventTypes.${t.event_type}`,t.event_type)}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||s("notifications.unknownProvider")}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(Yl,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logTitle")}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logMessage")}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:s("notifications.logError")}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsx("span",{children:s("notifications.logProvider",{type:t.provider_type})}),a.jsx("span",{children:s("notifications.logTime",{time:i(t.created_at)})})]})]})]})}function ytt({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Lt();w.useEffect(()=>{const d=u=>{u.key==="Escape"&&r()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const c=d=>{e({...t,group_ids:t.group_ids.includes(d)?t.group_ids.filter(u=>u!==d):[...t.group_ids,d]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(Dt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(_u,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Ie,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(Rt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:d=>e({...t,username:d.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:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:d=>e({...t,email:d.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:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(d=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(d.id),onChange:()=>c(d.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:d.name}),d.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},d.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Ie,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Ie,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(ur,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function vtt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[d,u]=w.useState(!1),[m,p]=w.useState(!0),[f,y]=w.useState("all"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,P]=w.useState(!1),{data:N,isLoading:M}=et({queryKey:["spoolman-settings"],queryFn:he.getSpoolmanSettings}),{data:T,isLoading:A,refetch:C}=et({queryKey:["spoolman-status"],queryFn:he.getSpoolmanStatus,refetchInterval:3e4}),{data:F}=et({queryKey:["printers"],queryFn:he.getPrinters});w.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),u(N.spoolman_disable_weight_sync==="true"),p(N.spoolman_report_partial_usage!=="false"),b(!0))},[N]),w.useEffect(()=>{if(!v||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==d||N.spoolman_report_partial_usage!=="false"!==m){const te=setTimeout(()=>{$.mutate()},500);return()=>clearTimeout(te)}},[r,s,l,d,m,v]);const $=lt({mutationFn:()=>he.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:d?"true":"false",spoolman_report_partial_usage:m?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),e.invalidateQueries({queryKey:["settings"]}),n(t("settings.toast.settingsSaved"))}}),I=lt({mutationFn:he.connectSpoolman,onSuccess:()=>{C()}}),Q=lt({mutationFn:he.disconnectSpoolman,onSuccess:()=>{C()}}),L=lt({mutationFn:he.syncAllPrintersAms,onSuccess:K=>{K.success}}),re=lt({mutationFn:K=>he.syncPrinterAms(K),onSuccess:K=>{K.success}}),ae=()=>{f==="all"?L.mutate():re.mutate(f)},ee=lt({mutationFn:he.syncWeightsFromAms,onSuccess:K=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:K.synced,skipped:K.skipped}),"success"),P(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),P(!1)}}),ue=L.isPending||re.isPending,le=f==="all"?L.data:re.data,de=f==="all"?L.isSuccess:re.isSuccess;return M?a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),$.isPending&&a.jsx(ct,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(Na,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),a.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(sa,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[a.jsx("li",{children:t("settings.builtInFeatureRfid")}),a.jsx("li",{children:t("settings.builtInFeatureUsage")}),a.jsx("li",{children:t("settings.builtInFeatureCatalog")}),a.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>P(!0),disabled:ee.isPending,children:[ee.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(vr,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:t("settings.syncInfoRfidOnly")}),a.jsx("li",{children:t("settings.syncInfoAutoCreate")}),a.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),a.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:K=>o(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),a.jsxs("select",{value:l,onChange:K=>c(K.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",children:[a.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),a.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:d,onChange:K=>u(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),d&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:m,onChange:K=>p(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),A?a.jsx(ct,{className:"w-4 h-4 text-bambu-gray animate-spin"}):T?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx(Kr,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Bt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),a.jsx("div",{className:"flex gap-2",children:T?.connected?a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Q.mutate(),disabled:Q.isPending,children:[Q.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Sge,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(Ie,{size:"sm",onClick:()=>I.mutate(),disabled:I.isPending||!s,children:[I.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Ru,{className:"w-4 h-4"}),t("settings.connect")]})})]}),I.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:I.error.message}),T?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:f,onChange:K=>y(K.target.value==="all"?"all":Number(K.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"all",children:t("settings.allPrinters")}),F?.map(K=>a.jsx("option",{value:K.id,children:K.name},K.id))]}),a.jsx(Fn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ae,disabled:ue,children:[ue?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),de&&le&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${le.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:le.success?`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} successfully`:`Synced ${le.synced_count} spool${le.synced_count!==1?"s":""} with ${le.errors.length} error${le.errors.length!==1?"s":""}`}),le.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[le.skipped_count," spool",le.skipped_count!==1?"s":""," skipped"]})]}),le.skipped_count>5&&a.jsx("button",{onClick:()=>_(!g),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:g?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(g?le.skipped:le.skipped.slice(0,5)).map((K,te)=>a.jsxs("li",{className:"flex items-center gap-2",children:[K.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${K.color}`}}),a.jsx("span",{children:K.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",K.reason]})]},te)),!g&&le.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",le.skipped_count-5," more"]})]})]}),le.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:le.errors.map((K,te)=>a.jsx("li",{children:K},te))})]})]})]})]})]}),k&&a.jsx(kn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:ee.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>ee.mutate(),onCancel:()=>P(!1)})]})}function wtt(){const{t}=Lt(),{showToast:e}=xn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[d,u]=w.useState(!1),[m,p]=w.useState(null),[f,y]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(!1),[k,P]=w.useState(new Set),[N,M]=w.useState(!1),[T,A]=w.useState(null),[C,F]=w.useState(!1),$=w.useCallback(async()=>{try{const be=await he.getSpoolCatalog();r(be)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{$()},[$]);const I=n.filter(be=>be.name.toLowerCase().includes(o.toLowerCase())),Q=async()=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const be=await he.addCatalogEntry({name:f.trim(),weight:parseInt(v)});r(Ne=>[...Ne,be].sort((B,Y)=>B.name.localeCompare(Y.name))),u(!1),y(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},L=be=>{p(be.id),y(be.name),b(be.weight.toString())},re=()=>{p(null),y(""),b("")},ae=async be=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const Ne=await he.updateCatalogEntry(be,{name:f.trim(),weight:parseInt(v)});r(B=>B.map(Y=>Y.id===be?Ne:Y).sort((Y,D)=>Y.name.localeCompare(D.name))),p(null),y(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},ee=async()=>{if(T)try{await he.deleteCatalogEntry(T.id),r(be=>be.filter(Ne=>Ne.id!==T.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{A(null)}},ue=async()=>{F(!1),s(!0);try{await he.resetSpoolCatalog(),await $(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},le=be=>{P(Ne=>{const B=new Set(Ne);return B.has(be)?B.delete(be):B.add(be),B})},de=()=>{k.size===I.length?P(new Set):P(new Set(I.map(be=>be.id)))},K=async()=>{if(M(!1),k.size!==0)try{const be=await he.bulkDeleteCatalogEntries([...k]);r(Ne=>Ne.filter(B=>!k.has(B.id))),P(new Set),e(t("settings.catalog.bulkDeleted",{count:be.deleted}),"success")}catch{e(t("settings.catalog.bulkDeleteFailed"),"error")}},te=()=>{const be=n.map(({name:D,weight:j})=>({name:D,weight:j})),Ne=new Blob([JSON.stringify(be,null,2)],{type:"application/json"}),B=URL.createObjectURL(Ne),Y=document.createElement("a");Y.href=B,Y.download="spool-catalog.json",document.body.appendChild(Y),Y.click(),document.body.removeChild(Y),URL.revokeObjectURL(B),e(t("settings.catalog.exported",{count:n.length}),"success")},se=async be=>{const Ne=be.target.files?.[0];if(Ne){try{const B=await Ne.text(),Y=JSON.parse(B);if(!Array.isArray(Y))throw new Error("Invalid format");let D=0,j=0;for(const z of Y){if(!z.name||typeof z.weight!="number"){j++;continue}if(n.some(q=>q.name.toLowerCase()===z.name.toLowerCase())){j++;continue}try{const q=await he.addCatalogEntry({name:z.name,weight:z.weight});r(ce=>[...ce,q].sort((O,G)=>O.name.localeCompare(G.name))),D++}catch{j++}}e(t("settings.catalog.imported",{added:D,skipped:j}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(Dt,{children:[a.jsxs(Dn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Ul,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:te,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[a.jsx(va,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[a.jsx(Ca,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:se}),a.jsxs("button",{onClick:()=>F(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[a.jsx(jo,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>u(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(ur,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),k.size>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[a.jsx("span",{className:"text-sm text-red-400",children:t("settings.catalog.selectedCount",{count:k.size})}),a.jsxs("button",{onClick:()=>M(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[a.jsx(un,{className:"w-4 h-4"}),t("settings.catalog.deleteSelected")]}),a.jsx("button",{onClick:()=>P(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:be=>l(be.target.value)})]}),d&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:f,onChange:be=>y(be.target.value)})}),a.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:v,onChange:be=>b(be.target.value)}),a.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),a.jsxs("button",{onClick:Q,disabled:g,className:"px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center gap-1 shrink-0",children:[g?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{u(!1),y(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-2 py-2 w-10",children:a.jsx("input",{type:"checkbox",checked:I.length>0&&k.size===I.length,onChange:de,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),a.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),a.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),a.jsx("th",{className:"px-4 py-2 w-24"})]})}),a.jsx("tbody",{children:I.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:5,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):I.map(be=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${k.has(be.id)?"bg-bambu-dark":""}`,children:m===be.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(be.id),onChange:()=>le(be.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:f,onChange:Ne=>y(Ne.target.value)})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:v,onChange:Ne=>b(Ne.target.value)})}),a.jsx("td",{className:"px-4 py-2 text-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>ae(be.id),disabled:g,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:g?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:re,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Bt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:k.has(be.id),onChange:()=>le(be.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-4 py-2 text-white",children:be.name}),a.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[be.weight,"g"]}),a.jsx("td",{className:"px-4 py-2 text-center",children:be.is_default?a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>L(be),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>A(be),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(un,{className:"w-4 h-4"})})]})})]})},be.id))})]})})]}),T&&a.jsx(kn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:T.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:ee,onCancel:()=>A(null)}),N&&a.jsx(kn,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:k.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:K,onCancel:()=>M(!1)}),C&&a.jsx(kn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:ue,onCancel:()=>F(!1)})]})}function Stt(){const{t}=Lt(),{showToast:e}=xn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),[c,d]=w.useState("Bambu Lab"),u=w.useRef(null),[m,p]=w.useState(!1),[f,y]=w.useState(null),[v,b]=w.useState(""),[g,_]=w.useState(""),[k,P]=w.useState("#FFFFFF"),[N,M]=w.useState(""),[T,A]=w.useState(!1),[C,F]=w.useState(new Set),[$,I]=w.useState(!1),[Q,L]=w.useState(!1),[re,ae]=w.useState(null),[ee,ue]=w.useState(null),[le,de]=w.useState(!1),K=w.useCallback(async()=>{try{const V=await he.getColorCatalog();r(V)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{K()},[K]);const te=[...new Set(n.map(V=>V.manufacturer))].sort(),se=n.filter(V=>{const J=o===""||V.manufacturer.toLowerCase().includes(o.toLowerCase())||V.color_name.toLowerCase().includes(o.toLowerCase())||(V.material?.toLowerCase().includes(o.toLowerCase())??!1),ie=c===""||V.manufacturer===c;return J&&ie}),be=()=>{b(""),_(""),P("#FFFFFF"),M("")},Ne=async()=>{if(!v.trim()||!g.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}A(!0);try{const V=await he.addColorEntry({manufacturer:v.trim(),color_name:g.trim(),hex_color:k,material:N.trim()||null});r(J=>[...J,V].sort((ie,me)=>ie.manufacturer.localeCompare(me.manufacturer)||(ie.material||"").localeCompare(me.material||"")||ie.color_name.localeCompare(me.color_name))),p(!1),be(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{A(!1)}},B=V=>{y(V.id),b(V.manufacturer),_(V.color_name),P(V.hex_color),M(V.material||"")},Y=()=>{y(null),be()},D=async V=>{if(!v.trim()||!g.trim()||!k){e(t("settings.colorCatalog.fieldsRequired"),"error");return}A(!0);try{const J=await he.updateColorEntry(V,{manufacturer:v.trim(),color_name:g.trim(),hex_color:k,material:N.trim()||null});r(ie=>ie.map(me=>me.id===V?J:me).sort((me,pe)=>me.manufacturer.localeCompare(pe.manufacturer)||(me.material||"").localeCompare(pe.material||"")||me.color_name.localeCompare(pe.color_name))),y(null),be(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{A(!1)}},j=async()=>{if(ee)try{await he.deleteColorEntry(ee.id),r(V=>V.filter(J=>J.id!==ee.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{ue(null)}},z=async()=>{de(!1),s(!0);try{await he.resetColorCatalog(),await K(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},W=async()=>{L(!0),ae(null);try{const V={},J=Ku();J&&(V.Authorization=`Bearer ${J}`);const ie=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:V});if(!ie.ok)throw new Error("Failed to start sync");const me=ie.body?.getReader();if(!me)throw new Error("No response body");const pe=new TextDecoder;let oe="";for(;;){const{done:U,value:R}=await me.read();if(U)break;oe+=pe.decode(R,{stream:!0});const ne=oe.split(`
`);oe=ne.pop()||"";for(const xe of ne)if(xe.startsWith("data: "))try{const Se=JSON.parse(xe.slice(6));Se.type==="progress"?ae({fetched:Se.total_fetched,total:Se.total_available}):Se.type==="complete"?Se.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:Se.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:Se.added,skipped:Se.skipped}),"success"):Se.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${Se.error}`,"error")}catch{}}await K()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{L(!1),ae(null)}},q=V=>{F(J=>{const ie=new Set(J);return ie.has(V)?ie.delete(V):ie.add(V),ie})},ce=()=>{C.size===se.length?F(new Set):F(new Set(se.map(V=>V.id)))},O=async()=>{if(I(!1),C.size!==0)try{const V=await he.bulkDeleteColorEntries([...C]);r(J=>J.filter(ie=>!C.has(ie.id))),F(new Set),e(t("settings.colorCatalog.bulkDeleted",{count:V.deleted}),"success")}catch{e(t("settings.colorCatalog.bulkDeleteFailed"),"error")}},G=()=>{const V=n.map(({manufacturer:pe,color_name:oe,hex_color:U,material:R})=>({manufacturer:pe,color_name:oe,hex_color:U,material:R})),J=new Blob([JSON.stringify(V,null,2)],{type:"application/json"}),ie=URL.createObjectURL(J),me=document.createElement("a");me.href=ie,me.download="color-catalog.json",document.body.appendChild(me),me.click(),document.body.removeChild(me),URL.revokeObjectURL(ie),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},X=async V=>{const J=V.target.files?.[0];if(J){try{const ie=await J.text(),me=JSON.parse(ie);if(!Array.isArray(me))throw new Error("Invalid format");let pe=0,oe=0;for(const U of me){if(!U.manufacturer||!U.color_name||!U.hex_color){oe++;continue}if(n.some(ne=>ne.manufacturer.toLowerCase()===U.manufacturer.toLowerCase()&&ne.color_name.toLowerCase()===U.color_name.toLowerCase()&&(ne.material||"").toLowerCase()===(U.material||"").toLowerCase())){oe++;continue}try{const ne=await he.addColorEntry({manufacturer:U.manufacturer,color_name:U.color_name,hex_color:U.hex_color,material:U.material||null});r(xe=>[...xe,ne].sort((Se,ye)=>Se.manufacturer.localeCompare(ye.manufacturer)||(Se.material||"").localeCompare(ye.material||"")||Se.color_name.localeCompare(ye.color_name))),pe++}catch{oe++}}e(t("settings.colorCatalog.imported",{added:pe,skipped:oe}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}u.current&&(u.current.value="")}};return a.jsxs(Dt,{children:[a.jsxs(Dn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Dw,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:G,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(va,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>u.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(Ca,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:u,type:"file",accept:".json",className:"hidden",onChange:X}),a.jsxs("button",{onClick:W,disabled:Q,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.colorCatalog.syncTooltip"),children:[Q?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Jx,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:Q?re?`${Math.min(re.fetched,re.total)} / ${re.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),a.jsxs("button",{onClick:()=>de(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(jo,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>p(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(ur,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),C.size>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[a.jsx("span",{className:"text-sm text-red-400",children:t("settings.colorCatalog.selectedCount",{count:C.size})}),a.jsxs("button",{onClick:()=>I(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[a.jsx(un,{className:"w-4 h-4"}),t("settings.colorCatalog.deleteSelected")]}),a.jsx("button",{onClick:()=>F(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),a.jsxs("div",{className:"flex gap-2 flex-wrap",children:[a.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.searchColors"),value:o,onChange:V=>l(V.target.value)})]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:V=>d(V.target.value),children:[a.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),te.map(V=>a.jsx("option",{value:V,children:V},V))]})]}),m&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[a.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.manufacturer"),value:v,onChange:V=>b(V.target.value)}),a.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.colorName"),value:g,onChange:V=>_(V.target.value)}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:k,onChange:V=>P(V.target.value)}),a.jsx("input",{type:"text",className:"w-32 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:"#FFFFFF",value:k,onChange:V=>P(V.target.value)})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("input",{type:"text",className:"flex-1 max-w-lg min-w-[200px] px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.materialOptional"),value:N,onChange:V=>M(V.target.value)}),a.jsxs("button",{onClick:Ne,disabled:T,className:"w-24 px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center justify-center gap-3",children:[T?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{p(!1),be()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Bt,{className:"w-4 h-4"})})]})]})]}),(o||c)&&a.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:se.length,total:n.length})}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(ct,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-2 py-2 w-10",children:a.jsx("input",{type:"checkbox",checked:se.length>0&&C.size===se.length,onChange:ce,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),a.jsx("th",{className:"px-3 py-2 w-16"})]})}),a.jsx("tbody",{children:se.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:7,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):se.map(V=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${C.has(V.id)?"bg-bambu-dark":""}`,children:f===V.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:C.has(V.id),onChange:()=>q(V.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:k,onChange:J=>P(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:v,onChange:J=>b(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:N,onChange:J=>M(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:g,onChange:J=>_(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:k,onChange:J=>P(J.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>D(V.id),disabled:T,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:T?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(Kr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:Y,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Bt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-2 py-2",children:a.jsx("input",{type:"checkbox",checked:C.has(V.id),onChange:()=>q(V.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("div",{className:"w-8 h-8 rounded border border-bambu-dark-tertiary",style:{backgroundColor:V.hex_color},title:V.hex_color})}),a.jsx("td",{className:"px-3 py-2 text-white",children:V.manufacturer}),a.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:V.material||"-"}),a.jsx("td",{className:"px-3 py-2 text-white",children:V.color_name}),a.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:V.hex_color}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>B(V),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>ue(V),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(un,{className:"w-4 h-4"})})]})})]})},V.id))})]})})]}),ee&&a.jsx(kn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${ee.manufacturer} - ${ee.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:j,onCancel:()=>ue(null)}),$&&a.jsx(kn,{title:t("settings.colorCatalog.deleteSelected"),message:t("settings.colorCatalog.bulkDeleteConfirm",{count:C.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:O,onCancel:()=>I(!1)}),le&&a.jsx(kn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:z,onCancel:()=>de(!1)})]})}function _tt({link:t,onClose:e}){const{t:n}=Lt(),r=mn(),i=!!t,s=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.url||""),[u,m]=w.useState(t?.icon||"link"),[p,f]=w.useState(t?.open_in_new_tab||!1),[y,v]=w.useState(!!t?.custom_icon),[b,g]=w.useState(t?.custom_icon?he.getExternalLinkIconUrl(t.id):null),[_,k]=w.useState(null),[P,N]=w.useState(null);w.useEffect(()=>{const Q=L=>{L.key==="Escape"&&e()};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[e]);const M=lt({mutationFn:async Q=>{const L=await he.createExternalLink(Q);return _?await he.uploadExternalLinkIcon(L.id,_):L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:Q=>{N(Q.message)}}),T=lt({mutationFn:async Q=>{let L=await he.updateExternalLink(t.id,Q);return _?L=await he.uploadExternalLinkIcon(t.id,_):!y&&t?.custom_icon&&(L=await he.deleteExternalLinkIcon(t.id)),L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:Q=>{N(Q.message)}}),A=Q=>{const L=Q.target.files?.[0];if(L){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(L.type)){N("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(L.size>1024*1024){N("Image file must be less than 1MB");return}k(L),v(!0);const ae=new FileReader;ae.onload=ee=>{g(ee.target?.result)},ae.readAsDataURL(L)}},C=()=>{k(null),g(null),v(!1),s.current&&(s.current.value="")},F=Q=>{if(Q.preventDefault(),N(null),!o.trim()){N("Name is required");return}if(!c.trim()){N("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){N("URL must start with http:// or https://");return}const L={name:o.trim(),url:c.trim(),icon:u,open_in_new_tab:p};i?T.mutate(L):M.mutate(L)},$=M.isPending||T.isPending,I=TP(u);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:Q=>Q.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:y&&b?a.jsx("img",{src:b,alt:"",className:"w-5 h-5 rounded"}):a.jsx(I,{className:"w-5 h-5"})}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:F,className:"p-6 space-y-4",children:[P&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:P}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:o,onChange:Q=>l(Q.target.value),placeholder:"My Link",maxLength:50,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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),a.jsx("input",{type:"text",value:c,onChange:Q=>d(Q.target.value),placeholder:"https://example.com",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"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),a.jsx("button",{type:"button",onClick:()=>f(!p),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${p?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),a.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),a.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:A}),y&&b?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:b,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:C,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:a.jsx(un,{className:"w-4 h-4"})})]}):a.jsxs(Ie,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[a.jsx(Ca,{className:"w-4 h-4"}),"Upload"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!y&&a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),a.jsx(Oxe,{value:u,onChange:m})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Ie,{type:"submit",disabled:$,className:"flex-1",children:[$?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(cs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function ktt(){const{t}=Lt(),e=mn(),[n,r]=w.useState(!1),[i,s]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),{data:u,isLoading:m}=et({queryKey:["external-links"],queryFn:he.getExternalLinks}),p=lt({mutationFn:k=>he.deleteExternalLink(k),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),f=lt({mutationFn:k=>he.reorderExternalLinks(k),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),y=(k,P)=>{d(P),k.dataTransfer.effectAllowed="move"},v=k=>{k.preventDefault(),k.dataTransfer.dropEffect="move"},b=(k,P)=>{if(k.preventDefault(),c===null||c===P||!u)return;const N=u.map(C=>C.id),M=N.indexOf(c),T=N.indexOf(P);if(M===-1||T===-1)return;const A=[...N];A.splice(M,1),A.splice(T,0,c),f.mutate(A),d(null)},g=k=>{l(k)},_=()=>{o&&(p.mutate(o.id),l(null))};return a.jsxs(a.Fragment,{children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ru,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),a.jsxs(Ie,{size:"sm",onClick:()=>r(!0),children:[a.jsx(ur,{className:"w-4 h-4"}),"Add Link"]})]})}),a.jsxs(Rt,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),m?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?a.jsx("div",{className:"space-y-2",children:u.map(k=>{const P=TP(k.icon);return a.jsxs("div",{draggable:!0,onDragStart:N=>y(N,k.id),onDragOver:v,onDrop:N=>b(N,k.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===k.id?"opacity-50":""}`,children:[a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(P,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-white font-medium truncate",children:k.name}),a.jsx(sa,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),a.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:k.url})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{onClick:()=>s(k),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>g(k),disabled:p.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:t("externalLinks.deleteLink"),children:a.jsx(un,{className:"w-4 h-4"})})]})]},k.id)})}):a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Ru,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:t("externalLinks.noLinksConfigured")}),a.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||i)&&a.jsx(_tt,{link:i,onClose:()=>{r(!1),s(null)}}),o&&a.jsx(kn,{title:"Delete Link",message:`Are you sure you want to delete "${o.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:_,onCancel:()=>l(null)})]})}const s3={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function Ntt({printer:t,models:e}){const{t:n}=Lt(),r=mn(),{showToast:i}=xn(),[s,o]=w.useState(!0),[l,c]=w.useState(t.enabled),[d,u]=w.useState(t.name),[m,p]=w.useState(""),[f,y]=w.useState(t.mode==="queue"?"review":t.mode),[v,b]=w.useState(t.target_printer_id),[g,_]=w.useState(t.bind_ip||""),[k,P]=w.useState(t.remote_interface_ip||""),[N,M]=w.useState(t.model||""),[T,A]=w.useState(t.auto_dispatch??!0),[C,F]=w.useState(!1),[$,I]=w.useState(null),[Q,L]=w.useState(!1);w.useEffect(()=>{$||(c(t.enabled),y(t.mode==="queue"?"review":t.mode),u(t.name),b(t.target_printer_id),_(t.bind_ip||""),P(t.remote_interface_ip||""),M(t.model||""),A(t.auto_dispatch??!0))},[t,$]);const{data:re}=et({queryKey:["printers"],queryFn:he.getPrinters}),{data:ae}=et({queryKey:["network-interfaces"],queryFn:()=>he.getNetworkInterfaces().then(j=>j.interfaces)}),ee=lt({mutationFn:j=>oN.update(t.id,j),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.updated")),I(null)},onError:j=>{i(j.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),y(t.mode==="queue"?"review":t.mode),b(t.target_printer_id),_(t.bind_ip||""),I(null)}}),ue=lt({mutationFn:()=>oN.remove(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.deleted")),L(!1)},onError:j=>{i(j.message||n("virtualPrinter.toast.failedToDelete"),"error"),L(!1)}}),le=j=>{j.stopPropagation();const z=!l;if(z){if(!g){i(n("virtualPrinter.toast.bindIpRequired"),"error");return}if(f==="proxy"){if(!v){i(n("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!m&&!t.access_code_set){i(n("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(z),I("toggle"),ee.mutate({enabled:z})},de=()=>{d.trim()&&(I("name"),ee.mutate({name:d.trim()}))},K=()=>{if(!m){i(n("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(m.length!==8){i(n("virtualPrinter.toast.accessCodeLength"),"error");return}I("accessCode"),ee.mutate({access_code:m}),p("")},te=j=>{y(j),I("mode"),ee.mutate({mode:j})},se=j=>{M(j),I("model"),ee.mutate({model:j})},be=j=>{b(j),I("targetPrinter"),ee.mutate({target_printer_id:j})},Ne=j=>{P(j),I("remoteInterface"),ee.mutate({remote_interface_ip:j})},B=t.status?.running||!1,Y=n(`virtualPrinter.mode.${s3[f]||"archive"}`),D=re?.find(j=>j.id===v)?.name;return a.jsxs(a.Fragment,{children:[a.jsxs(Dt,{children:[a.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[a.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?a.jsx(Fn,{className:"w-4 h-4"}):a.jsx(Va,{className:"w-4 h-4"})}),a.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${B?"bg-green-400 animate-pulse":"bg-gray-500"}`}),a.jsx("span",{className:"text-white font-medium truncate",children:t.name}),a.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:Y}),t.model_name&&a.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),D&&a.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[f==="proxy"&&a.jsx(L3,{className:"w-3 h-3 inline mr-1"}),D]}),g&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:g}),k&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:k}),a.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:j=>j.stopPropagation(),children:a.jsx("button",{onClick:le,disabled:$==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${$==="toggle"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${l?"translate-x-5":""}`})})})]}),s&&a.jsxs(Rt,{className:"pt-0 space-y-4",children:[a.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"text",value:d,onChange:j=>u(j.target.value),onBlur:de,onKeyDown:j=>j.key==="Enter"&&de(),className:"flex-1 text-sm text-white bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-xs text-bambu-gray font-mono",children:t.serial}),a.jsx("button",{onClick:()=>L(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors",title:n("common.delete"),children:a.jsx(un,{className:"w-4 h-4"})})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.mode.title")}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(j=>a.jsxs("button",{onClick:()=>te(j),disabled:$==="mode",className:`p-2 rounded-lg border text-left transition-colors ${f===j?j==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[j==="proxy"&&a.jsx(L3,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${s3[j]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${s3[j]}Desc`)})]},j))})]}),f==="print_queue"&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.autoDispatch.title")}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:n("virtualPrinter.autoDispatch.description")})]}),a.jsx("button",{onClick:()=>{const j=!T;A(j),I("autoDispatch"),ee.mutate({auto_dispatch:j})},disabled:$==="autoDispatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${T?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${$==="autoDispatch"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${T?"translate-x-5":""}`})})]})}),f!=="proxy"&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.model.title")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("virtualPrinter.model.description")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:N,onChange:j=>se(j.target.value),disabled:$==="model",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:Object.entries(e).map(([j,z])=>a.jsxs("option",{value:j,children:[z," (",j,")"]},j))}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),f==="proxy"&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[a.jsx(Ks,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("virtualPrinter.proxy.accessCodeHint")})]})}),f!=="proxy"&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.accessCode.title")}),t.access_code_set?a.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[a.jsx(Kr,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.isSet")]}):a.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.notSet")]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:C?"text":"password",value:m,onChange:j=>p(j.target.value),placeholder:t.access_code_set?n("virtualPrinter.accessCode.placeholderChange"):n("virtualPrinter.accessCode.placeholder"),maxLength:8,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm placeholder-bambu-gray pr-10 font-mono"}),a.jsx("button",{onClick:()=>F(!C),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:C?a.jsx(Tw,{className:"w-4 h-4"}):a.jsx(Dc,{className:"w-4 h-4"})})]}),a.jsx(Ie,{onClick:K,disabled:!m||$==="accessCode",variant:"primary",children:$==="accessCode"?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("common.save")})]}),m&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a.jsx("span",{className:m.length===8?"text-green-400":"text-yellow-400",children:n("virtualPrinter.accessCode.charCount",{count:m.length})})})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.targetPrinter.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:v??"",onChange:j=>{const z=parseInt(j.target.value,10);isNaN(z)||be(z)},disabled:$==="targetPrinter",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[a.jsx("option",{value:"",children:n("virtualPrinter.targetPrinter.placeholder")}),re?.map(j=>a.jsxs("option",{value:j.id,children:[j.name," (",j.ip_address,")"]},j.id))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.bindIp.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:g,onChange:j=>{_(j.target.value),I("bindIp"),ee.mutate({bind_ip:j.target.value})},disabled:$==="bindIp",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[a.jsx("option",{value:"",children:n("virtualPrinter.bindIp.placeholder")}),ae?.map(j=>a.jsxs("option",{value:j.ip,children:[j.name," (",j.ip,")",j.is_alias?" [alias]":""," - ",j.subnet]},j.ip))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("virtualPrinter.bindIp.hint")})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.remoteInterface.title")}),k?a.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:a.jsx(Kr,{className:"w-3 h-3"})}):a.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:n("virtualPrinter.remoteInterface.optional"),children:a.jsx(Ks,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:k,onChange:j=>Ne(j.target.value),disabled:$==="remoteInterface",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[a.jsx("option",{value:"",children:n("virtualPrinter.remoteInterface.placeholder")}),ae?.map(j=>a.jsxs("option",{value:j.ip,children:[j.name," (",j.ip,") - ",j.subnet]},j.ip))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),Q&&a.jsx(kn,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:ue.isPending,onConfirm:()=>ue.mutate(),onCancel:()=>L(!1)})]})}const QY={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function Ctt({onClose:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),[i,s]=w.useState(""),[o,l]=w.useState("immediate"),[c,d]=w.useState(null),{data:u}=et({queryKey:["printers"],queryFn:he.getPrinters}),m=lt({mutationFn:()=>oN.create({name:i.trim()||"Bambuddy",mode:o,target_printer_id:o==="proxy"?c??void 0:void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["virtual-printers"]}),r(e("virtualPrinter.toast.created")),t()},onError:p=>{r(p.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:a.jsx(Dt,{className:"w-full max-w-md",onClick:p=>p.stopPropagation(),children:a.jsxs(Rt,{className:"p-6 space-y-4",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),a.jsx("input",{type:"text",value:i,onChange:p=>s(p.target.value),placeholder:"Bambuddy",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm placeholder-bambu-gray",autoFocus:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(p=>a.jsxs("button",{onClick:()=>l(p),className:`p-2 rounded-lg border text-left transition-colors ${o===p?p==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[p==="proxy"&&a.jsx(L3,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${QY[p]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${QY[p]}Desc`)})]},p))})]}),o==="proxy"&&a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:c??"",onChange:p=>{const f=parseInt(p.target.value,10);d(isNaN(f)?null:f)},className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm appearance-none cursor-pointer pr-10",children:[a.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),u?.map(p=>a.jsxs("option",{value:p.id,children:[p.name," (",p.ip_address,")"]},p.id))]}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",disabled:m.isPending,children:e("common.cancel")}),a.jsx(Ie,{variant:"primary",onClick:()=>m.mutate(),className:"flex-1",disabled:m.isPending,children:m.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function Ptt(){const{t}=Lt(),[e,n]=w.useState(!1),{data:r,isLoading:i}=et({queryKey:["virtual-printers"],queryFn:oN.list,refetchInterval:1e4});if(i)return a.jsx(Dt,{children:a.jsx(Rt,{className:"py-8 flex justify-center",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const s=r?.printers||[],o=r?.models||{};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4 items-stretch",children:[a.jsx(Dt,{className:"border-l-4 border-l-yellow-500",children:a.jsx(Rt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs",children:[a.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),a.jsxs("a",{href:"https://wiki.bambuddy.cool/features/virtual-printer/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 mt-2 px-3 py-1.5 bg-yellow-500/20 border border-yellow-500/50 rounded text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs",children:[a.jsx(sa,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),a.jsx(Dt,{className:"lg:col-span-3",children:a.jsx(Rt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Ks,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),a.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Pr,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s.length,")"]})]}),a.jsxs(Ie,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(ur,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),s.length===0?a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-8 text-center",children:[a.jsx(Pr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),a.jsxs(Ie,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(ur,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:s.map(l=>a.jsx(Ntt,{printer:l,models:o},l.id))}),e&&a.jsx(Ctt,{onClose:()=>n(!1)})]})}function Ttt(t){if(!t)return"-";const e=Qn(t);return e?e.toLocaleString():"-"}function ZY({status:t}){if(!t)return null;const e={success:"bg-green-500/20 text-green-400",failed:"bg-red-500/20 text-red-400",skipped:"bg-yellow-500/20 text-yellow-400",running:"bg-blue-500/20 text-blue-400"},n={success:a.jsx(fr,{className:"w-3 h-3"}),failed:a.jsx($a,{className:"w-3 h-3"}),skipped:a.jsx(CP,{className:"w-3 h-3"}),running:a.jsx(ct,{className:"w-3 h-3 animate-spin"})};return a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${e[t]||"bg-gray-500/20 text-gray-400"}`,children:[n[t],t.charAt(0).toUpperCase()+t.slice(1)]})}function Att(){const t=mn(),{showToast:e}=xn(),{t:n}=Lt(),[r,i]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[d,u]=w.useState(!1),[m,p]=w.useState("daily"),[f,y]=w.useState(!0),[v,b]=w.useState(!0),[g,_]=w.useState(!1),[k,P]=w.useState(!1),[N,M]=w.useState(!1),[T,A]=w.useState(!0),[C,F]=w.useState(!1),[$,I]=w.useState(!1),[Q,L]=w.useState(""),[re,ae]=w.useState(!1),[ee,ue]=w.useState(null),[le,de]=w.useState(null),K=w.useRef(null);w.useEffect(()=>{if(C||$){const Se=ye=>(ye.preventDefault(),ye.returnValue="A backup operation is in progress. Are you sure you want to leave?",ye.returnValue);return window.addEventListener("beforeunload",Se),()=>window.removeEventListener("beforeunload",Se)}},[C,$]);const[te,se]=w.useState(!1),[be,Ne]=w.useState(null),B=w.useRef(null),Y=w.useRef(!1),{data:D,isLoading:j}=et({queryKey:["github-backup-config"],queryFn:he.getGitHubBackupConfig}),{data:z}=et({queryKey:["github-backup-status"],queryFn:he.getGitHubBackupStatus,refetchInterval:xe=>xe.state.data?.is_running?500:1e4}),{data:W}=et({queryKey:["github-backup-logs"],queryFn:()=>he.getGitHubBackupLogs(20)}),{data:q}=et({queryKey:["cloud-status"],queryFn:he.getCloudStatus}),{data:ce}=et({queryKey:["printers"],queryFn:he.getPrinters}),O=ep({queries:(ce??[]).map(xe=>({queryKey:["printerStatus",xe.id],queryFn:()=>he.getPrinterStatus(xe.id),staleTime:1e4,refetchInterval:3e4}))}),G=(ce??[]).map((xe,Se)=>({printer:xe,connected:O[Se]?.data?.connected??!1})),X=G.length,V=G.filter(xe=>xe.connected).length,J=X>0&&V===0,ie=V>0&&V{D&&(i(D.repository_url),c(D.branch),u(D.schedule_enabled),p(D.schedule_type),y(D.backup_kprofiles),b(D.backup_cloud_profiles),_(D.backup_settings),P(D.backup_spools),M(D.backup_archives),A(D.enabled),o(""),setTimeout(()=>{Y.current=!0},100))},[D]);const me=w.useCallback(async(xe=!1)=>{if(D?.has_token)try{xe&&s?(await he.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:g,backup_spools:k,backup_archives:N,enabled:T}),o(""),e(n("backup.tokenUpdated"))):(await he.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:g,backup_spools:k,backup_archives:N,enabled:T}),e(n("backup.settingsSaved"))),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(Se){e(n("backup.failedToSave",{message:Se.message}),"error")}},[D?.has_token,r,s,l,d,m,f,v,g,k,N,T,t,e,n]);w.useEffect(()=>{if(!(!Y.current||!D?.has_token))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{me(!1)},500),()=>{B.current&&clearTimeout(B.current)}},[r,l,d,m,f,v,g,k,N,T,me,D?.has_token]),w.useEffect(()=>{if(!(!Y.current||!D?.has_token||!s))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{me(!0)},1e3),()=>{B.current&&clearTimeout(B.current)}},[s,me,D?.has_token]);const pe=lt({mutationFn:xe=>he.saveGitHubBackupConfig(xe),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e(n("backup.githubBackupEnabled")),o(""),Y.current=!0},onError:xe=>{e(n("backup.failedToSave",{message:xe.message}),"error")}}),oe=lt({mutationFn:he.triggerGitHubBackup,onSuccess:xe=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),xe.success?xe.files_changed>0?e(n("backup.backupCompleteFiles",{count:xe.files_changed})):e(n("backup.backupSkippedNoChanges")):e(n("backup.backupFailed2",{message:xe.message}),"error")},onError:xe=>{e(n("backup.backupFailed2",{message:xe.message}),"error")}}),U=lt({mutationFn:()=>he.clearGitHubBackupLogs(0),onSuccess:xe=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(n("backup.clearedLogs",{count:xe.deleted}))},onError:xe=>{e(n("backup.failedToClearLogs",{message:xe.message}),"error")}}),R=async()=>{se(!0),Ne(null);try{let xe;if(s){if(!r){e(n("backup.enterRepoUrl"),"error"),se(!1);return}xe=await he.testGitHubConnection(r,s)}else if(D?.has_token)xe=await he.testGitHubStoredConnection();else{e(n("backup.enterRepoAndToken"),"error"),se(!1);return}Ne({success:xe.success,message:xe.message})}catch(xe){Ne({success:!1,message:xe.message})}finally{se(!1)}},ne=()=>{if(!r){e(n("backup.repoRequired"),"error");return}if(!s){e(n("backup.tokenRequired"),"error");return}pe.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:g,backup_spools:k,backup_archives:N,enabled:T})};return j?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(I3,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.githubBackup")})]}),D&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("backup.enabled")}),a.jsx(Vn,{checked:T,onChange:A})]})]})}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.githubDescription")}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.repositoryUrl")}),a.jsx("input",{type:"text",value:r,onChange:xe=>{i(xe.target.value),Ne(null)},placeholder:"https://github.com/username/bambuddy-backup",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"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[n("backup.personalAccessToken")," ",D?.has_token&&a.jsx("span",{className:"text-green-400",children:n("backup.tokenSaved")})]}),a.jsx("input",{type:"password",value:s,onChange:xe=>{o(xe.target.value),Ne(null)},placeholder:D?.has_token?n("backup.enterNewToken"):"ghp_xxxxxxxxxxxx",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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("backup.tokenHint")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.branch")}),a.jsx("input",{type:"text",value:l,onChange:xe=>c(xe.target.value),placeholder:"main",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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.autoBackup")}),a.jsxs("select",{value:d?m:"disabled",onChange:xe=>{xe.target.value==="disabled"?u(!1):(u(!0),p(xe.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",children:[a.jsx("option",{value:"disabled",children:n("backup.manualOnly")}),a.jsx("option",{value:"hourly",children:n("backup.hourly")}),a.jsx("option",{value:"daily",children:n("backup.daily")}),a.jsx("option",{value:"weekly",children:n("backup.weekly")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:n("backup.includeInBackup")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:`flex items-start gap-2 ${J?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[a.jsx("input",{type:"checkbox",checked:f,onChange:xe=>y(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:J}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${J?"text-bambu-gray":"text-white"}`,children:n("backup.kProfiles")}),J&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("backup.noPrintersConnected")]}),ie&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("backup.printersConnected",{connected:V,total:X})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.kProfilesDescription")})]})]}),a.jsxs("label",{className:`flex items-start gap-2 ${q?.is_authenticated?"cursor-pointer":"cursor-not-allowed opacity-60"}`,children:[a.jsx("input",{type:"checkbox",checked:v,onChange:xe=>b(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:!q?.is_authenticated}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${q?.is_authenticated?"text-white":"text-bambu-gray"}`,children:n("backup.cloudProfiles")}),!q?.is_authenticated&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Ln,{className:"w-3 h-3"}),n("backup.cloudLoginRequiredShort")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.cloudProfilesDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:g,onChange:xe=>_(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.appSettings")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.appSettingsDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:k,onChange:xe=>P(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.spoolInventory")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.spoolInventoryDescription")})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:N,onChange:xe=>M(xe.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:n("backup.printArchives")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.printArchivesDescription")})]})]})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[z?.configured&&a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:z.last_backup_at?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[n("backup.lastBackupAt")," ",Sx(z.last_backup_at,"system",n)]}),a.jsx(ZY,{status:z.last_backup_status})]}):a.jsx("span",{children:n("backup.noBackupsYet")})}),z.next_scheduled_run&&a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx(rr,{className:"w-3 h-3 inline mr-1"}),n("backup.next")," ",Sx(z.next_scheduled_run,"system",n)]})]}),be&&a.jsxs("div",{className:`text-sm flex items-center gap-1 ${be.success?"text-green-400":"text-red-400"}`,children:[be.success?a.jsx(fr,{className:"w-4 h-4"}):a.jsx($a,{className:"w-4 h-4"}),be.message]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:z?.configured?a.jsx(a.Fragment,{children:oe.isPending||z.is_running?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{className:"text-sm",children:z.progress||n("backup.startingBackup")})]}):a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"primary",size:"sm",onClick:()=>oe.mutate(),disabled:!D?.enabled,children:[a.jsx(Ds,{className:"w-4 h-4"}),n("backup.backupNow")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:R,disabled:te,children:[te?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),n("backup.test")]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"primary",size:"sm",onClick:ne,disabled:pe.isPending||!r||!s,children:[pe.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(fr,{className:"w-4 h-4"}),n("backup.enableBackup")]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:R,disabled:te||!r||!s,children:[te?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),n("backup.testConnection")]})]})})]})]})]}),W&&W.length>0&&a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(L0,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.history")})]}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:[a.jsx(un,{className:"w-4 h-4"}),n("backup.clear")]})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.date")}),a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.status")}),a.jsx("th",{className:"text-left py-2 px-2",children:n("backup.commit")})]})}),a.jsx("tbody",{children:W.slice(0,10).map(xe=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[a.jsx("td",{className:"py-2 px-2 text-white",children:Ttt(xe.started_at)}),a.jsx("td",{className:"py-2 px-2",children:a.jsx(ZY,{status:xe.status})}),a.jsx("td",{className:"py-2 px-2",children:xe.commit_sha?a.jsxs("a",{href:`${D?.repository_url}/commit/${xe.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[xe.commit_sha.substring(0,7),a.jsx(sa,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-bambu-gray",children:"-"})})]},xe.id))})]})})})]})]}),a.jsx("div",{className:"space-y-6",children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ul,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.localBackup")})]})}),a.jsxs(Rt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.localBackupDescription")}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.downloadBackupLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.completeBackupZip")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",disabled:C||$,onClick:async()=>{F(!0),L(n("backup.preparingBackup"));try{L(n("backup.creatingArchive"));const{blob:xe,filename:Se}=await he.exportBackup();L(n("backup.downloadingFile"));const ye=URL.createObjectURL(xe),ve=document.createElement("a");ve.href=ye,ve.download=Se,ve.click(),URL.revokeObjectURL(ye),e(n("backup.backupDownloaded"))}catch(xe){e(n("backup.failedToCreateBackup",{message:xe instanceof Error?xe.message:"Unknown error"}),"error")}finally{F(!1),L("")}},children:[a.jsx(va,{className:"w-4 h-4"}),n("backup.download")]})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),a.jsx("input",{ref:K,type:"file",accept:".zip",className:"hidden",onChange:xe=>{const Se=xe.target.files?.[0];Se&&(ue(Se),ae(!0)),xe.target.value=""}}),a.jsxs(Ie,{variant:"secondary",size:"sm",disabled:$||C,onClick:()=>K.current?.click(),children:[a.jsx(Ca,{className:"w-4 h-4"}),n("backup.restore")]})]}),le&&a.jsx("div",{className:`p-3 rounded-lg ${le.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[le.success?a.jsx(fr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):a.jsx($a,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:le.success?"text-green-200":"text-red-200",children:[le.message,le.success&&a.jsx("div",{className:"mt-2",children:a.jsxs(Ie,{size:"sm",onClick:()=>window.location.reload(),children:[a.jsx(jo,{className:"w-3 h-3"}),n("backup.reloadNow")]})})]})]})}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-yellow-200",children:[a.jsx("span",{className:"font-medium",children:n("backup.restoreReplacesAll")})," ",a.jsx("span",{className:"text-yellow-200/70",children:n("backup.restoreReplacesAllDetail")})]})]})})]})]})}),re&&ee&&a.jsx(kn,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:ee.name}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:async()=>{ae(!1),I(!0),de(null);try{L(n("backup.uploadingFile"));const xe=await he.importBackup(ee);de(xe),xe.success?e(n("backup.backupRestoredRestart"),"success"):e(xe.message,"error")}catch(xe){const Se=xe instanceof Error?xe.message:n("backup.failedToRestore");de({success:!1,message:Se}),e(Se,"error")}finally{I(!1),L(""),ue(null)}},onCancel:()=>{ae(!1),ue(null)}}),(C||$)&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center",children:[a.jsx("div",{className:"flex justify-center mb-4",children:a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),a.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:n(C?"backup.creatingBackup":"backup.restoringBackup")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:Q||n(C?"backup.preparing":"backup.processing")}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Ln,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-yellow-200 text-left",children:n("backup.doNotClosePage")})]})})]})})]})}const Mtt={starttls:587,ssl:465,none:25},jtt={587:"starttls",465:"ssl",25:"none"};function Ett(){const{t}=Lt(),{showToast:e}=xn(),n=mn(),[r,i]=w.useState({smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",smtp_security:"starttls",smtp_auth_enabled:!0,smtp_from_email:"",smtp_from_name:"BamBuddy"}),[s,o]=w.useState(""),{data:l,isLoading:c}=et({queryKey:["smtpSettings"],queryFn:()=>he.getSMTPSettings()}),{authEnabled:d}=Sr(),{data:u}=et({queryKey:["advancedAuthStatus"],queryFn:()=>he.getAdvancedAuthStatus()});w.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const m=T=>{i({...r,smtp_security:T,smtp_port:Mtt[T]})},p=T=>{const A=jtt[T];i({...r,smtp_port:T,...A?{smtp_security:A}:{}})},f=T=>{i({...r,smtp_auth_enabled:T,...T?{}:{smtp_username:"",smtp_password:""}})},y=lt({mutationFn:T=>he.saveSMTPSettings(T),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:T=>{e(T.message,"error")}}),v=lt({mutationFn:T=>he.testSMTP(T),onSuccess:T=>{e(T.message,T.success?"success":"error")},onError:T=>{e(T.message,"error")}}),b=lt({mutationFn:T=>T?he.enableAdvancedAuth():he.disableAdvancedAuth(),onSuccess:T=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(T.message,"success")},onError:T=>{e(T.message,"error")}}),g=()=>{if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(r.smtp_auth_enabled&&!r.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}y.mutate(r)},_=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}v.mutate({test_recipient:s})},k=()=>{if(!d){e(t("settings.email.errors.enableAuthFirst"),"error");return}if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}b.mutate(!u?.advanced_auth_enabled)};if(c)return a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});const P=u?.advanced_auth_enabled??!1,N="w-full px-3 py-2 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",M="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";return a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(vx,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),a.jsx(Ie,{onClick:k,disabled:b.isPending,variant:P?"danger":"primary",children:P?a.jsxs(a.Fragment,{children:[a.jsx(s0,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(ld,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),a.jsx(Rt,{children:a.jsx("div",{className:"space-y-3",children:P?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(fr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),a.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),a.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),a.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Ln,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[a.jsx("div",{className:"lg:col-span-2",children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),a.jsx(Rt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.authentication")||"Authentication"}),a.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:T=>f(T.target.value==="true"),className:N,children:[a.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),a.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),a.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-4 transition-opacity ${r.smtp_auth_enabled?"":"opacity-40 pointer-events-none"}`,children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.username")||"Username"}),a.jsx("input",{type:"text",value:r.smtp_username||"",onChange:T=>i({...r,smtp_username:T.target.value}),placeholder:"your.email@gmail.com",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?N:M})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.password")||"Password"}),a.jsx("input",{type:"password",value:r.smtp_password||"",onChange:T=>i({...r,smtp_password:T.target.value}),placeholder:l?"••••••••":"App password",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?N:M})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),a.jsx("input",{type:"text",value:r.smtp_host,onChange:T=>i({...r,smtp_host:T.target.value}),placeholder:"smtp.gmail.com",className:N})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.smtpPort")||"SMTP Port"}),a.jsx("input",{type:"number",value:r.smtp_port,onChange:T=>p(parseInt(T.target.value)||587),placeholder:"587",className:N})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.security")||"Security"}),a.jsxs("select",{value:r.smtp_security,onChange:T=>m(T.target.value),className:N,children:[a.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),a.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),a.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.fromEmail")||"From Email"," *"]}),a.jsx("input",{type:"email",value:r.smtp_from_email,onChange:T=>i({...r,smtp_from_email:T.target.value}),placeholder:"your@email.com",className:N})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.fromName")||"From Name"}),a.jsx("input",{type:"text",value:r.smtp_from_name,onChange:T=>i({...r,smtp_from_name:T.target.value}),placeholder:"BamBuddy",className:N})]})]}),a.jsx("div",{className:"flex gap-2",children:a.jsx(Ie,{onClick:g,disabled:y.isPending,className:"flex-1",children:y.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),a.jsx("div",{children:a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),a.jsx(Rt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.testRecipient")||"Test Recipient Email"}),a.jsx("input",{type:"email",value:s,onChange:T=>o(T.target.value),placeholder:"test@example.com",className:N})]}),a.jsx(Ie,{onClick:_,disabled:v.isPending,variant:"secondary",children:v.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Lw,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})]})}const Dtt={starttls:"389",ldaps:"636"};function Ftt(){const{t}=Lt(),{showToast:e}=xn(),n=mn(),{authEnabled:r}=Sr(),[i,s]=w.useState({ldap_server_url:"",ldap_bind_dn:"",ldap_bind_password:"",ldap_search_base:"",ldap_user_filter:"(sAMAccountName={username})",ldap_security:"starttls",ldap_group_mapping:"",ldap_auto_provision:!1,ldap_default_group:""}),{data:o,isLoading:l}=et({queryKey:["settings"],queryFn:()=>he.getSettings()}),{data:c}=et({queryKey:["ldapStatus"],queryFn:()=>he.getLDAPStatus()}),{data:d=[]}=et({queryKey:["groups"],queryFn:()=>he.getGroups()});w.useEffect(()=>{o&&s({ldap_server_url:o.ldap_server_url||"",ldap_bind_dn:o.ldap_bind_dn||"",ldap_bind_password:"",ldap_search_base:o.ldap_search_base||"",ldap_user_filter:o.ldap_user_filter||"(sAMAccountName={username})",ldap_security:o.ldap_security||"starttls",ldap_group_mapping:o.ldap_group_mapping||"",ldap_auto_provision:o.ldap_auto_provision??!1,ldap_default_group:o.ldap_default_group||""})},[o]);const u=lt({mutationFn:g=>he.updateSettings(g),onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]}),n.invalidateQueries({queryKey:["ldapStatus"]}),e(t("settings.ldap.settingsSaved")||"LDAP settings saved","success")},onError:g=>{e(g.message,"error")}}),m=lt({mutationFn:g=>he.updateSettings({ldap_enabled:g}),onSuccess:()=>{n.invalidateQueries({queryKey:["settings"]}),n.invalidateQueries({queryKey:["ldapStatus"]}),e(c?.ldap_enabled?t("settings.ldap.disabled")||"LDAP authentication disabled":t("settings.ldap.enabled")||"LDAP authentication enabled","success")},onError:g=>{e(g.message,"error")}}),p=lt({mutationFn:()=>he.testLDAP(),onSuccess:g=>{e(g.message,g.success?"success":"error")},onError:g=>{e(g.message,"error")}}),f=()=>{if(!i.ldap_server_url){e(t("settings.ldap.errors.serverRequired")||"LDAP server URL is required","error");return}if(!i.ldap_search_base){e(t("settings.ldap.errors.searchBaseRequired")||"Search base DN is required","error");return}const g={ldap_server_url:i.ldap_server_url,ldap_bind_dn:i.ldap_bind_dn,ldap_search_base:i.ldap_search_base,ldap_user_filter:i.ldap_user_filter,ldap_security:i.ldap_security,ldap_group_mapping:i.ldap_group_mapping,ldap_auto_provision:i.ldap_auto_provision,ldap_default_group:i.ldap_default_group};i.ldap_bind_password&&(g.ldap_bind_password=i.ldap_bind_password),u.mutate(g)},y=()=>{if(!r){e(t("settings.ldap.errors.enableAuthFirst")||"Enable authentication first","error");return}if(!c?.ldap_enabled&&!c?.ldap_configured){e(t("settings.ldap.errors.configureLdapFirst")||"Save LDAP settings first","error");return}m.mutate(!c?.ldap_enabled)};if(l)return a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});const v=c?.ldap_enabled??!1,b="w-full px-3 py-2 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";return a.jsxs("div",{className:"space-y-3",children:[a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wb,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.title")||"LDAP Authentication"})]}),a.jsx(Ie,{onClick:y,disabled:m.isPending,variant:v?"danger":"primary",children:v?a.jsxs(a.Fragment,{children:[a.jsx(s0,{className:"w-4 h-4"}),t("common.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(ld,{className:"w-4 h-4"}),t("common.enable")||"Enable"]})})]})}),a.jsx(Rt,{children:v?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(fr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.enabledDesc")||"LDAP authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.ldap.feature1")||"Users can login with LDAP credentials"}),a.jsx("li",{children:t("settings.ldap.feature2")||"Local admin account remains as fallback"}),a.jsx("li",{children:t("settings.ldap.feature3")||"LDAP groups are mapped to BamBuddy groups on login"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Ln,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.disabledDesc")||"LDAP authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300 mt-1",children:t("settings.ldap.disabledHint")||"Configure and save LDAP settings below, then enable."})]})]})})})]}),a.jsxs(Dt,{children:[a.jsx(Dn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.serverConfig")||"LDAP Server Configuration"})}),a.jsx(Rt,{children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[a.jsxs("div",{className:"md:col-span-2",children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.serverUrl")||"Server URL"}),a.jsx("input",{type:"text",className:b,placeholder:"ldaps://ldap.example.com:636",value:i.ldap_server_url,onChange:g=>s({...i,ldap_server_url:g.target.value})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.serverUrlHint")||"Use ldaps:// for SSL or ldap:// with StartTLS"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.security")||"Security"}),a.jsx("div",{className:"flex gap-2",children:["starttls","ldaps"].map(g=>a.jsx("button",{onClick:()=>s({...i,ldap_security:g}),className:`flex-1 px-2 py-2 rounded-lg text-sm font-medium transition-colors ${i.ldap_security===g?"bg-bambu-green text-black":"bg-bambu-dark-secondary text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:g==="starttls"?"StartTLS":"LDAPS"},g))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.securityHint")||`Default port: ${Dtt[i.ldap_security]}`})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindDn")||"Bind DN (Service Account)"}),a.jsx("input",{type:"text",className:b,placeholder:"cn=service-account,ou=service,dc=example,dc=com",value:i.ldap_bind_dn,onChange:g=>s({...i,ldap_bind_dn:g.target.value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindPassword")||"Bind Password"}),a.jsx("input",{type:"password",className:b,placeholder:o?.ldap_bind_dn?"••••••••":"",value:i.ldap_bind_password,onChange:g=>s({...i,ldap_bind_password:g.target.value})})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.searchBase")||"Search Base DN"}),a.jsx("input",{type:"text",className:b,placeholder:"ou=users,dc=example,dc=com",value:i.ldap_search_base,onChange:g=>s({...i,ldap_search_base:g.target.value})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.userFilter")||"User Search Filter"}),a.jsx("input",{type:"text",className:b,placeholder:"(sAMAccountName={username})",value:i.ldap_user_filter,onChange:g=>s({...i,ldap_user_filter:g.target.value})})]})]}),a.jsx(lle,{summary:a.jsx("span",{className:"text-sm font-medium text-bambu-gray",children:t("settings.ldap.advanced")||"Advanced"}),className:"border-t border-bambu-dark-tertiary pt-3",summaryClassName:"py-1",children:a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white",children:t("settings.ldap.autoProvision")||"Auto-provision users"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:t("settings.ldap.autoProvisionHint")||"Automatically create a BamBuddy account on first LDAP login"})]}),a.jsx("button",{onClick:()=>s({...i,ldap_auto_provision:!i.ldap_auto_provision}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${i.ldap_auto_provision?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.ldap_auto_provision?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.defaultGroup")||"Default group"}),a.jsxs("select",{className:b,value:i.ldap_default_group,onChange:g=>s({...i,ldap_default_group:g.target.value}),children:[a.jsx("option",{value:"",children:t("settings.ldap.defaultGroupNone")||"— None (reject login) —"}),d.map(g=>a.jsx("option",{value:g.name,children:g.name},g.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.defaultGroupHint")||"Fallback group assigned when an LDAP user authenticates but is not listed in any mapped group. Leave empty to leave unmapped users without permissions."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.groupMapping")||"Group Mapping (JSON)"}),a.jsx("textarea",{className:`${b} font-mono text-sm`,rows:4,placeholder:`{
"CN=PrintFarm_Admins,OU=Groups,DC=example,DC=com": "Administrators",
"CN=PrintFarm_Users,OU=Groups,DC=example,DC=com": "Operators"
@@ -8717,7 +8717,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ls(t.
`+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{
`+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+BL(o,e+1)).join(`,
`)+`
-`+n+"}"}return String(t)}function Qtt({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=xn(),c=mn(),[d,u]=w.useState(!1),{data:m,isLoading:p}=et({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>he.getCloudSettingDetail(t.setting_id)}),f=lt({mutationFn:()=>he.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=kw(t.setting_id),v=Kz(t.name,m?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&a.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")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.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:BL(m)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Ln,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Ie,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Ie,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(Mo,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(Za,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Ie,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(un,{className:"w-4 h-4"})})]})]})})]})})})}function mle(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function hle(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Ztt({onClose:t,onApply:e,t:n}){const{showToast:r}=xn(),[i,s]=w.useState(mle),[o,l]=w.useState("all"),[c,d]=w.useState(null),[u,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,k]=w.useState(null),P=o==="all"?i:i.filter(Q=>Q.type===o),N=Q=>{s(Q),hle(Q)},M=Q=>{const L=i.filter(re=>re.id!==Q);N(L),k(null),r(n("profiles.templates.toast.deleted"))},T=Q=>{d(Q.id),m(Q.name),f(Q.description),v(JSON.stringify(Q.settings,null,2)),g(null)},A=()=>{if(!(!c||!u.trim()))try{const Q=JSON.parse(y),L=i.map(re=>re.id===c?{...re,name:u.trim(),description:p.trim(),settings:Q}:re);N(L),d(null),r(n("profiles.templates.toast.updated"))}catch(Q){g(Q.message)}},C=()=>{d(null),m(""),f(""),v("{}"),g(null)},F=Q=>{const L=i.map(re=>re.id===Q?{...re,showInModal:!re.showInModal}:re);N(L)},$={filament:{label:n("profiles.presets.types.filament"),icon:SP,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Nd,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Pr,color:"text-purple-400"}},I=_?i.find(Q=>Q.id===_):null;return w.useEffect(()=>{const Q=L=>{L.key==="Escape"&&(_?k(null):c?C():t())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[_,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(Dt,{className:"w-full max-w-md",children:a.jsxs(Rt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Ln,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:I.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>k(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Ie,{onClick:()=>M(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(un,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(Dt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(wx,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(Q=>a.jsx("button",{onClick:()=>l(Q),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===Q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:Q==="all"?n("common.all"):$[Q].label},Q))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(wx,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:P.map(Q=>{const L=$[Q.type],re=L.icon;return c===Q.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:u,onChange:ae=>m(ae.target.value),placeholder:n("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}),a.jsx("input",{type:"text",value:p,onChange:ae=>f(ae.target.value),placeholder:n("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"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:y,onChange:ae=>{v(ae.target.value),g(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&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{size:"sm",onClick:A,disabled:!u.trim(),children:[a.jsx(cs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:C,children:"Cancel"})]})]},Q.id):a.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:[a.jsx(re,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Q.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Q.description})]}),a.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(Q.settings).length})}),a.jsx("button",{onClick:()=>F(Q.id),className:`p-1 transition-colors ${Q.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:Q.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:Q.showInModal?a.jsx(Dc,{className:"w-4 h-4"}):a.jsx(Tw,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(Q),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),a.jsx("button",{onClick:()=>T(Q),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>k(Q.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(un,{className:"w-4 h-4"})})]},Q.id)})})})]})})]})}function ple({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,d]=w.useState(""),u=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],k=b in e,P=b in n;let N;!k&&P?N="added":k&&!P?N="removed":JSON.stringify(g)!==JSON.stringify(_)?N="changed":N="same",v.push({key:b,left:g,right:_,status:N})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...u];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[u,o,c]),p=w.useMemo(()=>({added:u.filter(y=>y.status==="added").length,removed:u.filter(y=>y.status==="removed").length,changed:u.filter(y=>y.status==="changed").length,same:u.filter(y=>y.status==="same").length}),[u]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);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 w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(tx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(ur,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(rN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(O3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(uj,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:y=>d(y.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&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.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")}),a.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")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(uj,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:a.jsx(ur,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(rN,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(O3,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(uj,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[b,a.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Jtt({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=xn(),s=mn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[d,u]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[k,P]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,M]=w.useState(null),[T,A]=w.useState(""),[C,F]=w.useState(!1),[$,I]=w.useState(""),[Q,L]=w.useState(!1),[re,ae]=w.useState(mle),[ee,ue]=w.useState(!1),[le,de]=w.useState(""),[K,te]=w.useState(""),[se,be]=w.useState(!0),[Ne,B]=w.useState(null),[Y,D]=w.useState(!1),j=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),z=w.useMemo(()=>j.filter(je=>kw(je.setting_id)),[j]),{data:W}=et({queryKey:["cloudFields",d],queryFn:()=>he.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:q}=et({queryKey:["allPresetDetails",d,z.map(je=>je.setting_id).join(",")],queryFn:async()=>{const je={};for(let Re=0;Re{try{const De=await he.getCloudSettingDetail($e.setting_id);return{id:$e.setting_id,detail:De}}catch{return null}}))).forEach($e=>{$e&&(je[$e.id]=$e.detail)})}return je},enabled:z.length>0,staleTime:1e3*60*10}),{data:ce,isLoading:O}=et({queryKey:["cloudSettingDetail",f],queryFn:()=>he.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&P(JSON.stringify(g,null,2))},[g,l]);const G=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter(Be=>!kw(Be.setting_id)).sort((Be,Re)=>Be.name.localeCompare(Re.name)),[n,d]);w.useEffect(()=>{if(!f)return;const je=G.find(Be=>Be.setting_id===f);je&&(b(je.name),o||(_({inherits:je.name}),P(JSON.stringify({inherits:je.name},null,2))))},[f,G,o]);const X=w.useMemo(()=>{const je=W?.fields||[],Be=new Set(je.map($e=>$e.key)),Re=new Set,Ye=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);q&&Object.values(q).forEach($e=>{$e?.setting&&Object.keys($e.setting).forEach(De=>{!Be.has(De)&&!Ye.has(De)&&Re.add(De)})}),Object.keys(g).forEach($e=>{!Be.has($e)&&!Ye.has($e)&&Re.add($e)});const we=Array.from(Re).sort().map($e=>({key:$e,label:$e.replace(/_/g," ").replace(/\b\w/g,De=>De.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...je,...we]},[W,q,g,r]),V=X.filter(je=>je.label.toLowerCase().includes(T.toLowerCase())||je.key.toLowerCase().includes(T.toLowerCase())),J=()=>{if($.trim()){const je=$.trim().toLowerCase().replace(/\s+/g,"_");ie(je,""),I(""),L(!1),i(r("profiles.presets.toast.fieldAdded",{key:je}))}},ie=(je,Be)=>{_(Re=>{const Ye={...Re};return Be===""||Be===void 0?delete Ye[je]:Ye[je]=Be,Ye})},me=je=>{_(Be=>({...Be,...je.settings})),B(je.name),i(r("profiles.templates.toast.applied"))},pe=()=>{if(!le.trim())return;const je={...g};if(delete je.inherits,Object.keys(je).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const Be={id:Date.now().toString(),name:le.trim(),description:K.trim()||r("profiles.presets.customTemplate"),type:d,settings:je,showInModal:se},Re=[...re,Be];ae(Re),hle(Re),ue(!1),de(""),te(""),be(!0),i(r("profiles.templates.toast.created"))},oe=w.useMemo(()=>re.filter(je=>je.type===d&&je.showInModal),[d,re]),U=je=>{P(je);try{const Be=JSON.parse(je);_(Be),M(null)}catch(Be){M(Be.message)}},R=je=>{je.preventDefault(),F(!1);const Be=je.dataTransfer.files[0];if(Be&&Be.name.endsWith(".json")){const Re=new FileReader;Re.onload=Ye=>{try{const we=Ye.target?.result,$e=JSON.parse(we),De=$e.setting||$e;_(Xe=>({...Xe,...De})),P(JSON.stringify({...g,...De},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Re.readAsText(Be)}},ne=lt({mutationFn:()=>{const je={...g},Be=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";je[Be]=`"${m}"`;const Re={type:d,name:m,base_id:f,setting:je};return he.createCloudSetting(Re)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:je=>i(je.message,"error")}),xe=lt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return he.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:je=>i(je.message,"error")}),Se=o?xe:ne,ye=ce?.setting?.inherits,ve=ye?G.find(je=>je.name===ye):void 0,{data:fe}=et({queryKey:["cloudSettingDetail",ve?.setting_id],queryFn:()=>he.getCloudSettingDetail(ve.setting_id),enabled:!!ve?.setting_id}),ke=w.useMemo(()=>{const je=fe?.setting||{},Be=ce?.setting||{},Re=f&&q?.[f]?.setting?q[f].setting:{};return{...je,...Be,...Re}},[f,ce,fe,q]),Ee=je=>{if(je==null)return"";if(Array.isArray(je)){const Be=[...new Set(je.map(Re=>String(Re)))];return Be.length===1?Be[0]:je.join(", ")}return String(je)},Ae=je=>{const Be=g[je.key],Re=ke[je.key],Ye=Ee(Re),we=O?r("common.loading"):Ye||"",$e="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(je.type==="boolean"){const De=Be==="1"||Be===void 0&&Re==="1";return a.jsx("button",{type:"button",onClick:()=>ie(je.key,Be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${De?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${De?"translate-x-3.5":"translate-x-0.5"}`})})}return je.type==="select"?a.jsxs("select",{value:Be||"",onChange:De=>ie(je.key,De.target.value),className:$e,children:[a.jsx("option",{value:"",children:we}),je.options?.map(De=>a.jsx("option",{value:De.value,children:De.label},De.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:je.type==="number"?"number":"text",value:Be!==void 0?String(Be):"",onChange:De=>ie(je.key,De.target.value),step:je.step,min:je.min,max:je.max,placeholder:we,className:$e}),je.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:je.unit})]})},_e=w.useMemo(()=>ce?.setting?ce.setting:{},[ce]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:je=>{je.preventDefault(),F(!0)},onDragLeave:()=>F(!1),onDrop:R,children:[Y&&f&&a.jsx(ple,{onClose:()=>D(!1),leftPreset:_e,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),a.jsx(Dt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[f&&a.jsxs("button",{onClick:()=>D(!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:r("profiles.presets.compareWithBase"),children:[a.jsx(tx,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),C&&a.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:a.jsxs("div",{className:"text-center",children:[a.jsx(Ca,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:d,onChange:je=>{u(je.target.value),y("")},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:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:f,onChange:je=>y(je.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:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),G.map(je=>a.jsx("option",{value:je.setting_id,children:je.name},je.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.jsx("input",{type:"text",value:m,onChange:je=>p(je.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:r("profiles.presets.myCustomPreset")})]})]}),v&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),O&&a.jsx(ct,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.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:[a.jsx(m6,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.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:[a.jsx(Ew,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.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:[a.jsx(ey,{className:"w-4 h-4"}),"JSON",N&&a.jsx(qa,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const je={name:m,type:d,base_id:f,setting:g},Be=new Blob([JSON.stringify(je,null,2)],{type:"application/json"}),Re=URL.createObjectURL(Be),Ye=document.createElement("a");Ye.href=Re,Ye.download=`${m||"preset"}.json`,document.body.appendChild(Ye),Ye.click(),document.body.removeChild(Ye),URL.revokeObjectURL(Re),i(r("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:r("profiles.presets.exportToJson"),children:[a.jsx(va,{className:"w-4 h-4"}),r("common.download")]}),a.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:r("profiles.presets.importFromJson"),children:[a.jsx(Ca,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:je=>{const Be=je.target.files?.[0];if(Be){const Re=new FileReader;Re.onload=Ye=>{try{const we=JSON.parse(Ye.target?.result),$e=we.setting||we;_(De=>({...De,...$e})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Re.readAsText(Be)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(wx,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(je=>je!=="inherits").length>0&&a.jsxs("button",{onClick:()=>ue(!ee),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(cs,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),ee&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:le,onChange:je=>de(je.target.value),placeholder:r("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}),a.jsx("input",{type:"text",value:K,onChange:je=>te(je.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{size:"sm",onClick:pe,disabled:!le.trim(),children:[a.jsx(cs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>ue(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>be(!se),className:`flex items-center gap-1.5 text-xs transition-colors ${se?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[se?a.jsx(Dc,{className:"w-3.5 h-3.5"}):a.jsx(Tw,{className:"w-3.5 h-3.5"}),r(se?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Ne&&a.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:[a.jsx(Kr,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:Ne})]}),a.jsx("button",{onClick:()=>B(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[oe.map(je=>a.jsxs("button",{onClick:()=>me(je),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:je.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:je.description})]},je.id)),oe.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:X.slice(0,10).map(je=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:je.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:Ae(je)})]},je.key))})]}),Object.keys(g).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([je])=>je!=="inherits").map(([je,Be])=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[je,": ",String(Be).slice(0,20),a.jsx("button",{onClick:()=>ie(je,void 0),className:"hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},je))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:q?r("profiles.templates.fieldsCount",{count:X.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:T,onChange:je=>A(je.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[V.filter(je=>!(je.key in g)).map(je=>{const Be=ke[je.key],Re=Ee(Be);return a.jsxs("div",{onClick:()=>{_(Ye=>({...Ye,[je.key]:Re||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:je.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:je.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Re&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Re,children:[Re.slice(0,20),Re.length>20?"...":""]}),a.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:a.jsx(ur,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},je.key)}),V.filter(je=>!(je.key in g)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(T?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:Q?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:$,onChange:je=>I(je.target.value),onKeyDown:je=>je.key==="Enter"&&J(),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}),a.jsx(Ie,{size:"sm",onClick:J,disabled:!$.trim(),children:a.jsx(ur,{className:"w-4 h-4"})}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>{L(!1),I("")},children:a.jsx(Bt,{className:"w-4 h-4"})})]}):a.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:[a.jsx(ur,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(je=>je!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([je])=>je!=="inherits").map(([je,Be])=>{const Re=X.find(Ye=>Ye.key===je);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Re?.label||je}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:je})]}),a.jsx("button",{onClick:()=>ie(je,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),Re?Ae(Re):a.jsx("input",{type:"text",value:String(Be),onChange:Ye=>ie(je,Ye.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"})]},je)}),Object.keys(g).filter(je=>je!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(m6,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(je=>je!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{ue(!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:[a.jsx(cs,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[N&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(qa,{className:"w-4 h-4"}),N]}),a.jsx("textarea",{value:k,onChange:je=>U(je.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 ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ie,{onClick:()=>Se.mutate(),disabled:Se.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[Se.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o?a.jsx(cs,{className:"w-4 h-4"}):a.jsx(ur,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function ent({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[d,u]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[k,P]=w.useState("all"),[N,M]=w.useState(null),[T,A]=w.useState(!1),[C,F]=w.useState(!1),[$,I]=w.useState(null),[Q,L]=w.useState(null),[re,ae]=w.useState(null),[ee,ue]=w.useState(!1),[le,de]=w.useState([null,null]),[K,te]=w.useState(!1),[se,be]=w.useState(null),Ne=mn(),B=w.useMemo(()=>[...t.filament.map(J=>({...J,type:"filament"})),...t.printer.map(J=>({...J,type:"printer"})),...t.process.map(J=>({...J,type:"process"}))].map(J=>({...J,meta:Kz(J.name)})),[t]),Y=w.useMemo(()=>{const V=new Set,J=new Set,ie=new Set;return B.forEach(me=>{me.meta.nozzle&&V.add(me.meta.nozzle),me.meta.filamentType&&J.add(me.meta.filamentType),me.meta.layerHeight&&ie.add(me.meta.layerHeight)}),{printers:i.map(me=>({id:me.id.toString(),name:me.name})),nozzles:Array.from(V).sort((me,pe)=>parseFloat(me)-parseFloat(pe)),filaments:Array.from(J).sort(),layerHeights:Array.from(ie).sort((me,pe)=>parseFloat(me)-parseFloat(pe))}},[B,i]),D=w.useMemo(()=>f==="all"?null:i.find(J=>J.id.toString()===f)?.model||null,[f,i]),j=w.useMemo(()=>B.filter(V=>d==="all"||V.type===d).filter(V=>{if(m==="all")return!0;const J=kw(V.setting_id);return m==="custom"?J:!J}).filter(V=>{if(f==="all"||!D)return!0;const J=V.meta.printer?.toLowerCase()||"",ie=D.toLowerCase();return J.includes(ie)||ie.includes(J)}).filter(V=>v==="all"||V.meta.nozzle===v).filter(V=>g==="all"||V.meta.filamentType===g).filter(V=>k==="all"||V.meta.layerHeight===k).filter(V=>l===""||V.name.toLowerCase().includes(l.toLowerCase())).sort((V,J)=>V.name.localeCompare(J.name)),[B,d,m,f,D,v,g,k,l]),z=V=>{if(ee){const J=le[0]?.setting_id===V.setting_id,ie=le[1]?.setting_id===V.setting_id;if(J)de([le[1],null]);else if(ie)de([le[0],null]);else if(!le[0])de([V,null]);else if(le[1]){if(le[0].type!==V.type)return;de([le[0],V])}else{if(le[0].type!==V.type)return;de([le[0],V])}}else M(V)},W=V=>{if(le[0]?.setting_id===V.setting_id)return 0;if(le[1]?.setting_id===V.setting_id)return 1},q=async V=>{try{const J=await he.getCloudSettingDetail(V.setting_id),ie=V.type==="process"?"print":V.type;I({type:ie,name:V.name,base_id:J.base_id||"GFSA00",setting:J.setting||{}}),M(null)}catch(J){console.error("Failed to fetch preset details for duplication:",J)}},ce=async V=>{try{Ne.removeQueries({queryKey:["cloudSettingDetail",V.setting_id]});const J=await he.getCloudSettingDetail(V.setting_id),ie=V.type==="process"?"print":V.type;L({type:ie,name:V.name,base_id:J.base_id||"GFSA00",setting:J.setting||{},setting_id:V.setting_id}),M(null)}catch(J){console.error("Failed to fetch preset details for editing:",J)}},O=()=>{u("all"),p("all"),y("all"),b("all"),_("all"),P("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||k!=="all"||l!=="",X=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:V=>c(V.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"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(Ie,{variant:ee?"primary":"secondary",onClick:()=>{ee?(ue(!1),de([null,null])):ue(!0)},children:[a.jsx(tx,{className:"w-4 h-4"}),o(ee?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(wx,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Ie,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(vr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Ie,{onClick:()=>A(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(kP,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(Lb,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:X},{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:V=>u(V)}),a.jsx(Lb,{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:V=>p(V)}),Y.printers.length>0&&a.jsx(Lb,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.printers.map(V=>({value:V.id,label:V.name}))],onChange:y}),Y.nozzles.length>0&&a.jsx(Lb,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.nozzles.map(V=>({value:V,label:V}))],onChange:b}),Y.filaments.length>0&&(d==="all"||d==="filament")&&a.jsx(Lb,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.filaments.map(V=>({value:V,label:V}))],onChange:_}),Y.layerHeights.length>0&&(d==="all"||d==="process")&&a.jsx(Lb,{label:o("profiles.cloudView.filters.layer"),value:k,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.layerHeights.map(V=>({value:V,label:V}))],onChange:P}),G&&a.jsx("button",{onClick:O,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),ee&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(tx,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:le[0]?o("profiles.cloudView.selectAnotherPreset",{type:le[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[0]?le[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(O3,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[1]?le[1].name:o("profiles.cloudView.selectSecond")})]}),le[0]&&le[1]&&a.jsxs(Ie,{size:"sm",onClick:async()=>{try{const[V,J]=await Promise.all([he.getCloudSettingDetail(le[0].setting_id),he.getCloudSettingDetail(le[1].setting_id)]);be([V.setting||{},J.setting||{}]),te(!0)}catch{}},children:[a.jsx(tx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Sx(e.toISOString(),"system",o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:X})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(ea,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&a.jsx("button",{onClick:O,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(SP,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="filament").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Nd,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="process").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Pr,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="printer").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&a.jsx(Qtt,{setting:N,onClose:()=>M(null),onDeleted:()=>M(null),onDuplicate:()=>q(N),onEdit:()=>ce(N),hasPermission:s,t:o}),(T||$||Q||re)&&a.jsx(Jtt,{onClose:()=>{A(!1),I(null),L(null),ae(null)},initialData:Q||$||(re?{type:re.type,name:"",base_id:"",setting:re.setting}:void 0),allPresets:t,t:o}),C&&a.jsx(Ztt,{onClose:()=>F(!1),onApply:V=>{ae({type:V.type,setting:V.settings}),F(!1)},t:o}),K&&se&&le[0]&&le[1]&&a.jsx(ple,{onClose:()=>{te(!1),be(null)},leftPreset:se[0],rightPreset:se[1],leftLabel:le[0].name,rightLabel:le[1].name,t:o})]})}function tnt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=Sr(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:d}=et({queryKey:["cloudStatus"],queryFn:he.getCloudStatus}),{data:u=[]}=et({queryKey:["printers"],queryFn:he.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=et({queryKey:["cloudSettings"],queryFn:()=>he.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=lt({mutationFn:he.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.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:[a.jsx(Jx,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.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:[a.jsx(ty,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.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:[a.jsx(Aw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email})]})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(B3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.jsx(ent,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(Ie,{onClick:()=>f(),children:t("profiles.retry")})]}):a.jsx(Ytt,{onSuccess:b,t})]}),i==="local"&&a.jsx(Ktt,{}),i==="kprofiles"&&a.jsx($tt,{}),a.jsx(Xtt,{})]})}const r0={Droplet:SP,Flame:Qp,Ruler:bbe,Sparkles:wx,Square:eo,Cable:cO,Wrench:zf,Calendar:Wr,Timer:Pc,Cog:rfe,Fan:hQ,Zap:Xl,Wind:PQ,Thermometer:PP,Layers:ea,Box:si,Target:_Q,RefreshCw:vr,Settings:Ow,Filter:kP,CircleDot:Ipe};function A0(t){return t&&r0[t]||zf}function Ob(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} 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 r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function u3(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function nnt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S");switch(t){case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"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 r||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":m?"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 r?"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":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||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 r||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}}function rnt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=A0(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:Ob(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ob(f,"days",i)}):i("maintenance.timeLeft",{duration:Ob(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Ob(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ob(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Ob(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.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:[a.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.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`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(Wr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||nnt(t.maintenance_type_name,t.printer_model);return f?a.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:y=>y.stopPropagation(),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&a.jsx(Ln,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(rr,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Kr,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(Vn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),a.jsxs(Ie,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(jo,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function ant({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.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)),y=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(r(t.printer_id,v),d(!1))};return a.jsxs(Dt,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.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:[a.jsx(Ln,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.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:[a.jsx(rr,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.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:[a.jsx(Kr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.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?a.jsx(Yl,{className:"w-4 h-4"}):a.jsx(Fn,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(Pc,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),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}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(Ie,{size:"sm",onClick:y,children:s("common.save")}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):a.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:[a.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"),a.jsx(Of,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=A0(f.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),a.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&&a.jsx(Rt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>a.jsx(rnt,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function int({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,k]=w.useState(!1),[P,N]=w.useState(""),[M,T]=w.useState("100"),[A,C]=w.useState("hours"),[F,$]=w.useState("Wrench"),[I,Q]=w.useState(""),[L,re]=w.useState(new Set),[ae,ee]=w.useState(null),[ue,le]=w.useState(null),de=w.useMemo(()=>t?t.map(U=>({id:U.printer_id,name:U.printer_name})):[],[t]),K=U=>t?t.filter(R=>R.maintenance_items.some(ne=>ne.maintenance_type_id===U)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ne=>ne.maintenance_type_id===U)?.id})):[],te=U=>{if(!t)return[];const R=new Set(K(U).map(ne=>ne.printerId));return de.filter(ne=>!R.has(ne.id))},[se,be]=w.useState(null),[Ne,B]=w.useState(""),[Y,D]=w.useState(""),[j,z]=w.useState("hours"),[W,q]=w.useState("Wrench"),[ce,O]=w.useState(""),G=U=>{be(U),B(U.name),D(U.default_interval_hours.toString()),z(U.interval_type||"hours"),q(U.icon||"Wrench"),O(U.wiki_url||"")},X=()=>{se&&Ne.trim()&&parseFloat(Y)>0&&(i(se.id,{name:Ne.trim(),default_interval_hours:parseFloat(Y),interval_type:j,icon:W,wiki_url:ce.trim()||null}),be(null))},V=(U,R,ne)=>{const xe=parseFloat(y);if(!isNaN(xe)&&xe>0){const Se=Math.abs(xe-R)<.01?null:xe;n(U,{custom_interval_hours:Se,custom_interval_type:b!==ne?b:null})}f(null)},J=U=>{U.preventDefault(),P.trim()&&parseFloat(M)>0&&L.size>0&&(r({name:P.trim(),default_interval_hours:parseFloat(M),interval_type:A,icon:F,wiki_url:I.trim()||null},Array.from(L)),N(""),T("100"),C("hours"),Q(""),re(new Set),k(!1))},ie=U=>{re(R=>{const ne=new Set(R);return ne.has(U)?ne.delete(U):ne.add(U),ne})},me=t?.map(U=>({printerId:U.printer_id,printerName:U.printer_name,items:U.maintenance_items.sort((R,ne)=>R.maintenance_type_id-ne.maintenance_type_id)})).sort((U,R)=>U.printerName.localeCompare(R.printerName))||[],pe=e.filter(U=>U.is_system),oe=e.filter(U=>!U.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),a.jsxs(Ie,{onClick:()=>k(!_),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[a.jsx(ur,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&a.jsx(Dt,{className:"mb-6",children:a.jsx(Rt,{className:"py-4",children:a.jsxs("form",{onSubmit:J,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),a.jsx("input",{type:"text",value:P,onChange:U=>N(U.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),a.jsxs("select",{value:A,onChange:U=>{C(U.target.value),U.target.value==="days"?T("30"):T("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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:A==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),a.jsx("input",{type:"number",value:M,onChange:U=>T(U.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"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(r0).map(U=>{const R=r0[U];return a.jsx("button",{type:"button",onClick:()=>$(U),className:`p-2 rounded-lg transition-colors ${F===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(R,{className:"w-4 h-4"})},U)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:I,onChange:U=>Q(U.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/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:de.map(U=>a.jsx("button",{type:"button",onClick:()=>ie(U.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(U.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:U.name},U.id))}),L.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:()=>{k(!1),re(new Set)},children:m("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!P.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[pe.map(U=>{const R=A0(U.icon),ne=U.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:U.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(U.default_interval_hours,ne,m)]})]}),a.jsx("button",{onClick:()=>{u("maintenance:delete")&&le(U)},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:a.jsx(un,{className:"w-4 h-4"})})]})},U.id)}),oe.map(U=>{const R=A0(U.icon),ne=U.interval_type||"hours";if(se?.id===U.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:Ne,onChange:fe=>B(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",placeholder:m("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:j,onChange:fe=>z(fe.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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:Y,onChange:fe=>D(fe.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"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(r0).map(fe=>{const ke=r0[fe];return a.jsx("button",{type:"button",onClick:()=>q(fe),className:`p-1.5 rounded transition-colors ${W===fe?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(ke,{className:"w-3.5 h-3.5"})},fe)})}),a.jsx("input",{type:"url",value:ce,onChange:fe=>O(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",placeholder:m("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{size:"sm",onClick:X,disabled:!Ne.trim(),children:m("common.save")}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>be(null),children:m("common.cancel")})]})]})},U.id);const Se=K(U.id),ye=te(U.id),ve=ae===U.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:U.name}),a.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")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(U.default_interval_hours,ne,m)]})]}),a.jsxs("button",{onClick:()=>ee(ve?null:U.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${Se.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:Se.length}),children:[a.jsx(Pr,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:Se.length}),a.jsx(Fn,{className:`w-3 h-3 transition-transform ${ve?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>G(U),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:a.jsx(Of,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:U.name}))&&s(U.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:a.jsx(un,{className:"w-4 h-4"})})]}),ve&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),Se.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:Se.map(fe=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[fe.printerName,a.jsx("button",{onClick:()=>fe.itemId&&d(fe.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:"×"})]},fe.printerId))}),ye.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ye.map(fe=>a.jsxs("button",{onClick:()=>c(fe.id,U.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:["+ ",fe.name]},fe.id))]})]})]},U.id)})]})]}),me.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:me.map(U=>a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:U.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:U.items.map(R=>{const ne=A0(R.maintenance_type_icon),xe=e.find(ke=>ke.id===R.maintenance_type_id),Se=xe?.default_interval_hours||R.interval_hours,ye=xe?.interval_type||"hours",ve=R.interval_type||"hours",fe=p===R.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(ne,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),fe?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(Wr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(Pc,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:ke=>g(ke.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:y,onChange:ke=>v(ke.target.value),onKeyDown:ke=>{ke.key==="Enter"&&V(R.id,Se,ye),ke.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"}),a.jsx(Ie,{size:"sm",onClick:()=>V(R.id,Se,ye),children:"OK"})]}):a.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),v(R.interval_hours.toString()),g(ve))},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:[ve==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(R.interval_hours,ve,m),a.jsx(Of,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},U.printerId))})]}),me.length===0&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-12",children:[a.jsx(rr,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ue&&a.jsx(kn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ue.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(ue.id),le(null)},onCancel:()=>le(null)})]})}function snt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=Sr(),[i,s]=w.useState("status"),{data:o,isLoading:l}=et({queryKey:["maintenanceOverview"],queryFn:he.getMaintenanceOverview}),{data:c}=et({queryKey:["maintenanceTypes"],queryFn:he.getMaintenanceTypes}),d=lt({mutationFn:({id:M,notes:T})=>he.performMaintenance(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),u=lt({mutationFn:({id:M,data:T})=>he.updateMaintenanceItem(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),m=lt({mutationFn:({id:M,data:T})=>he.updateMaintenanceType(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),p=lt({mutationFn:he.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),f=lt({mutationFn:he.restoreDefaultMaintenanceTypes,onSuccess:M=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:M.restored}))},onError:M=>{n(M.message,"error")}}),y=lt({mutationFn:({printerId:M,hours:T})=>he.setPrinterHours(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),v=lt({mutationFn:({printerId:M,typeId:T})=>he.assignMaintenanceType(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),b=lt({mutationFn:he.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),g=M=>{d.mutate({id:M})},_=(M,T)=>{u.mutate({id:M,data:{enabled:T}})},k=(M,T)=>{y.mutate({printerId:M,hours:T})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((M,T)=>M+T.due_count,0)||0,N=o?.reduce((M,T)=>M+T.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[P>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.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")}),a.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"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((M,T)=>{const A=M.due_count*10+M.warning_count,C=T.due_count*10+T.warning_count;return A!==C?C-A:M.printer_name.localeCompare(T.printer_name)}).map(M=>a.jsx(ant,{overview:M,onPerform:g,onToggle:_,onSetHours:k,hasPermission:r,t},M.printer_id)):a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-16",children:[a.jsx(zf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx(int,{overview:o,types:c||[],onUpdateInterval:(M,T)=>u.mutate({id:M,data:T}),onAddType:async(M,T)=>{const A=await he.createMaintenanceType(M);for(const C of T)await he.assignMaintenanceType(C,A.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,T)=>m.mutate({id:M,data:T}),onDeleteType:M=>p.mutate(M),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(M,T)=>v.mutate({printerId:M,typeId:T}),onRemoveItem:M=>b.mutate(M),hasPermission:r,t})]})}const tX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function fle({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:i,t:s}){const[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.description||""),[u,m]=w.useState(t?.color||tX[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,k]=w.useState(t?.tags||""),[P,N]=w.useState(t?.due_date?.split("T")[0]||""),[M,T]=w.useState(t?.priority||"normal"),[A,C]=w.useState(t?.budget?.toString()||""),F=$=>{$.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:P||void 0,priority:M,budget:A.trim()?parseFloat(A):null,...t&&{status:b}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:F,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:$=>l($.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),a.jsx("textarea",{value:c,onChange:$=>d($.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:tX.map($=>a.jsx("button",{type:"button",onClick:()=>m($),className:`w-8 h-8 rounded-full transition-transform ${u===$?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:$}},$))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),a.jsx("input",{type:"number",value:p,onChange:$=>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:s("projects.targetPlatesPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),a.jsx("input",{type:"number",value:y,onChange:$=>v($.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),a.jsx("input",{type:"text",value:_,onChange:$=>k($.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")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),a.jsx("input",{type:"date",value:P,onChange:$=>N($.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),a.jsxs("select",{value:M,onChange:$=>T($.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:[a.jsx("option",{value:"low",children:s("projects.priorityLow")}),a.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),a.jsx("option",{value:"high",children:s("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:A,onChange:$=>C($.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&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),a.jsxs("select",{value:b,onChange:$=>g($.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:[a.jsx("option",{value:"active",children:s("projects.statusActive")}),a.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!o.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function ont({project:t,onClick:e,onEdit:n,onDelete:r,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]=w.useState(!1),f=c?{icon:Cc,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:Qs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:rr,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:js,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.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:[a.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`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:a.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.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?a.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?a.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&&a.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&&a.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&&a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(k=>k.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(k=>k.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[a.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:a.jsx(Ah,{className:"w-4 h-4"})}),u&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),a.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:[a.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")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4"}),s("common.edit")]}),a.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")&&(r(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(un,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(Qs,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?a.jsx("img",{src:he.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(Na,{className:"w-6 h-6"})}),y.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Ln,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(ea,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(Na,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(U3,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(Va,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function lnt(){const{t}=Lt(),e=Eo(),n=mn(),{showToast:r}=xn(),{hasPermission:i}=Sr(),[s,o]=w.useState(!1),[l,c]=w.useState(),[d,u]=w.useState("active"),[m,p]=w.useState(null),{data:f}=et({queryKey:["settings"],queryFn:he.getSettings}),y=yo(f?.currency||"USD"),{data:v,isLoading:b}=et({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>he.getProjects(d==="all"?void 0:d)}),g=lt({mutationFn:re=>he.createProject(re),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:re=>{r(re.message,"error")}}),_=lt({mutationFn:({id:re,data:ae})=>he.updateProject(re,ae),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:re=>{r(re.message,"error")}}),k=lt({mutationFn:re=>he.deleteProject(re),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:re=>{p(null),r(re.message,"error")}}),P=lt({mutationFn:re=>he.importProject(re),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:re=>{r(re.message,"error")}}),N=w.useRef(null),M=async()=>{try{const re=await he.getProjects(),ae=await Promise.all(re.map(async de=>await he.exportProjectJson(de.id))),ee=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),ue=URL.createObjectURL(ee),le=document.createElement("a");le.href=ue,le.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,le.click(),URL.revokeObjectURL(ue),r(t("projects.toast.exported"),"success")}catch(re){r(re.message,"error")}},T=()=>{N.current?.click()},A=async re=>{const ae=re.target.files?.[0];if(ae){try{if(ae.name.toLowerCase().endsWith(".zip"))await he.importProjectFile(ae),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const ue=await ae.text(),le=JSON.parse(ue),de=Array.isArray(le)?le:[le];for(const K of de)await P.mutateAsync(K);de.length>1&&r(t("projects.toast.multipleImported",{count:de.length}),"success")}}catch(ee){r(`${t("projects.toast.importFailed")}: ${ee.message}`,"error")}re.target.value=""}},C=re=>{l?_.mutate({id:l.id,data:re}):g.mutate(re)},F=re=>{c(re),o(!0)},$=re=>{e(`/projects/${re.id}`)},I=re=>{p(re)},Q=()=>{m!==null&&k.mutate(m)},L=v?.reduce((re,ae)=>(re[ae.status]=(re[ae.status]||0)+1,re.all=(re.all||0)+1,re),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:A,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(js,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",onClick:T,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(Ca,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Ie,{variant:"secondary",onClick:M,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(va,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Ie,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:rr},{key:"completed",label:t("projects.statusCompleted"),icon:Cc},{key:"archived",label:t("projects.statusArchived"),icon:Qs},{key:"all",label:t("common.all"),icon:js}].map(({key:re,label:ae,icon:ee})=>a.jsxs("button",{onClick:()=>u(re),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===re?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(ee,{className:"w-4 h-4"}),a.jsx("span",{children:ae}),L[re]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===re?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[re]})]},re))}),b?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(js,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),a.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"&&a.jsxs(Ie,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(re=>a.jsx(ont,{project:re,onClick:()=>$(re),onEdit:()=>F(re),onDelete:()=>I(re.id),hasPermission:i,t},re.id))}),m!==null&&a.jsx(kn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:Q,onCancel:()=>p(null)}),s&&a.jsx(fle,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function cnt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function dnt({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function nX({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(Dt,{children:a.jsx(Rt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function unt({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Na,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.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(n=>a.jsxs(vo,{to:`/archives?search=${encodeURIComponent(n.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:[n.thumbnail_path?a.jsx("img",{src:he.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(Na,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx($a,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(fr,{className:"w-4 h-4 text-bambu-green"})}),a.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:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function mnt({priority:t,t:e}){const n={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:r,label:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Ln,{className:"w-3 h-3"}),i]})}function m3(t,e){if(!t)return null;const n=Qn(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.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 hnt(){const{id:t}=Cw(),e=Eo(),{t:n}=Lt(),r=mn(),{showToast:i}=xn(),{hasPermission:s}=Sr(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(""),p=parseInt(t||"0",10),{data:f,isLoading:y,error:v}=et({queryKey:["project",p],queryFn:()=>he.getProject(p),enabled:p>0}),{data:b,isLoading:g}=et({queryKey:["project-archives",p],queryFn:()=>he.getProjectArchives(p),enabled:p>0}),{data:_,isLoading:k}=et({queryKey:["project-bom",p],queryFn:()=>he.getProjectBOM(p),enabled:p>0}),{data:P,isLoading:N}=et({queryKey:["project-timeline",p],queryFn:()=>he.getProjectTimeline(p,20),enabled:p>0}),{data:M}=et({queryKey:["settings"],queryFn:he.getSettings}),{data:T}=et({queryKey:["project-folders",p],queryFn:()=>he.getLibraryFoldersByProject(p),enabled:p>0}),A=yo(M?.currency||"USD"),C=M?.time_format||"system",F=lt({mutationFn:Re=>he.updateProject(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:Re=>{i(Re.message,"error")}}),$=()=>{m(f?.notes||""),d(!0)},I=()=>{F.mutate({notes:u})},Q=()=>{d(!1),m("")},[L,re]=w.useState(""),[ae,ee]=w.useState(1),[ue,le]=w.useState(""),[de,K]=w.useState(""),[te,se]=w.useState(""),[be,Ne]=w.useState(!1),[B,Y]=w.useState(!1),[D,j]=w.useState(null),[z,W]=w.useState(""),[q,ce]=w.useState(1),[O,G]=w.useState(""),[X,V]=w.useState(""),[J,ie]=w.useState(""),[me,pe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),oe=lt({mutationFn:Re=>he.createBOMItem(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),re(""),ee(1),le(""),K(""),se(""),Ne(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:Re=>i(Re.message,"error")}),U=lt({mutationFn:({itemId:Re,data:Ye})=>he.updateBOMItem(p,Re,Ye),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),j(null)},onError:Re=>i(Re.message,"error")}),R=lt({mutationFn:Re=>he.deleteBOMItem(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:Re=>i(Re.message,"error")}),ne=Re=>{Re.preventDefault(),L.trim()&&oe.mutate({name:L.trim(),quantity_needed:ae,unit_price:ue?parseFloat(ue):void 0,sourcing_url:de.trim()||void 0,remarks:te.trim()||void 0})},xe=Re=>{const Ye=Re.is_complete?0:Re.quantity_needed;U.mutate({itemId:Re.id,data:{quantity_acquired:Ye}})},Se=(Re,Ye)=>{pe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ye}),onConfirm:()=>{pe(we=>({...we,isOpen:!1})),R.mutate(Re)}})},ye=Re=>{j(Re),W(Re.name),ce(Re.quantity_needed),G(Re.unit_price?.toString()||""),V(Re.sourcing_url||""),ie(Re.remarks||"")},ve=Re=>{Re.preventDefault(),!(!D||!z.trim())&&U.mutate({itemId:D.id,data:{name:z.trim(),quantity_needed:q,unit_price:O?parseFloat(O):void 0,sourcing_url:X.trim()||void 0,remarks:J.trim()||void 0}})},fe=()=>{j(null)},ke=async()=>{try{const{blob:Re,filename:Ye}=await he.exportProjectZip(Number(p)),we=URL.createObjectURL(Re),$e=document.createElement("a");$e.href=we,$e.download=Ye||`${f?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,$e.click(),URL.revokeObjectURL(we),i(n("projectDetail.toast.projectExported"),"success")}catch(Re){i(Re.message,"error")}},Ee=lt({mutationFn:()=>he.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:Re=>i(Re.message,"error")}),Ae=Re=>Bf(Re,C,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(y)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!f)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),a.jsx(Ie,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const _e=f.stats,je=_e?.progress_percent??0,Be=_e?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(vo,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),a.jsx(Va,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:f.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(uQ,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:f.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:f.name}),f.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:f.description})]})]}),a.jsx(dnt,{status:f.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",onClick:ke,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(va,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Ie,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(f.target_count||f.target_parts_count)&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4 space-y-4",children:[f.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.total_archives||0," / ",f.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(je,100)}%`,backgroundColor:je>=100?"#22c55e":f.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:je.toFixed(0)})}),_e?.remaining_prints!=null&&_e.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_prints})})]})]}),f.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.completed_prints||0," / ",f.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Be,100)}%`,backgroundColor:Be>=100?"#22c55e":f.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Be.toFixed(0)})}),_e?.remaining_parts!=null&&_e.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_parts})})]})]})]})}),_e&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(Dt,{children:a.jsx(Rt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(Na,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[_e.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),_e.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:_e.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:_e.completed_prints})})]})]})})}),a.jsx(nX,{icon:rr,label:n("projectDetail.stats.printTime"),value:Wxe(_e.total_print_time_hours),color:"text-yellow-400"}),a.jsx(nX,{icon:Pr,label:n("projectDetail.stats.filamentUsed"),value:cnt(_e.total_filament_grams),color:"text-purple-400"})]}),_e&&(()=>{const Re=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return _e.estimated_cost>0||Re>0||f.budget!==null})()&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[A,_e.estimated_cost.toFixed(2)]})]}),_e.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[_e.total_energy_kwh.toFixed(3)," kWh",_e.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",A,_e.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Re=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return Re<=0?null:a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),a.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[A,Re.toFixed(2)]}),_e.bom_cost>0&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),f.budget!==null&&(()=>{const Re=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost,Ye=f.budget-Re;return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",a.jsxs("span",{className:"text-white font-semibold",children:[A,f.budget.toFixed(2)]})]}),a.jsxs("p",{className:`text-sm ${Ye>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",a.jsxs("span",{className:"font-semibold",children:[A,Ye.toFixed(2)]})]})]})})()]})]})}),f.children&&f.children.length>0&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(Hfe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:f.children.length})]}),a.jsx("div",{className:"space-y-2",children:f.children.map(Re=>a.jsxs(vo,{to:`/projects/${Re.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Re.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:Re.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Re.status==="completed"?"bg-status-ok/20 text-status-ok":Re.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Re.status})]}),Re.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[Re.progress_percent.toFixed(0),"%"]})]},Re.id))})]})}),f.parent_id&&f.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(ea,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(vo,{to:`/projects/${f.parent_id}`,className:"text-bambu-green hover:underline",children:f.parent_name})]}),(f.tags||f.due_date||f.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.priority&&f.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx(mnt,{priority:f.priority,t:n})]}),f.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wr,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:Uf(f.due_date,{year:"numeric",month:"short",day:"numeric"})}),m3(f.due_date,n)&&a.jsxs("span",{className:`text-xs ${m3(f.due_date,n).color}`,children:["(",m3(f.due_date,n).label,")"]})]}),f.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Vu,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:f.tags.split(",").map((Re,Ye)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Re.trim()},Ye))})]})]}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Q,disabled:F.isPending,children:[a.jsx(Bt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Ie,{size:"sm",onClick:I,disabled:F.isPending,children:[F.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(cs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:$,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(FL,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):f.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:Bae.sanitize(f.notes)}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Fc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(vo,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),T&&T.length>0?a.jsx("div",{className:"space-y-2",children:T.map(Re=>a.jsxs(vo,{to:`/files?folder=${Re.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Fc,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:Re.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:Re.file_count})})]})]}),a.jsx(Va,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},Re.id))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(vQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),_e&&_e.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:_e.bom_completed_items,total:_e.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(Re=>Re.is_complete)&&a.jsx("button",{onClick:()=>Y(!B),className:`text-xs px-2 py-1 rounded transition-colors ${B?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(B?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!be&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Ne(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),be&&a.jsxs("form",{onSubmit:ne,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:L,onChange:Re=>re(Re.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:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:ae,onChange:Re=>ee(parseInt(Re.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:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:ue,onChange:Re=>le(Re.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:n("projectDetail.bom.price",{currency:A})})]})]}),a.jsx("input",{type:"url",value:de,onChange:Re=>K(Re.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:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:te,onChange:Re=>se(Re.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:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:()=>Ne(!1),children:n("common.cancel")}),a.jsx(Ie,{type:"submit",size:"sm",disabled:!L.trim()||oe.isPending,children:oe.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),k?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?a.jsxs("div",{className:"space-y-2",children:[_.filter(Re=>!B||!Re.is_complete).map(Re=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${Re.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:D?.id===Re.id?a.jsxs("form",{onSubmit:ve,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:z,onChange:Ye=>W(Ye.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:n("projectDetail.bom.partName"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:q,onChange:Ye=>ce(parseInt(Ye.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:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:O,onChange:Ye=>G(Ye.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:n("projectDetail.bom.price",{currency:A})})]})]}),a.jsx("input",{type:"url",value:X,onChange:Ye=>V(Ye.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:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:J,onChange:Ye=>ie(Ye.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:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:fe,children:n("common.cancel")}),a.jsx(Ie,{type:"submit",size:"sm",disabled:!z.trim()||U.isPending,children:U.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&xe(Re),disabled:U.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${Re.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:Re.is_complete&&a.jsx(fr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${Re.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Re.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Re.quantity_needed]})]}),Re.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[A,(Re.unit_price*Re.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&ye(Re),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-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")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&Se(Re.id,Re.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-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")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:a.jsx(un,{className:"w-4 h-4"})})]})]}),Re.sourcing_url&&a.jsxs("a",{href:Re.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:Ye=>Ye.stopPropagation(),children:[a.jsx(sa,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Re.sourcing_url).hostname.replace("www.","")}catch{return Re.sourcing_url}})()})]}),Re.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Re.remarks})]})]})},Re.id)),_e&&_e.bom_cost>0&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[A,_e.bom_cost.toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(L0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),N?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):P&&P.length>0?a.jsx("div",{className:"space-y-3",children:P.slice(0,10).map((Re,Ye)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${Re.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Re.event_type==="print_failed"?"bg-status-error/20 text-status-error":Re.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Re.event_type==="print_completed"&&a.jsx(fr,{className:"w-4 h-4"}),Re.event_type==="print_failed"&&a.jsx($a,{className:"w-4 h-4"}),Re.event_type==="print_started"&&a.jsx(Pr,{className:"w-4 h-4"}),Re.event_type==="queued"&&a.jsx(U3,{className:"w-4 h-4"}),Re.event_type==="project_created"&&a.jsx(ur,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:Re.title}),Re.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Re.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:Ae(Re.timestamp)})]})]},Ye))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!f.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Ee.mutate(),disabled:Ee.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Ee.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Mo,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),_e&&(_e.queued_prints>0||_e.in_progress_prints>0)&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(U3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(vo,{to:`/queue?project=${p}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[_e.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:_e.in_progress_prints})}),_e.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:_e.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Na,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),g?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(unt,{archives:b||[],t:n})]}),o&&a.jsx(fle,{t:n,currencySymbol:A,project:{...f,archive_count:_e?.total_archives||0,total_items:_e?.total_items||0,completed_count:_e?.completed_prints||0,failed_count:_e?.failed_prints||0,queue_count:_e?.queued_prints||0,progress_percent:_e?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Re=>F.mutate(Re),isLoading:F.isPending}),me.isOpen&&a.jsx(kn,{title:me.title,message:me.message,confirmText:n("common.delete"),variant:"danger",onConfirm:me.onConfirm,onCancel:()=>pe(Re=>({...Re,isOpen:!1}))})]})}function pnt({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.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})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function fnt({onClose:t,onSave:e,isLoading:n,t:r}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!0),[u,m]=w.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(tN,{className:"w-5 h-5 text-bambu-green"}),r("fileManager.linkExternalFolder")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.linkExternalFolderDescription")})]}),a.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.folderName")}),a.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:r("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.externalPath")}),a.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}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("fileManager.externalPathHelp")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.readOnly")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",r("fileManager.readOnlyHelp"),")"]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.showHiddenFiles")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:t,children:r("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):r("fileManager.linkFolder")})]})]})]})})}function gnt({type:t,currentName:e,onClose:n,onSave:r,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]=w.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[a.jsx("input",{type:"text",value:c,onChange:m=>d(m.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&&a.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function bnt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),d=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...d(y.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>a.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,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===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[a.jsx(Fc,{className:"w-4 h-4"}),m.name,m.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Ie,{onClick:()=>i(l),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function xnt({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:d}=et({queryKey:["projects"],queryFn:()=>he.getProjects()}),{data:u}=et({queryKey:["archives-for-link"],queryFn:()=>he.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ru,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.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:[a.jsx(mQ,{className:"w-4 h-4"}),i("fileManager.project")]}),a.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:[a.jsx(Qs,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.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(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:y.name})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(yf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&a.jsxs(Ie,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(qh,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ie,{onClick:m,disabled:!l||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function gle({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:d}){const[u,m]=w.useState(!0),[p,f]=w.useState(!1),y=t.children.length>0,v=t.project_id||t.archive_id,b=t.is_external;return a.jsxs("div",{children:[a.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:()=>n(t.id),children:[y?a.jsx("button",{onClick:g=>{g.stopPropagation(),m(!u)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Va,{className:`w-3.5 h-3.5 transition-transform ${u?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),b?a.jsx(tN,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):a.jsx(Fc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&a.jsxs("button",{onClick:g=>{g.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:[a.jsx(Ru,{className:"w-3 h-3"}),t.project_name?a.jsx(mQ,{className:"w-3 h-3"}):a.jsx(Qs,{className:"w-3 h-3"})]}),b&&t.external_readonly&&a.jsx("span",{title:d("fileManager.readOnly"),children:a.jsx(ld,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&!b&&a.jsx("button",{onClick:g=>{g.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:d("fileManager.linkToProjectOrArchive"),children:a.jsx(Ru,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:g=>g.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),a.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:[a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionRenameFolder"),children:[a.jsx(Za,{className:"w-3.5 h-3.5"}),d("common.rename")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(i(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionLinkFolder"),children:[a.jsx(Ru,{className:"w-3.5 h-3.5"}),d(v?"fileManager.changeLink":"fileManager.linkTo")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:d("fileManager.noPermissionDeleteFolder"),children:[a.jsx(un,{className:"w-3.5 h-3.5"}),d("common.delete")]})]})]})]})})]}),y&&u&&a.jsx("div",{children:t.children.map(g=>a.jsx(gle,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:d},g.id))})]})}function HL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function ynt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:d,onGenerateThumbnail:u,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return a.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:()=>r(t.id),children:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${he.getLibraryFileThumbnailUrl(t.id)}${m?(he.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(yf,{className:"w-12 h-12 text-bambu-gray/30"}),a.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"?"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()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:_o(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),ls(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Pr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Gu,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[a.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.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&&HL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Pr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&HL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(si,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(va,{className:"w-3.5 h-3.5"}),v("common.download")]}),d&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx(Za,{className:"w-3.5 h-3.5"}),v("common.rename")]}),u&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx($u,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(i(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(un,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.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 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function vnt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Sr(),[l]=eO(),c=l.get("folder"),d=c?parseInt(c,10):null,[u,m]=w.useState(d),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(!1),[M,T]=w.useState(null),[A,C]=w.useState(null),[F,$]=w.useState(null),[I,Q]=w.useState(null),[L,re]=w.useState(null),[ae,ee]=w.useState(null),[ue,le]=w.useState({}),[de,K]=w.useState(null),[te,se]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[be,Ne]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[B,Y]=w.useState(()=>{const We=localStorage.getItem("library-sidebar-width");return We?parseInt(We,10):256}),[D,j]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{if(!D)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const We=Nt=>{if(!z.current)return;const ht=z.current.parentElement?.getBoundingClientRect();if(!ht)return;const Mt=Nt.clientX-ht.left,Qt=Math.min(500,Math.max(200,Mt));Y(Qt)},Ft=()=>{j(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(B))};return document.addEventListener("mousemove",We),document.addEventListener("mouseup",Ft),()=>{document.removeEventListener("mousemove",We),document.removeEventListener("mouseup",Ft),document.body.style.userSelect="",document.body.style.cursor=""}},[D,B]);const[W,q]=w.useState(""),[ce,O]=w.useState("all"),[G,X]=w.useState(""),[V,J]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[ie,me]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),pe=Eae();w.useEffect(()=>{const We=l.get("folder");if(We){const Ft=parseInt(We,10);m(Ft)}},[l]);const{data:oe}=et({queryKey:["settings"],queryFn:()=>he.getSettings()}),{data:U,isLoading:R}=et({queryKey:["library-folders"],queryFn:()=>he.getLibraryFolders()}),{data:ne,isLoading:xe}=et({queryKey:["library-files",u],queryFn:()=>he.getLibraryFiles(u,u===null)}),{data:Se}=et({queryKey:["library-stats"],queryFn:()=>he.getLibraryStats()}),{data:ye}=et({queryKey:["users"],queryFn:()=>he.getUsers()}),ve=w.useMemo(()=>{if(!ne)return[];const We=new Set(ne.map(Ft=>Ft.file_type));return Array.from(We).sort()},[ne]),fe=w.useMemo(()=>{if(!ne)return[];let We=[...ne];if(W.trim()){const Ft=W.toLowerCase();We=We.filter(Nt=>Nt.filename.toLowerCase().includes(Ft)||Nt.print_name&&Nt.print_name.toLowerCase().includes(Ft))}if(ce!=="all"&&(We=We.filter(Ft=>Ft.file_type===ce)),G.trim()){const Ft=G.toLowerCase();We=We.filter(Nt=>Nt.created_by_username&&Nt.created_by_username.toLowerCase().includes(Ft))}return We.sort((Ft,Nt)=>{let ht=0;switch(V){case"name":ht=(Ft.print_name||Ft.filename).localeCompare(Nt.print_name||Nt.filename);break;case"date":ht=(Qn(Ft.created_at)?.getTime()??0)-(Qn(Nt.created_at)?.getTime()??0);break;case"size":ht=Ft.file_size-Nt.file_size;break;case"type":ht=Ft.file_type.localeCompare(Nt.file_type);break;case"prints":ht=Ft.print_count-Nt.print_count;break}return ie==="asc"?ht:-ht}),We},[ne,W,ce,G,V,ie]),ke=w.useMemo(()=>{if(!Se||!oe)return!1;const We=(oe.library_disk_warning_gb||5)*1024*1024*1024;return Se.disk_free_byteshe.createLibraryFolder(We),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:We=>n(We.message,"error")}),Ae=lt({mutationFn:async We=>{const Ft=await he.createExternalFolder(We);return await he.scanExternalFolder(Ft.id),Ft},onSuccess:We=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),g(!1),m(We.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:We=>n(We.message,"error")}),_e=lt({mutationFn:We=>he.scanExternalFolder(We),onSuccess:We=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:We.added,removed:We.removed}),"success")},onError:We=>n(We.message,"error")}),je=lt({mutationFn:We=>he.deleteLibraryFolder(We),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),u===A?.id&&m(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:We=>{C(null),n(We.message,"error")}}),Be=lt({mutationFn:We=>he.deleteLibraryFile(We),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(We=>We.filter(Ft=>Ft!==A?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:We=>{C(null),n(We.message,"error")}}),Re=lt({mutationFn:We=>he.bulkDeleteLibrary(We,[]),onSuccess:(We,Ft)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:Ft.length}),"success"),f([]),C(null)},onError:We=>{C(null),n(We.message,"error")}}),Ye=lt({mutationFn:({fileIds:We,folderId:Ft})=>he.moveLibraryFiles(We,Ft),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),k(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:We=>n(We.message,"error")}),we=lt({mutationFn:({id:We,data:Ft})=>he.updateLibraryFolder(We,Ft),onSuccess:(We,Ft)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),T(null);const Nt=Ft.data.project_id===0&&Ft.data.archive_id===0;n(t(Nt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:We=>n(We.message,"error")}),$e=lt({mutationFn:({id:We,filename:Ft})=>he.updateLibraryFile(We,{filename:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:We=>{ee(null),n(We.message,"error")}}),De=lt({mutationFn:({id:We,name:Ft})=>he.updateLibraryFolder(We,{name:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:We=>{ee(null),n(We.message,"error")}}),Xe=lt({mutationFn:()=>he.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:We=>{if(e.invalidateQueries({queryKey:["library-files"]}),We.succeeded>0){const Ft=Date.now(),Nt={};We.results.forEach(ht=>{ht.success&&(Nt[ht.file_id]=Ft)}),le(ht=>({...ht,...Nt}))}We.succeeded>0&&We.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:We.succeeded}),"success"):We.succeeded>0&&We.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:We.succeeded,failed:We.failed}),"success"):We.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:We.results[0]?.error||"Unknown error"}),"error")},onError:We=>n(We.message,"error")}),Ve=lt({mutationFn:We=>he.batchGenerateStlThumbnails({file_ids:[We]}),onSuccess:We=>{if(e.invalidateQueries({queryKey:["library-files"]}),We.succeeded>0){const Ft=We.results[0]?.file_id;Ft&&le(Nt=>({...Nt,[Ft]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:We.results[0]?.error||"Unknown error"}),"error")},onError:We=>n(We.message,"error")}),Te=w.useCallback(We=>{const Ft=We.toLowerCase();return Ft.endsWith(".gcode")||Ft.includes(".gcode.")},[]),Me=w.useMemo(()=>ne?ne.filter(We=>p.includes(We.id)&&Te(We.filename)):[],[ne,p,Te]),qe=w.useCallback(We=>{f(Ft=>Ft.includes(We)?Ft.filter(Nt=>Nt!==We):[...Ft,We])},[]),tt=w.useCallback(()=>{fe.length>0&&f(fe.map(We=>We.id))},[fe]),ut=w.useCallback(()=>{f([])},[]),xt=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},wt=We=>{he.downloadLibraryFile(We).catch(Ft=>{console.error("Library file download failed:",Ft)})},Ht=()=>{A&&(A.type==="file"?Be.mutate(A.id):A.type==="folder"?je.mutate(A.id):A.type==="bulk"&&Re.mutate(p))},Xt=je.isPending||Be.isPending||Re.isPending,Kt=We=>{se(We),localStorage.setItem("library-view-mode",We)},Ut=R||xe,en=w.useMemo(()=>{if(!u||!U)return null;const We=Ft=>{for(const Nt of Ft){if(Nt.id===u)return Nt;const ht=We(Nt.children);if(ht)return ht}return null};return We(U)},[u,U]);return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Fc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>Kt("grid"),className:`p-1.5 rounded transition-colors ${te==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(jw,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Kt("list"),className:`p-1.5 rounded transition-colors ${te==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(Ew,{className:"w-4 h-4"})})]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>Xe.mutate(),disabled:Xe.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Xe.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx($u,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>g(!0),disabled:!r("library:upload"),title:r("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[a.jsx(tN,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(zfe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(Ca,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ke&&Se&&oe&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Ln,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:_o(Se.disk_free_bytes),total:_o(Se.disk_total_bytes),threshold:oe.library_disk_warning_gb})})]})]}),Se&&a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(_P,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Se.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Fc,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Se.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(ty,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:_o(Se.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${ke?"text-amber-500":"text-white"}`,children:_o(Se.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:u??"",onChange:We=>m(We.target.value?parseInt(We.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:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),U&&(()=>{const We=(Ft,Nt=0)=>{const ht=[];for(const Mt of Ft)ht.push({id:Mt.id,name:Mt.name,fileCount:Mt.file_count,depth:Nt}),Mt.children.length>0&&ht.push(...We(Mt.children,Nt+1));return ht};return We(U).map(Ft=>a.jsxs("option",{value:Ft.id,children:["│ ".repeat(Ft.depth),"📂 ",Ft.name," ",Ft.fileCount>0?`(${Ft.fileCount})`:""]},Ft.id))})()]})}),a.jsxs("div",{ref:z,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:`${B}px`},children:[a.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 ${D?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:We=>{We.preventDefault(),j(!0)},onDoubleClick:()=>{Y(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${D?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsx("button",{onClick:()=>{const We=!be;Ne(We),localStorage.setItem("library-wrap-folders",String(We))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${be?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(be?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${u===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[a.jsx(yf,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),U?.map(We=>a.jsx(gle,{folder:We,selectedFolderId:u,onSelect:m,onDelete:Ft=>C({type:"folder",id:Ft}),onLink:T,onRename:Ft=>ee({type:"folder",id:Ft.id,name:Ft.name}),wrapNames:be,hasPermission:r,t},We.id))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[en?.is_external&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[a.jsx(tN,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),en.external_readonly&&a.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:[a.jsx(ld,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:en.external_path||"",children:en.external_path})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>u&&_e.mutate(u),disabled:_e.isPending,title:t("fileManager.scanFolder"),children:[_e.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),a.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),ne&&ne.length>0&&a.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:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:W,onChange:We=>q(We.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"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kP,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:ce,onChange:We=>O(We.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:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),ve.map(We=>a.jsx("option",{value:We,children:We.toUpperCase()},We))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:G,onChange:We=>X(We.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 ${G?"pr-7":""}`,style:G?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),G&&a.jsx("button",{onClick:()=>X(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Bt,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ye?.map(We=>a.jsx("option",{value:We.username},We.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:V,onChange:We=>{const Ft=We.target.value;J(Ft),localStorage.setItem("library-sort-field",Ft)},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:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>me(We=>{const Ft=We==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ft),Ft}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(ie==="asc"?"fileManager.ascending":"fileManager.descending"),children:ie==="asc"?a.jsx(Jhe,{className:"w-4 h-4 text-white"}):a.jsx(Ghe,{className:"w-4 h-4 text-white"})})]}),(W||ce!=="all"||G)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:fe.length,total:ne.length})})]}),fe.length>0&&a.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:[p.length===fe.length&&p.length>0?a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(eo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:tt,children:[a.jsx(us,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Me.length===1&&a.jsxs(Ie,{variant:"primary",size:"sm",onClick:()=>Q(Me[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(Ds,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Me.length===1&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>re(Me[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(rr,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>k(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[a.jsx(Yge,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Ie,{variant:"danger",size:"sm",onClick:()=>{p.length===1?C({type:"file",id:p[0]}):C({type:"bulk",id:0,count:p.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(un,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(Bt,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Ut?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):ne?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(yf,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(u!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(u!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):fe.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Cr,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(Ie,{variant:"secondary",onClick:()=>{q(""),O("all")},children:t("fileManager.clearFilters")})]}):te==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.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:fe.map(We=>a.jsx(ynt,{file:We,isSelected:p.includes(We.id),isMobile:pe,t,onSelect:qe,onDelete:Ft=>C({type:"file",id:Ft}),onDownload:wt,onAddToQueue:Ft=>{const Nt=ne?.find(ht=>ht.id===Ft);Nt&&re(Nt)},onPrint:$,onPreview3d:K,onRename:Ft=>ee({type:"file",id:Ft.id,name:Ft.filename}),onGenerateThumbnail:Ft=>Ve.mutate(Ft.id),thumbnailVersion:ue[We.id],hasPermission:r,canModify:s,authEnabled:o},We.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),fe.map(We=>a.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} 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 ${p.includes(We.id)?"bg-bambu-green/10":""}`,onClick:()=>qe(We.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(We.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(We.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:We.thumbnail_path?a.jsx("img",{src:`${he.getLibraryFileThumbnailUrl(We.id)}${ue[We.id]?(he.getLibraryFileThumbnailUrl(We.id).includes("?")?"&":"?")+`v=${ue[We.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(yf,{className:"w-5 h-5 text-bambu-gray/50"})})}),We.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${he.getLibraryFileThumbnailUrl(We.id)}${ue[We.id]?(he.getLibraryFileThumbnailUrl(We.id).includes("?")?"&":"?")+`v=${ue[We.id]}`:""}`,alt:We.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:We.print_name||We.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:We.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(Gu,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:We.created_by_username})]}):"-"}),a.jsx("div",{children:a.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":We.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:We.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:_o(We.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:We.print_count>0?`${We.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:Ft=>Ft.stopPropagation(),children:[HL(We.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&$(We),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:a.jsx(Pr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&re(We)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:a.jsx(rr,{className:"w-4 h-4"})})]}),(We.file_type==="3mf"||We.file_type==="gcode"||We.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&K(We),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:a.jsx(si,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&wt(We.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:a.jsx(va,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",We.created_by_id)&&ee({type:"file",id:We.id,name:We.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",We.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",We.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",We.created_by_id),children:a.jsx(Za,{className:"w-4 h-4"})}),We.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",We.created_by_id)&&Ve.mutate(We.id),className:`p-1.5 rounded transition-colors ${s("library","update",We.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",We.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Ve.isPending||!s("library","update",We.created_by_id),children:a.jsx($u,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",We.created_by_id)&&C({type:"file",id:We.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",We.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",We.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",We.created_by_id),children:a.jsx(un,{className:"w-4 h-4"})})]})]},We.id))]})})]})]}),y&&a.jsx(pnt,{parentId:u,onClose:()=>v(!1),onSave:We=>Ee.mutate(We),isLoading:Ee.isPending,t}),b&&a.jsx(fnt,{onClose:()=>g(!1),onSave:We=>Ae.mutate(We),isLoading:Ae.isPending,t}),_&&U&&a.jsx(bnt,{folders:U,selectedFiles:p,currentFolderId:u,onClose:()=>k(!1),onMove:We=>Ye.mutate({fileIds:p,folderId:We}),isLoading:Ye.isPending,t}),P&&a.jsx(kae,{folderId:u,onClose:()=>N(!1),onUploadComplete:xt}),M&&a.jsx(xnt,{folder:M,onClose:()=>T(null),onLink:We=>we.mutate({id:M.id,data:We}),isLoading:we.isPending,t}),A&&a.jsx(kn,{title:A.type==="folder"?t("fileManager.deleteFolder"):A.type==="bulk"?t("fileManager.deleteFilesCount",{count:A.count}):t("fileManager.deleteFile"),message:A.type==="folder"?t("fileManager.deleteFolderConfirm"):A.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:A.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Xt,loadingText:t("fileManager.deleting"),onConfirm:Ht,onCancel:()=>C(null)}),F&&a.jsx(kd,{mode:"reprint",libraryFileId:F.id,archiveName:F.print_name||F.filename,onClose:()=>$(null),onSuccess:()=>{$(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),I&&a.jsx(kd,{mode:"reprint",libraryFileId:I.id,archiveName:I.print_name||I.filename,onClose:()=>Q(null),onSuccess:()=>{Q(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(kd,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>re(null),onSuccess:()=>{re(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),de&&a.jsx(ez,{libraryFileId:de.id,title:de.print_name||de.filename,fileType:de.file_type,onClose:()=>K(null)}),ae&&a.jsx(gnt,{type:ae.type,currentName:ae.name,onClose:()=>ee(null),onSave:We=>{ae.type==="file"?$e.mutate({id:ae.id,filename:We}):De.mutate({id:ae.id,name:We})},isLoading:$e.isPending||De.isPending,t})]})}const fk=5,wnt=2e3,Snt=3e4,_nt=5e3;function knt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=Sr(),{printerId:i}=Cw(),s=parseInt(i||"0",10),[o,l]=w.useState("stream"),[c,d]=w.useState(!1),[u,m]=w.useState(!1),[p,f]=w.useState(!0),[y,v]=w.useState(Date.now()),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(0),[M,T]=w.useState(!1),[A,C]=w.useState(0),[F,$]=w.useState(1),[I,Q]=w.useState({x:0,y:0}),[L,re]=w.useState(!1),[ae,ee]=w.useState({x:0,y:0}),[ue,le]=w.useState(null),[de,K]=w.useState(null),te=w.useRef(null),se=w.useRef(null),be=w.useRef(null),Ne=w.useRef(null),B=w.useRef(null),{data:Y}=et({queryKey:["printer",s],queryFn:()=>he.getPrinter(s),enabled:s>0}),{data:D}=et({queryKey:["printerStatus",s],queryFn:()=>he.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),j=lt({mutationFn:_e=>he.setChamberLight(s,_e),onMutate:async _e=>{await e.cancelQueries({queryKey:["printerStatus",s]});const je=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Be=>({...Be,chamber_light:_e})),{previousStatus:je}},onSuccess:(_e,je)=>{n(`Chamber light ${je?"on":"off"}`)},onError:(_e,je,Be)=>{Be?.previousStatus&&e.setQueryData(["printerStatus",s],Be.previousStatus),n(_e.message||t("printers.toast.failedToControlChamberLight"),"error")}}),z=(D?.state==="RUNNING"||D?.state==="PAUSE")&&(D?.printable_objects_count??0)>=2;w.useEffect(()=>(Y&&(document.title=`${Y.name} - Camera`),()=>{document.title="Bambuddy"}),[Y]);const W=w.useRef(!1);w.useEffect(()=>{const _e=`/api/v1/printers/${s}/camera/stop`;W.current=!1;const je=()=>{if(s>0&&!W.current){W.current=!0;const Ye={},we=Ku();we&&(Ye.Authorization=`Bearer ${we}`),fetch(_e,{method:"POST",keepalive:!0,headers:Ye}).catch(()=>{})}},Be=()=>{je()};window.addEventListener("beforeunload",Be);const Re=te.current;return()=>{window.removeEventListener("beforeunload",Be),Re&&(Re.src=""),je()}},[s]),w.useEffect(()=>{if(p&&!b){const je=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(je)}},[o,p,y,b]),w.useEffect(()=>{const _e=()=>{const je=!!document.fullscreenElement;k(je),$(1),Q({x:0,y:0}),o==="stream"&&!b&&(te.current&&(te.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",_e),()=>document.removeEventListener("fullscreenchange",_e)},[o,b]),w.useEffect(()=>{let _e;const je=()=>{clearTimeout(_e),_e=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",je),()=>{clearTimeout(_e),window.removeEventListener("resize",je)}},[]),w.useEffect(()=>()=>{be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),B.current&&clearInterval(B.current)},[]);const q=w.useCallback(()=>{if(P>=fk){T(!1),m(!0);return}const _e=Math.min(wnt*Math.pow(2,P),Snt);T(!0),C(Math.ceil(_e/1e3)),Ne.current=setInterval(()=>{C(je=>je<=1?(Ne.current&&clearInterval(Ne.current),0):je-1)},1e3),be.current=setTimeout(()=>{N(je=>je+1),T(!1),f(!0),m(!1),te.current&&(te.current.src=""),v(Date.now())},_e)},[P]);w.useEffect(()=>{if(o!=="stream"||p||M||b){B.current&&(clearInterval(B.current),B.current=null);return}return B.current=setInterval(async()=>{try{const _e=await he.getCameraStatus(s);(_e.stalled||!_e.active&&!u)&&(console.log(`Stream issue detected: stalled=${_e.stalled}, active=${_e.active}, reconnecting...`),B.current&&(clearInterval(B.current),B.current=null),f(!1),q())}catch{}},_nt),()=>{B.current&&(clearInterval(B.current),B.current=null)}},[o,p,u,M,b,s,q]);const ce=()=>{f(!1),o==="stream"&&P{if(f(!1),m(!1),N(0),T(!1),be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),te.current&&!localStorage.getItem("cameraWindowState")){const _e=te.current,je=_e.naturalWidth,Be=_e.naturalHeight;if(je>0&&Be>0){const we=window.outerWidth-window.innerWidth,$e=window.outerHeight-window.innerHeight,De=je+16+we,Xe=Be+45+16+$e;try{window.resizeTo(De,Xe)}catch{}}}},G=()=>{if(s>0){const _e={},je=Ku();je&&(_e.Authorization=`Bearer ${je}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:_e}).catch(()=>{})}},X=_e=>{o===_e||b||(g(!0),f(!0),m(!1),N(0),T(!1),$(1),Q({x:0,y:0}),be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),te.current&&(te.current.src=""),o==="stream"&&G(),setTimeout(()=>{l(_e),v(Date.now()),g(!1)},100))},V=()=>{b||(g(!0),f(!0),m(!1),N(0),T(!1),be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),te.current&&(te.current.src=""),o==="stream"&&G(),setTimeout(()=>{v(Date.now()),g(!1)},100))},J=()=>{se.current&&(document.fullscreenElement?document.exitFullscreen():se.current.requestFullscreen())},ie=()=>{$(_e=>Math.min(_e+.5,4))},me=()=>{$(_e=>{const je=Math.max(_e-.5,1);return je===1&&Q({x:0,y:0}),je})},pe=_e=>{_e.preventDefault(),_e.deltaY<0?ie():me()},oe=_e=>{F>1&&(_e.preventDefault(),re(!0),ee({x:_e.clientX-I.x,y:_e.clientY-I.y}))},U=w.useCallback(()=>{if(!se.current)return{x:300,y:200};const _e=se.current.getBoundingClientRect(),je=_e.width*(F-1)/2,Be=_e.height*(F-1)/2;return{x:Math.max(50,je),y:Math.max(50,Be)}},[F]),R=_e=>{if(L&&F>1){const je=_e.clientX-ae.x,Be=_e.clientY-ae.y,Re=U();Q({x:Math.max(-Re.x,Math.min(Re.x,je)),y:Math.max(-Re.y,Math.min(Re.y,Be))})}},ne=()=>{re(!1)},xe=_e=>{if(_e.length<2)return 0;const je=_e[0].clientX-_e[1].clientX,Be=_e[0].clientY-_e[1].clientY;return Math.sqrt(je*je+Be*Be)},Se=_e=>_e.length<2?{x:_e[0].clientX,y:_e[0].clientY}:{x:(_e[0].clientX+_e[1].clientX)/2,y:(_e[0].clientY+_e[1].clientY)/2},ye=_e=>{_e.touches.length===2?(_e.preventDefault(),le(xe(_e.touches)),K(Se(_e.touches))):_e.touches.length===1&&F>1&&(_e.preventDefault(),re(!0),ee({x:_e.touches[0].clientX-I.x,y:_e.touches[0].clientY-I.y}))},ve=_e=>{if(_e.touches.length===2&&ue!==null){_e.preventDefault();const je=xe(_e.touches),Be=je/ue;$(Ye=>{const we=Math.max(1,Math.min(4,Ye*Be));return we===1&&Q({x:0,y:0}),we}),le(je);const Re=Se(_e.touches);if(de){const Ye=U();Q(we=>({x:Math.max(-Ye.x,Math.min(Ye.x,we.x+(Re.x-de.x))),y:Math.max(-Ye.y,Math.min(Ye.y,we.y+(Re.y-de.y)))}))}K(Re)}else if(_e.touches.length===1&&L&&F>1){_e.preventDefault();const je=_e.touches[0].clientX-ae.x,Be=_e.touches[0].clientY-ae.y,Re=U();Q({x:Math.max(-Re.x,Math.min(Re.x,je)),y:Math.max(-Re.y,Math.min(Re.y,Be))})}},fe=_e=>{_e.touches.length<2&&(le(null),K(null)),_e.touches.length===0&&re(!1)},ke=()=>{$(1),Q({x:0,y:0})},Ee=b?"":Ra(o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${y}`:`/api/v1/printers/${s}/camera/snapshot?t=${y}`),Ae=p||b||M;return s?a.jsxs("div",{ref:se,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(yx,{className:"w-4 h-4"}),Y?.name||`Printer ${s}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>X("stream"),disabled:Ae,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),a.jsx("button",{onClick:()=>X("snapshot"),disabled:Ae,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),a.jsx("button",{onClick:()=>j.mutate(!D?.chamber_light),disabled:!D?.connected||j.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${D?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:a.jsx(YO,{on:D?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>d(!0),disabled:!z||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${z&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(z?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(zP,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:V,disabled:Ae,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(vr,{className:`w-4 h-4 text-bambu-gray ${Ae?"animate-spin":""}`})}),a.jsx("button",{onClick:J,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?a.jsx(bQ,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Ige,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:R,onMouseUp:ne,onMouseLeave:ne,onTouchStart:ye,onTouchMove:ve,onTouchEnd:fe,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||b)&&!M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(vr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Wu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:A,attempt:Math.min(P+1,fk),max:fk})}),a.jsx("button",{onClick:V,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),u&&!M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Ln,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:V,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:te,src:Ee,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${F}) translate(${I.x/F}px, ${I.y/F}px) rotate(${Y?.camera_rotation||0}deg)`,...Y?.camera_rotation===90||Y?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:F>1?L?"grabbing":"grab":"default"},onError:Ee?ce:void 0,onLoad:Ee?O:void 0,onMouseDown:oe,draggable:!1},y),a.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:[a.jsx("button",{onClick:me,disabled:F<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(xO,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:ke,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(F*100),"%"]}),a.jsx("button",{onClick:ie,disabled:F>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(bO,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(XO,{printerId:s,isOpen:c,onClose:()=>d(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Nnt(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function Cnt(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:r,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 Pnt(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 Tnt(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 Ant(){const{printerId:t}=Cw(),[e]=eO(),{t:n}=Lt(),r=mn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>Cnt(e),[e]),c=Tnt(l.size),{data:d}=et({queryKey:["printer",i],queryFn:()=>he.getPrinter(i),enabled:i>0}),{data:u}=et({queryKey:["printerStatus",i],queryFn:()=>he.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=et({queryKey:["settings"],queryFn:he.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!i)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(_);return k.onmessage=P=>{try{const N=JSON.parse(P.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},k.onerror=()=>{},()=>{k.close()}},[i,r]),w.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=Ra(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src:b,alt:n("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),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.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:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Pr,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:Nnt(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Pnt(u,n)}),l.showProgress&&y&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&a.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&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(ea,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:u.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Pc,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:ls(u.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(rr,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",vO(u.remaining_time,p,n)]})]})]})]}),!y&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Mnt(){const{t}=Lt(),{id:e}=Cw(),{mode:n}=cg(),{data:r,isLoading:i,error:s}=et({queryKey:["external-link",e],queryFn:()=>he.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Ln,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function rX(){const{id:t}=Cw(),e=Eo(),n=mn(),{t:r}=Lt(),{showToast:i}=xn(),s=!!t,[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=et({queryKey:["group",t],queryFn:()=>he.getGroup(Number(t)),enabled:s}),{data:_,isLoading:k}=et({queryKey:["permissions"],queryFn:()=>he.getPermissions()});s&&b&&!y&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const P=lt({mutationFn:ee=>he.createGroup(ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.created")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),N=lt({mutationFn:ee=>he.updateGroup(Number(t),ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.updated")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),M=P.isPending||N.isPending,T=()=>{if(!o.trim()){i(r("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},A=ee=>{m(ue=>ue.includes(ee)?ue.filter(le=>le!==ee):[...ue,ee])},C=(ee,ue)=>{const le=ee.permissions.map(de=>de.value);m(de=>{const K=de.filter(te=>!le.includes(te));return ue?[...K,...le]:K})},F=ee=>ee.permissions.every(ue=>u.includes(ue.value)),$=ee=>{const ue=ee.permissions.filter(le=>u.includes(le.value)).length;return ue>0&&ue{_&&m(_.all_permissions)},Q=()=>{m([])},L=p.toLowerCase(),re=w.useMemo(()=>_?L?_.categories.map(ee=>({...ee,permissions:ee.permissions.filter(ue=>ue.label.toLowerCase().includes(L))})).filter(ee=>ee.permissions.length>0):_.categories:[],[_,L]),ae=_?.all_permissions.length??0;return g||k?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.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:a.jsx(uQ,{className:"w-5 h-5"})}),a.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&a.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:[a.jsx(Ln,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),a.jsx("input",{type:"text",value:o,onChange:ee=>l(ee.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:r("groups.form.groupNamePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),a.jsx("input",{type:"text",value:c,onChange:ee=>d(ee.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:r("groups.form.descriptionPlaceholder")})]})]}),a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:u.length})," / ",ae]}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:I,children:r("groups.editor.selectAll")}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:Q,children:r("groups.editor.clearAll")})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),a.jsx("input",{type:"text",value:p,onChange:ee=>f(ee.target.value),placeholder:r("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"})]})]}),re.length===0?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:re.map(ee=>{const ue=_.categories.find(se=>se.name===ee.name),le=ue.permissions.filter(se=>u.includes(se.value)).length,de=ue.permissions.length,K=F(ue),te=$(ue);return a.jsxs(Dt,{children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>C(ue,!K),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${K?"bg-bambu-green border-bambu-green":te?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[K&&a.jsx(Kr,{className:"w-3 h-3 text-white"}),te&&!K&&a.jsx(rN,{className:"w-3 h-3 text-white"})]}),a.jsx(Wb,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-white font-medium text-sm",children:ee.name})]}),a.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[le,"/",de]})]}),a.jsx("div",{className:"p-3 space-y-1",children:ee.permissions.map(se=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u.includes(se.value),onChange:()=>A(se.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"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:se.label})]},se.value))})]},ee.name)})}),a.jsx("div",{className:"h-16"}),a.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:[a.jsx(Ie,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),a.jsx(Ie,{onClick:T,disabled:M||!o.trim(),children:M?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const qL={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function ble(t,e=!1){const n={};return e?(t.material||(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 xle=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],jnt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],M0=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","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"],yle=[{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"}],Ent=[{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"}],aX=[...yle,...Ent],vle="bambuddy-recent-colors",Dnt=8,Fnt=[{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 Jh(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["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 r="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){r=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of M0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of M0){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:r,variant:l}}function wle(t,e){const n=new Set(jnt);for(const r of t){const{brand:i}=Jh(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=Jh(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function Rnt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function Sle(t,e,n){if(t.length>0){const r=[],i=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=Rnt(n);if(r.length>0)return r}return Fnt}function _le(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function kle(){try{const t=localStorage.getItem(vle);if(t)return JSON.parse(t)}catch{}return[]}function Nle(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,Dnt);try{localStorage.setItem(vle,JSON.stringify(r))}catch{}return r}function h3(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Jh(r);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())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function Cle({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Lt(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,P]=w.useState(!1),[N,M]=w.useState(!1),[T,A]=w.useState(""),[C,F]=w.useState(""),[$,I]=w.useState(""),[Q,L]=w.useState(String(t.label_weight)),[re,ae]=w.useState(!1),ee=w.useRef(null),ue=w.useRef(null),le=w.useRef(null),de=w.useRef(null);w.useEffect(()=>{const B=Y=>{ee.current&&!ee.current.contains(Y.target)&&b(!1),de.current&&!de.current.contains(Y.target)&&M(!1),ue.current&&!ue.current.contains(Y.target)&&_(!1),le.current&&!le.current.contains(Y.target)&&P(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]);const K=w.useMemo(()=>{if(!i)return l;const B=i.toLowerCase();return l.filter(Y=>Y.displayName.toLowerCase().includes(B)||Y.code.toLowerCase().includes(B))},[l,i]),te=w.useMemo(()=>{if(!T)return c;const B=T.toLowerCase();return c.filter(D=>D.toLowerCase().includes(B)).sort((D,j)=>{const z=D.toLowerCase()===B,W=j.toLowerCase()===B;return z&&!W?-1:!z&&W?1:D.localeCompare(j)})},[c,T]),se=w.useMemo(()=>{if(!C)return M0;const B=C.toLowerCase();return M0.filter(Y=>Y.toLowerCase().includes(B))},[C]),be=w.useMemo(()=>{if(!$)return d;const B=$.toLowerCase();return d.filter(D=>D.toLowerCase().includes(B)).sort((D,j)=>{const z=D.toLowerCase()===B,W=j.toLowerCase()===B;return z&&!W?-1:!z&&W?1:D.localeCompare(j)})},[$,d]);w.useEffect(()=>{re||L(String(t.label_weight))},[t.label_weight,re]);const Ne=B=>{e("slicer_filament",B.code),s(B.displayName),b(!1);const Y=Jh(B.name);Y.material&&e("material",Y.material),Y.brand&&e("brand",Y.brand),Y.variant&&e("subtype",Y.variant)};return a.jsxs("div",{className:"space-y-4",children:[!u&&a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(Jx,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(Wpe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!u&&a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:ee,children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:y("inventory.searchPresets"),value:i,onChange:B=>{s(B.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&a.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:K.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):K.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===B.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Ne(B),children:B.displayName},B.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),a.jsxs("div",{className:"relative",ref:de,children:[a.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:y("inventory.selectMaterial"),value:N?$:t.material,onChange:B=>{I(B.target.value),M(!0)},onFocus:()=>{M(!0),I("")}}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&a.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:[be.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):be.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",B),M(!1),I("")},children:B},B)),$&&!be.includes($)&&a.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",$),M(!1),I("")},children:y("inventory.useCustomMaterial",{material:$})})]})]}),f?.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:ue,children:[a.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:y("inventory.searchBrand"),value:g?T:t.brand,onChange:B=>{A(B.target.value),_(!0)},onFocus:()=>{_(!0),A("")}}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&a.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:[te.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):te.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",B),_(!1),A("")},children:B},B)),T&&!te.includes(T)&&a.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",T),_(!1),A("")},children:y("inventory.useCustomBrand",{brand:T})})]})]}),f?.brand&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:le,children:[a.jsx("input",{type:"text",value:k?C:t.subtype,onChange:B=>{F(B.target.value),P(!0)},onFocus:()=>{P(!0),F("")},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"}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&a.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:[se.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):se.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",B),P(!1),F("")},children:B},B)),C&&!M0.some(B=>B.toLowerCase()===C.toLowerCase().trim())&&a.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",C),P(!1),F("")},children:y("inventory.useCustomBrand",{brand:C})})]})]}),f?.subtype&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.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:Q,min:0,onFocus:()=>ae(!0),onChange:B=>L(B.target.value),onBlur:()=>{ae(!1);const B=Q.trim(),Y=Number(B);if(!B||!Number.isFinite(Y)||Y<0){L(String(t.label_weight));return}const D=Math.round(Y);e("label_weight",D),L(String(D))}}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),a.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:B=>{const Y=Math.max(1,Math.min(100,parseInt(B.target.value)||1));p(Y)}})]})]})}function Ple({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=t.rgba.replace("#","").substring(0,6),m=g=>u.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(i.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),k=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const P=g?g.toLowerCase().split(/[\s\-_]+/).filter(T=>T.length>=2):[],N=T=>{if(P.length===0)return!0;const A=T.toLowerCase();return P.some(C=>A.includes(C))};if(g&&!_){const T=i.filter(A=>N(A.manufacturer));if(T.length>0)return T.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}))}const M=_&&k?`${_} ${k}`:"";if(M){const T=i.filter(C=>N(C.manufacturer)&&C.material?.toLowerCase()===M);if(T.length>0)return T.map(C=>({name:C.color_name,hex:C.hex_color.replace("#","").substring(0,6),manufacturer:C.manufacturer,material:typeof C.material=="string"?C.material:void 0}));const A=M.replace(/\+$/,"");if(A!==M){const C=i.filter(F=>N(F.manufacturer)&&F.material?.toLowerCase()===A);if(C.length>0)return C.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}}if(_){const T=i.filter(A=>N(A.manufacturer)&&(!A.material||A.material.toLowerCase().startsWith(_)));if(T.length>0)return T.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(k=>k.name.toLowerCase().includes(g)||(k.manufacturer?.toLowerCase().includes(g)??!1)||(k.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?aX.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?aX:yle,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${u}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(rr,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:g=>d(g.target.value)})]}),v?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:a.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:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(Yl,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(Fn,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:a.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:g.name})},g.hex)),b.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.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:g=>e("color_name",g.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.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:u.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),a.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Lnt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&r!==null&&i(null)},[e,t,r,i]);const p=w.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=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(vbe,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[a.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:y,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&a.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?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>a.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 ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),n(v.weight),l(!1),d("")},children:[a.jsx("span",{className:"truncate",children:v.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.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&&n(b)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Tle({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:i}=Lt(),{showToast:s}=xn(),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(Lnt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=u.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:o,min:0,onFocus:()=>d(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{d(!1);const b=o.trim(),g=Number(b),_=t.core_weight,k=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>k){s(i("inventory.measuredWeightError",{min:_,max:k}),"error"),l(String(v));return}const P=Math.round(g),N=Math.max(0,Math.min(t.label_weight,P-t.core_weight));e("weight_used",Math.max(0,t.label_weight-N)),l(String(P))},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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.costPerKg","Cost per kg")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),a.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.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"})]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.note")}),a.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:i("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function Ale({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Lt(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const k of Array.from(_)){const P=k.split(":");`${P[0]}:${P[2]}`===b&&_.delete(k)}_.add(v)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>h3(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const P=[..._].sort((N,M)=>M.k_value-N.k_value)[0];p.add(`${f.id}:${P.cali_idx}:${g}`)}}r(p)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>h3(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return a.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:[a.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"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.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 a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.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&&a.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:[a.jsx(wx,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=i.has(String(p.id)),v=f.filter(P=>h3(P,t)),b=v.length,g=v.some(P=>P.extruder_id!==void 0&&P.extruder_id!==null&&P.extruder_id>0),_=v.filter(P=>P.extruder_id===1),k=v.filter(P=>P.extruder_id===0||P.extruder_id===void 0||P.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[y?a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Va,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?a.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")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.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")})]}),y&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?a.jsxs(a.Fragment,{children:[_.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:_.map(P=>m(p,P))})]}),k.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:k.map(P=>m(p,P))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(P=>m(p,P))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Ont(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Int={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function znt({spoolId:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),{data:i,isLoading:s}=et({queryKey:["spool-usage",t],queryFn:()=>he.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>he.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(rr,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(un,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:Ont(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:Int[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Unt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:i,onSpoolsCreated:s}){const{t:o}=Lt(),l=mn(),{showToast:c}=xn(),d=!!n,[u,m]=w.useState(qL),[p,f]=w.useState({}),[y,v]=w.useState("filament"),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(1),[M,T]=w.useState(!1),[A,C]=w.useState(!1),[F,$]=w.useState([]),[I,Q]=w.useState(""),[L,re]=w.useState([]),[ae,ee]=w.useState([]),[ue,le]=w.useState([]),[de,K]=w.useState([]),[te,se]=w.useState([]),[be,Ne]=w.useState(new Set),[B,Y]=w.useState(new Set),D=r.length>0?r:te,j=w.useMemo(()=>be.size,[be]);w.useEffect(()=>{K(kle())},[]),w.useEffect(()=>{t&&((async()=>{C(!0);try{const Ee=await he.getCloudStatus();if(T(Ee.is_authenticated),Ee.is_authenticated){const Ae=await he.getFilamentPresets();$(Ae)}}catch(Ee){console.error("Failed to fetch cloud presets:",Ee),T(!1)}finally{C(!1)}})(),he.getSpoolCatalog().then(re).catch(console.error),he.getColorCatalog().then(le).catch(console.error),he.getLocalPresets().then(Ee=>ee(Ee.filament)).catch(console.error),r.length===0&&(async()=>{try{const Ee=await he.getPrinters(),Ae=await Promise.all(Ee.map(je=>he.getPrinterStatus(je.id).catch(()=>null))),_e=[];for(let je=0;je({cali_idx:De.slot_id,filament_id:De.filament_id,setting_id:De.setting_id||"",name:De.name,k_value:parseFloat(De.k_value)||0,n_coef:parseFloat(De.n_coef)||0,extruder_id:De.extruder_id,nozzle_diameter:De.nozzle_diameter}))}catch{}_e.push({printer:{...Be,connected:Ye},calibrations:we})}se(_e)}catch(Ee){console.error("Failed to fetch printer calibrations:",Ee)}})())},[t,r.length]);const z=w.useMemo(()=>Sle(F,new Set,ae),[F,ae]),W=w.useMemo(()=>{const ke=wle(F,ae),Ee=ue.map(_e=>_e.manufacturer?.trim()).filter(_e=>!!_e),Ae=new Set([...ke,...Ee]);return Array.from(Ae).sort((_e,je)=>_e.localeCompare(je))},[F,ae,ue]),q=w.useMemo(()=>{const ke=ue.map(Ae=>Ae.material?.trim()).filter(Ae=>!!Ae),Ee=new Set([...xle,...ke]);return Array.from(Ee).sort((Ae,_e)=>Ae.localeCompare(_e))},[ue]),ce=w.useMemo(()=>{const ke=[];for(const Ee of ue){const Ae=Ee.manufacturer?.trim(),_e=Ee.material?.trim();Ae&&_e&&ke.push({brand:Ae,material:_e})}for(const Ee of F){const Ae=Jh(Ee.name);Ae.brand&&Ae.material&&ke.push({brand:Ae.brand,material:Ae.material})}for(const Ee of ae){const Ae=Jh(Ee.name),_e=Ee.filament_vendor?.trim()||Ae.brand,je=Ae.material;_e&&je&&ke.push({brand:_e,material:je})}return ke},[F,ue,ae]),O=w.useMemo(()=>{const ke=new Map;for(const Ee of ce){const Ae=Ee.brand.toLowerCase(),_e=Ee.material.toLowerCase();ke.has(Ae)||ke.set(Ae,new Set),ke.get(Ae).add(_e)}return ke},[ce]),G=w.useMemo(()=>{const ke=new Map;for(const Ee of ce){const Ae=Ee.brand.toLowerCase(),_e=Ee.material.toLowerCase();ke.has(_e)||ke.set(_e,new Set),ke.get(_e).add(Ae)}return ke},[ce]),X=w.useMemo(()=>{if(!u.material)return W;const ke=u.material.toLowerCase(),Ee=G.get(ke);return!Ee||Ee.size===0?W:W.filter(Ae=>Ee.has(Ae.toLowerCase()))},[W,u.material,G]),V=w.useMemo(()=>{if(!u.brand)return q;const ke=u.brand.toLowerCase(),Ee=O.get(ke);return!Ee||Ee.size===0?q:q.filter(Ae=>Ee.has(Ae.toLowerCase()))},[q,u.brand,O]),J=w.useMemo(()=>_le(u.slicer_filament,z),[u.slicer_filament,z]);w.useEffect(()=>{if(t){if(n)if(m({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),Q(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const ke=new Set;for(const Ee of n.k_profiles)Ee.cali_idx!==null&&Ee.cali_idx!==void 0&&ke.add(`${Ee.printer_id}:${Ee.cali_idx}:${Ee.extruder??"null"}`);Ne(ke)}else Ne(new Set);else m(qL),Q(""),Ne(new Set),k(!1),N(1);f({}),v("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&D.length>0&&Y(new Set(D.map(ke=>String(ke.printer.id))))},[t,D]);const ie=(ke,Ee)=>{m(Ae=>({...Ae,[ke]:Ee})),ke==="weight_used"&&g(!0),p[ke]&&f(Ae=>({...Ae,[ke]:void 0}))},me=ke=>{K(Ee=>Nle(ke,Ee))},pe=lt({mutationFn:ke=>he.createSpool(ke),onSuccess:async ke=>{be.size>0&&ke?.id&&await ye(ke.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s([ke]),c(o("inventory.spoolCreated"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),oe=lt({mutationFn:({data:ke,qty:Ee})=>he.bulkCreateSpools(ke,Ee),onSuccess:async ke=>{if(be.size>0)for(const Ee of ke)await ye(Ee.id);await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s(ke),c(o("inventory.spoolsCreated",{count:ke.length}),"success"),e()},onError:ke=>{c(ke.message,"error")}}),U=lt({mutationFn:ke=>he.updateSpool(n.id,ke),onSuccess:async()=>{n?.id&&await ye(n.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.spoolUpdated"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),R=lt({mutationFn:()=>he.updateSpool(n.id,{tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null}),onSuccess:async()=>{await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.tagDeleted","Tag removed"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),{data:ne}=et({queryKey:["spool-assignments"],queryFn:()=>he.getAssignments(),enabled:t&&d}),xe=n?ne?.find(ke=>ke.spool_id===n.id):void 0,Se=lt({mutationFn:()=>{if(!xe)throw new Error("No assignment");return he.unassignSpool(xe.printer_id,xe.ams_id,xe.tray_id)},onSuccess:async()=>{await l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),ye=async ke=>{if(be.size===0){try{await he.saveSpoolKProfiles(ke,[])}catch{}return}const Ee=[];for(const Ae of be){const[_e,je,Be]=Ae.split(":"),Re=parseInt(_e),Ye=parseInt(je),we=Be==="null"?0:parseInt(Be),$e=D.find(De=>De.printer.id===Re);if($e){const De=$e.calibrations.find(Xe=>Xe.cali_idx===Ye);De&&Ee.push({printer_id:Re,extruder:we,nozzle_diameter:De.nozzle_diameter||"0.4",k_value:De.k_value,name:De.name||null,cali_idx:De.cali_idx,setting_id:De.setting_id||null})}}if(Ee.length>0)try{await he.saveSpoolKProfiles(ke,Ee)}catch(Ae){console.error("Failed to save K-profiles:",Ae)}};if(w.useEffect(()=>{if(!t)return;const ke=Ee=>{Ee.key==="Escape"&&e()};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[t,e]),!t)return null;const ve=()=>{const ke=ble(u,_);if(!ke.isValid){f(ke.errors),(ke.errors.slicer_filament||ke.errors.material||ke.errors.brand||ke.errors.subtype)&&v("filament");return}const Ee=J?.displayName||I||null,Ae={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Ee,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!d||b)&&(Ae.weight_used=u.weight_used),d?U.mutate(Ae):P>1?oe.mutate({data:Ae,qty:P}):pe.mutate(Ae)},fe=pe.isPending||oe.isPending||U.isPending||R.isPending||Se.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o(d?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),!d&&a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4 text-amber-400"}),a.jsx("span",{className:"text-sm text-white",children:o("inventory.quickAdd")})]}),a.jsx("button",{type:"button",onClick:()=>{k(!_),_||v("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${_?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${_?"translate-x-4":"translate-x-0.5"}`})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>v("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Dw,{className:"w-4 h-4"}),o("inventory.filamentInfoTab")]}),!_&&a.jsxs("button",{onClick:()=>v("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(npe,{className:"w-4 h-4"}),o("inventory.paProfileTab"),j>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:y==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.filamentInfo")}),a.jsx(Cle,{formData:u,updateField:ie,cloudAuthenticated:M,loadingCloudPresets:A,presetInputValue:I,setPresetInputValue:Q,selectedPresetOption:J,filamentOptions:z,availableBrands:X,availableMaterials:V,quickAdd:_,quantity:P,onQuantityChange:N,errors:p})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.color")}),a.jsx(Ple,{formData:u,updateField:ie,recentColors:de,onColorUsed:me,catalogColors:ue})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.additional")}),a.jsx(Tle,{formData:u,updateField:ie,spoolCatalog:L,currencySymbol:i})]}),d&&n&&a.jsx("div",{children:a.jsx(znt,{spoolId:n.id})})]}):a.jsx(Ale,{formData:u,updateField:ie,printersWithCalibrations:D,selectedProfiles:be,setSelectedProfiles:Ne,expandedPrinters:B,setExpandedPrinters:Y})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[d&&a.jsxs("div",{className:"flex gap-2 mr-auto",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>R.mutate(),disabled:fe||!n?.tag_uid,children:[a.jsx(Vu,{className:"w-4 h-4"}),o("inventory.deleteTag","Delete Tag")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>Se.mutate(),disabled:fe||!xe,children:[a.jsx(qh,{className:"w-4 h-4"}),o("inventory.unassignSpool","Unassign")]})]}),a.jsxs("div",{className:"flex gap-2 ml-auto",children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(Ie,{onClick:ve,disabled:fe,children:fe?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),o("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),o(d?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Bnt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Lt(),[o,l]=w.useState(n),[c,d]=w.useState(null),u=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(P=>({...P})))},[t,n]),w.useEffect(()=>{if(!t)return;const P=N=>{N.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,e]),!t)return null;const m=P=>{l(N=>N.map((M,T)=>T===P?{...M,visible:!M.visible}:M))},p=(P,N)=>{N<0||N>=o.length||l(M=>{const T=[...M],[A]=T.splice(P,1);return T.splice(N,0,A),T})},f=(P,N)=>{u.current=N,d(N),P.dataTransfer.effectAllowed="move"},y=(P,N)=>{P.preventDefault(),P.dataTransfer.dropEffect="move";const M=u.current;M!==null&&M!==N&&(p(M,N),u.current=N,d(N))},v=P=>{P.preventDefault()},b=()=>{u.current=null,d(null)},g=()=>{l(r.map(P=>({...P})))},_=()=>{i(o),e()},k=o.filter(P=>P.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(Dt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:P=>P.stopPropagation(),children:a.jsxs(Rt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",k," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((P,N)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===N?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${P.visible?"":"opacity-50"}`,draggable:!0,onDragStart:M=>f(M,N),onDragOver:M=>y(M,N),onDrop:v,onDragEnd:b,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx(jh,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:P.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>p(N,N-1),disabled:N===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:a.jsx(Yl,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>p(N,N+1),disabled:N===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:a.jsx(Fn,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>m(N),className:`p-1.5 rounded transition-colors ${P.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:P.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:P.visible?a.jsx(Dc,{className:"w-4 h-4"}):a.jsx(Tw,{className:"w-4 h-4"})})]},P.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(Ie,{variant:"secondary",onClick:g,className:"mr-auto",children:[a.jsx(jo,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(Ie,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(Ie,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function iX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Mle="bambuddy-inventory-columns",$k=[{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:"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 Hnt(){try{const t=localStorage.getItem(Mle);if(t){const e=JSON.parse(t),n=new Set($k.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=$k.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return $k.map(t=>({...t}))}function qnt(t){try{localStorage.setItem(Mle,JSON.stringify(t))}catch{}}function xd(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const $nt={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 p3(t,e="system"){if(!t)return"-";const n=Qn(t);return n?V3(n,e):"-"}const Vnt={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",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")},$L={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:p3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:p3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?p3(t.last_used,e):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:FT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.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 n=e[t.id];if(!n)return a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=uS(n.ams_id,n.tray_id,s,i);return a.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:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:xd(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:xd(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:xd(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?xd(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.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?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.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)}%`}})}),a.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 n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return a.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>a.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 n=t.last_scale_weight;if(n==null)return a.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g
+`+n+"}"}return String(t)}function Qtt({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:i,hasPermission:s,t:o}){const{showToast:l}=xn(),c=mn(),[d,u]=w.useState(!1),{data:m,isLoading:p}=et({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>he.getCloudSettingDetail(t.setting_id)}),f=lt({mutationFn:()=>he.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:b=>l(b.message,"error")}),y=kw(t.setting_id),v=Kz(t.name,m?.setting?.inherits);return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),y&&a.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")})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[a.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&a.jsxs(a.Fragment,{children:[a.jsx("span",{children:"•"}),a.jsx("span",{children:v.printer})]})]})]}),a.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.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:BL(m)}):a.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),d?a.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[a.jsx(Ln,{className:"w-5 h-5"}),a.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>u(!1),disabled:f.isPending,className:"flex-1",children:o("common.cancel")}),a.jsxs(Ie,{variant:"danger",onClick:()=>f.mutate(),disabled:f.isPending,className:"flex-1",children:[f.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(un,{className:"w-4 h-4"}),o("common.delete")]})]})]}):a.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),a.jsxs(Ie,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[a.jsx(Mo,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),y&&a.jsxs(a.Fragment,{children:[a.jsxs(Ie,{variant:"secondary",onClick:i,disabled:p||!m||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[a.jsx(Za,{className:"w-4 h-4"}),o("common.edit")]}),a.jsx(Ie,{variant:"danger",onClick:()=>u(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:a.jsx(un,{className:"w-4 h-4"})})]})]})})]})})})}function mle(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function hle(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function Ztt({onClose:t,onApply:e,t:n}){const{showToast:r}=xn(),[i,s]=w.useState(mle),[o,l]=w.useState("all"),[c,d]=w.useState(null),[u,m]=w.useState(""),[p,f]=w.useState(""),[y,v]=w.useState("{}"),[b,g]=w.useState(null),[_,k]=w.useState(null),P=o==="all"?i:i.filter(Q=>Q.type===o),N=Q=>{s(Q),hle(Q)},M=Q=>{const L=i.filter(re=>re.id!==Q);N(L),k(null),r(n("profiles.templates.toast.deleted"))},T=Q=>{d(Q.id),m(Q.name),f(Q.description),v(JSON.stringify(Q.settings,null,2)),g(null)},A=()=>{if(!(!c||!u.trim()))try{const Q=JSON.parse(y),L=i.map(re=>re.id===c?{...re,name:u.trim(),description:p.trim(),settings:Q}:re);N(L),d(null),r(n("profiles.templates.toast.updated"))}catch(Q){g(Q.message)}},C=()=>{d(null),m(""),f(""),v("{}"),g(null)},F=Q=>{const L=i.map(re=>re.id===Q?{...re,showInModal:!re.showInModal}:re);N(L)},$={filament:{label:n("profiles.presets.types.filament"),icon:SP,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:Nd,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:Pr,color:"text-purple-400"}},I=_?i.find(Q=>Q.id===_):null;return w.useEffect(()=>{const Q=L=>{L.key==="Escape"&&(_?k(null):c?C():t())};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[_,c,t]),a.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[I&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:a.jsx(Dt,{className:"w-full max-w-md",children:a.jsxs(Rt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:a.jsx(Ln,{className:"w-6 h-6 text-red-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),a.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:I.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:()=>k(null),className:"flex-1",children:n("common.cancel")}),a.jsxs(Ie,{onClick:()=>M(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[a.jsx(un,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),a.jsx(Dt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:a.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(wx,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(Q=>a.jsx("button",{onClick:()=>l(Q),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===Q?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:Q==="all"?n("common.all"):$[Q].label},Q))]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(wx,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:n("profiles.templates.noTemplates")}),a.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):a.jsx("div",{className:"space-y-2",children:P.map(Q=>{const L=$[Q.type],re=L.icon;return c===Q.id?a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[a.jsx("input",{type:"text",value:u,onChange:ae=>m(ae.target.value),placeholder:n("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}),a.jsx("input",{type:"text",value:p,onChange:ae=>f(ae.target.value),placeholder:n("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"})]}),a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),a.jsx("textarea",{value:y,onChange:ae=>{v(ae.target.value),g(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&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:b})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{size:"sm",onClick:A,disabled:!u.trim(),children:[a.jsx(cs,{className:"w-4 h-4"}),"Save"]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:C,children:"Cancel"})]})]},Q.id):a.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:[a.jsx(re,{className:`w-5 h-5 ${L.color} flex-shrink-0`}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Q.name}),a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Q.description})]}),a.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(Q.settings).length})}),a.jsx("button",{onClick:()=>F(Q.id),className:`p-1 transition-colors ${Q.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:Q.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:Q.showInModal?a.jsx(Dc,{className:"w-4 h-4"}):a.jsx(Tw,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>e(Q),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),a.jsx("button",{onClick:()=>T(Q),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>k(Q.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:a.jsx(un,{className:"w-4 h-4"})})]},Q.id)})})})]})})]})}function ple({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:i,t:s}){const[o,l]=w.useState("changes"),[c,d]=w.useState(""),u=w.useMemo(()=>{const y=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const b of y){if(b==="inherits"||b==="version")continue;const g=e[b],_=n[b],k=b in e,P=b in n;let N;!k&&P?N="added":k&&!P?N="removed":JSON.stringify(g)!==JSON.stringify(_)?N="changed":N="same",v.push({key:b,left:g,right:_,status:N})}return v.sort((b,g)=>{const _={changed:0,added:1,removed:2,same:3};return _[b.status]!==_[g.status]?_[b.status]-_[g.status]:b.key.localeCompare(g.key)})},[e,n]),m=w.useMemo(()=>{let y=[...u];if(o==="changes"&&(y=y.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();y=y.filter(b=>b.key.toLowerCase().includes(v)||String(b.left).toLowerCase().includes(v)||String(b.right).toLowerCase().includes(v))}return y},[u,o,c]),p=w.useMemo(()=>({added:u.filter(y=>y.status==="added").length,removed:u.filter(y=>y.status==="removed").length,changed:u.filter(y=>y.status==="changed").length,same:u.filter(y=>y.status==="same").length}),[u]),f=y=>{if(y===void 0)return"—";if(y===null)return"null";if(Array.isArray(y))return y.length===0?"[]":y.length===1?String(y[0]):y.join(", ");if(typeof y=="object")return JSON.stringify(y);const v=String(y);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 w.useEffect(()=>{const y=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsx(Dt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:a.jsxs(Rt,{className:"p-0 flex flex-col min-h-0 flex-1",children:[a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(tx,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),a.jsx("p",{className:"text-white font-medium truncate",children:r})]}),a.jsxs("div",{className:"text-center",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),a.jsx("p",{className:"text-white font-medium truncate",children:i})]})]}),a.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(ur,{className:"w-3.5 h-3.5"}),p.added," ",s("profiles.diff.added")]}),a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(rN,{className:"w-3.5 h-3.5"}),p.removed," ",s("profiles.diff.removed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[a.jsx(O3,{className:"w-3.5 h-3.5"}),p.changed," ",s("profiles.diff.changed")]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(uj,{className:"w-3.5 h-3.5"}),p.same," ",s("profiles.diff.same")]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:c,onChange:y=>d(y.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&&a.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[a.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")}),a.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")})]})]})]}),a.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:m.length===0?a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(uj,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),a.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):a.jsxs("table",{className:"w-full",children:[a.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:a.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),a.jsx("th",{className:"text-left p-3 w-1/3",children:r}),a.jsx("th",{className:"text-left p-3 w-1/3",children:i})]})}),a.jsx("tbody",{children:m.map(y=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[y.status],b={added:a.jsx(ur,{className:"w-3.5 h-3.5 text-green-400"}),removed:a.jsx(rN,{className:"w-3.5 h-3.5 text-red-400"}),changed:a.jsx(O3,{className:"w-3.5 h-3.5 text-amber-400"}),same:a.jsx(uj,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[y.status];return a.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[a.jsx("td",{className:"p-3",children:a.jsxs("div",{className:"flex items-center gap-2",children:[b,a.jsx("span",{className:"text-sm text-white font-mono",children:y.key})]})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="removed"?"text-red-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.left)})}),a.jsx("td",{className:"p-3",children:a.jsx("span",{className:`text-sm font-mono break-all ${y.status==="added"?"text-green-300":y.status==="changed"?"text-white":"text-bambu-gray"}`,children:f(y.right)})})]},y.key)})})]})})]})})})}function Jtt({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:i}=xn(),s=mn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[d,u]=w.useState(e?.type||"filament"),[m,p]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[f,y]=w.useState(e?.base_id||""),[v,b]=w.useState(""),[g,_]=w.useState(e?.setting||{inherits:""}),[k,P]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[N,M]=w.useState(null),[T,A]=w.useState(""),[C,F]=w.useState(!1),[$,I]=w.useState(""),[Q,L]=w.useState(!1),[re,ae]=w.useState(mle),[ee,ue]=w.useState(!1),[le,de]=w.useState(""),[K,te]=w.useState(""),[se,be]=w.useState(!0),[Ne,B]=w.useState(null),[Y,D]=w.useState(!1),j=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[d]||[],[n,d]),z=w.useMemo(()=>j.filter(je=>kw(je.setting_id)),[j]),{data:W}=et({queryKey:["cloudFields",d],queryFn:()=>he.getCloudFields(d==="print"?"process":d),staleTime:1e3*60*60}),{data:q}=et({queryKey:["allPresetDetails",d,z.map(je=>je.setting_id).join(",")],queryFn:async()=>{const je={};for(let Re=0;Re{try{const De=await he.getCloudSettingDetail($e.setting_id);return{id:$e.setting_id,detail:De}}catch{return null}}))).forEach($e=>{$e&&(je[$e.id]=$e.detail)})}return je},enabled:z.length>0,staleTime:1e3*60*10}),{data:ce,isLoading:O}=et({queryKey:["cloudSettingDetail",f],queryFn:()=>he.getCloudSettingDetail(f),enabled:!!f});w.useEffect(()=>{l!=="json"&&P(JSON.stringify(g,null,2))},[g,l]);const G=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[d]||[]).filter(Be=>!kw(Be.setting_id)).sort((Be,Re)=>Be.name.localeCompare(Re.name)),[n,d]);w.useEffect(()=>{if(!f)return;const je=G.find(Be=>Be.setting_id===f);je&&(b(je.name),o||(_({inherits:je.name}),P(JSON.stringify({inherits:je.name},null,2))))},[f,G,o]);const X=w.useMemo(()=>{const je=W?.fields||[],Be=new Set(je.map($e=>$e.key)),Re=new Set,Ye=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);q&&Object.values(q).forEach($e=>{$e?.setting&&Object.keys($e.setting).forEach(De=>{!Be.has(De)&&!Ye.has(De)&&Re.add(De)})}),Object.keys(g).forEach($e=>{!Be.has($e)&&!Ye.has($e)&&Re.add($e)});const we=Array.from(Re).sort().map($e=>({key:$e,label:$e.replace(/_/g," ").replace(/\b\w/g,De=>De.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...je,...we]},[W,q,g,r]),V=X.filter(je=>je.label.toLowerCase().includes(T.toLowerCase())||je.key.toLowerCase().includes(T.toLowerCase())),J=()=>{if($.trim()){const je=$.trim().toLowerCase().replace(/\s+/g,"_");ie(je,""),I(""),L(!1),i(r("profiles.presets.toast.fieldAdded",{key:je}))}},ie=(je,Be)=>{_(Re=>{const Ye={...Re};return Be===""||Be===void 0?delete Ye[je]:Ye[je]=Be,Ye})},me=je=>{_(Be=>({...Be,...je.settings})),B(je.name),i(r("profiles.templates.toast.applied"))},pe=()=>{if(!le.trim())return;const je={...g};if(delete je.inherits,Object.keys(je).length===0){i(r("profiles.presets.noOverridesToSave"),"error");return}const Be={id:Date.now().toString(),name:le.trim(),description:K.trim()||r("profiles.presets.customTemplate"),type:d,settings:je,showInModal:se},Re=[...re,Be];ae(Re),hle(Re),ue(!1),de(""),te(""),be(!0),i(r("profiles.templates.toast.created"))},oe=w.useMemo(()=>re.filter(je=>je.type===d&&je.showInModal),[d,re]),U=je=>{P(je);try{const Be=JSON.parse(je);_(Be),M(null)}catch(Be){M(Be.message)}},R=je=>{je.preventDefault(),F(!1);const Be=je.dataTransfer.files[0];if(Be&&Be.name.endsWith(".json")){const Re=new FileReader;Re.onload=Ye=>{try{const we=Ye.target?.result,$e=JSON.parse(we),De=$e.setting||$e;_(Xe=>({...Xe,...De})),P(JSON.stringify({...g,...De},null,2)),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJsonFile"),"error")}},Re.readAsText(Be)}},ne=lt({mutationFn:()=>{const je={...g},Be=d==="filament"?"filament_settings_id":d==="print"?"print_settings_id":"printer_settings_id";je[Be]=`"${m}"`;const Re={type:d,name:m,base_id:f,setting:je};return he.createCloudSetting(Re)},onSuccess:async()=>{i(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:je=>i(je.message,"error")}),xe=lt({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return he.updateCloudSetting(e.setting_id,{name:m,setting:g})},onSuccess:async()=>{i(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:je=>i(je.message,"error")}),Se=o?xe:ne,ye=ce?.setting?.inherits,ve=ye?G.find(je=>je.name===ye):void 0,{data:fe}=et({queryKey:["cloudSettingDetail",ve?.setting_id],queryFn:()=>he.getCloudSettingDetail(ve.setting_id),enabled:!!ve?.setting_id}),ke=w.useMemo(()=>{const je=fe?.setting||{},Be=ce?.setting||{},Re=f&&q?.[f]?.setting?q[f].setting:{};return{...je,...Be,...Re}},[f,ce,fe,q]),Ee=je=>{if(je==null)return"";if(Array.isArray(je)){const Be=[...new Set(je.map(Re=>String(Re)))];return Be.length===1?Be[0]:je.join(", ")}return String(je)},Ae=je=>{const Be=g[je.key],Re=ke[je.key],Ye=Ee(Re),we=O?r("common.loading"):Ye||"",$e="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(je.type==="boolean"){const De=Be==="1"||Be===void 0&&Re==="1";return a.jsx("button",{type:"button",onClick:()=>ie(je.key,Be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${De?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${De?"translate-x-3.5":"translate-x-0.5"}`})})}return je.type==="select"?a.jsxs("select",{value:Be||"",onChange:De=>ie(je.key,De.target.value),className:$e,children:[a.jsx("option",{value:"",children:we}),je.options?.map(De=>a.jsx("option",{value:De.value,children:De.label},De.value))]}):a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:je.type==="number"?"number":"text",value:Be!==void 0?String(Be):"",onChange:De=>ie(je.key,De.target.value),step:je.step,min:je.min,max:je.max,placeholder:we,className:$e}),je.unit&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:je.unit})]})},_e=w.useMemo(()=>ce?.setting?ce.setting:{},[ce]);return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:je=>{je.preventDefault(),F(!0)},onDragLeave:()=>F(!1),onDrop:R,children:[Y&&f&&a.jsx(ple,{onClose:()=>D(!1),leftPreset:_e,rightPreset:g,leftLabel:r("profiles.presets.baseLabel",{name:v||f}),rightLabel:r("profiles.presets.currentLabel",{name:m||r("profiles.presets.newPreset")}),t:r}),a.jsx(Dt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:a.jsxs(Rt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[f&&a.jsxs("button",{onClick:()=>D(!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:r("profiles.presets.compareWithBase"),children:[a.jsx(tx,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),a.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]})]}),C&&a.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:a.jsxs("div",{className:"text-center",children:[a.jsx(Ca,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),a.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),a.jsxs("select",{value:d,onChange:je=>{u(je.target.value),y("")},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:[a.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),a.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),a.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),a.jsxs("select",{value:f,onChange:je=>y(je.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:[a.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),G.map(je=>a.jsx("option",{value:je.setting_id,children:je.name},je.setting_id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),a.jsx("input",{type:"text",value:m,onChange:je=>p(je.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:r("profiles.presets.myCustomPreset")})]})]}),v&&a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("p",{className:"flex items-center gap-1",children:[a.jsx(Kr,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",a.jsx("span",{className:"text-white",children:v}),O&&a.jsx(ct,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[a.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:[a.jsx(m6,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),a.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:[a.jsx(Ew,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),a.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:[a.jsx(ey,{className:"w-4 h-4"}),"JSON",N&&a.jsx(qa,{className:"w-3 h-3 text-red-400"})]}),a.jsx("div",{className:"flex-1 max-[640px]:hidden"}),a.jsxs("button",{onClick:()=>{const je={name:m,type:d,base_id:f,setting:g},Be=new Blob([JSON.stringify(je,null,2)],{type:"application/json"}),Re=URL.createObjectURL(Be),Ye=document.createElement("a");Ye.href=Re,Ye.download=`${m||"preset"}.json`,document.body.appendChild(Ye),Ye.click(),document.body.removeChild(Ye),URL.revokeObjectURL(Re),i(r("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:r("profiles.presets.exportToJson"),children:[a.jsx(va,{className:"w-4 h-4"}),r("common.download")]}),a.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:r("profiles.presets.importFromJson"),children:[a.jsx(Ca,{className:"w-4 h-4"}),r("common.upload")]}),a.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:je=>{const Be=je.target.files?.[0];if(Be){const Re=new FileReader;Re.onload=Ye=>{try{const we=JSON.parse(Ye.target?.result),$e=we.setting||we;_(De=>({...De,...$e})),i(r("profiles.presets.fileImported"))}catch{i(r("profiles.presets.invalidJson"),"error")}},Re.readAsText(Be)}}})]}),a.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(wx,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(g).filter(je=>je!=="inherits").length>0&&a.jsxs("button",{onClick:()=>ue(!ee),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[a.jsx(cs,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),ee&&a.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[a.jsx("input",{type:"text",value:le,onChange:je=>de(je.target.value),placeholder:r("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}),a.jsx("input",{type:"text",value:K,onChange:je=>te(je.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{size:"sm",onClick:pe,disabled:!le.trim(),children:[a.jsx(cs,{className:"w-3 h-3"}),r("common.save")]}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>ue(!1),children:r("common.cancel")})]}),a.jsxs("button",{onClick:()=>be(!se),className:`flex items-center gap-1.5 text-xs transition-colors ${se?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[se?a.jsx(Dc,{className:"w-3.5 h-3.5"}):a.jsx(Tw,{className:"w-3.5 h-3.5"}),r(se?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),Ne&&a.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:[a.jsx(Kr,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",a.jsx("span",{className:"font-medium",children:Ne})]}),a.jsx("button",{onClick:()=>B(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[oe.map(je=>a.jsxs("button",{onClick:()=>me(je),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:je.name}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:je.description})]},je.id)),oe.length===0&&a.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),a.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),a.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:X.slice(0,10).map(je=>a.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[a.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:je.label}),a.jsx("div",{className:"w-48 max-[640px]:w-full",children:Ae(je)})]},je.key))})]}),Object.keys(g).length>1&&a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(g).filter(([je])=>je!=="inherits").map(([je,Be])=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[je,": ",String(Be).slice(0,20),a.jsx("button",{onClick:()=>ie(je,void 0),className:"hover:text-white",children:a.jsx(Bt,{className:"w-3 h-3"})})]},je))})]})]}),l==="fields"&&a.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:q?r("profiles.templates.fieldsCount",{count:X.length}):r("common.loading")})]}),a.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:T,onChange:je=>A(je.target.value),placeholder:r("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"})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[V.filter(je=>!(je.key in g)).map(je=>{const Be=ke[je.key],Re=Ee(Be);return a.jsxs("div",{onClick:()=>{_(Ye=>({...Ye,[je.key]:Re||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white truncate",children:je.label}),a.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:je.key})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[Re&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:Re,children:[Re.slice(0,20),Re.length>20?"...":""]}),a.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:a.jsx(ur,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},je.key)}),V.filter(je=>!(je.key in g)).length===0&&a.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(T?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:Q?a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:$,onChange:je=>I(je.target.value),onKeyDown:je=>je.key==="Enter"&&J(),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}),a.jsx(Ie,{size:"sm",onClick:J,disabled:!$.trim(),children:a.jsx(ur,{className:"w-4 h-4"})}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>{L(!1),I("")},children:a.jsx(Bt,{className:"w-4 h-4"})})]}):a.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:[a.jsx(ur,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),a.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[a.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),a.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(g).filter(je=>je!=="inherits").length})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(g).filter(([je])=>je!=="inherits").map(([je,Be])=>{const Re=X.find(Ye=>Ye.key===je);return a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm font-medium text-white",children:Re?.label||je}),a.jsx("p",{className:"text-xs text-bambu-gray-dark",children:je})]}),a.jsx("button",{onClick:()=>ie(je,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:a.jsx(Bt,{className:"w-4 h-4"})})]}),Re?Ae(Re):a.jsx("input",{type:"text",value:String(Be),onChange:Ye=>ie(je,Ye.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"})]},je)}),Object.keys(g).filter(je=>je!=="inherits").length===0&&a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(m6,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),a.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(g).filter(je=>je!=="inherits").length>0&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:a.jsxs("button",{onClick:()=>{ue(!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:[a.jsx(cs,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&a.jsxs("div",{className:"space-y-2",children:[N&&a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(qa,{className:"w-4 h-4"}),N]}),a.jsx("textarea",{value:k,onChange:je=>U(je.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 ${N?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsxs(Ie,{onClick:()=>Se.mutate(),disabled:Se.isPending||!m.trim()||!o&&!f||!!N,className:"flex-1",children:[Se.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o?a.jsx(cs,{className:"w-4 h-4"}):a.jsx(ur,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function ent({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:i,hasPermission:s,t:o}){const[l,c]=w.useState(""),[d,u]=w.useState("all"),[m,p]=w.useState("all"),[f,y]=w.useState("all"),[v,b]=w.useState("all"),[g,_]=w.useState("all"),[k,P]=w.useState("all"),[N,M]=w.useState(null),[T,A]=w.useState(!1),[C,F]=w.useState(!1),[$,I]=w.useState(null),[Q,L]=w.useState(null),[re,ae]=w.useState(null),[ee,ue]=w.useState(!1),[le,de]=w.useState([null,null]),[K,te]=w.useState(!1),[se,be]=w.useState(null),Ne=mn(),B=w.useMemo(()=>[...t.filament.map(J=>({...J,type:"filament"})),...t.printer.map(J=>({...J,type:"printer"})),...t.process.map(J=>({...J,type:"process"}))].map(J=>({...J,meta:Kz(J.name)})),[t]),Y=w.useMemo(()=>{const V=new Set,J=new Set,ie=new Set;return B.forEach(me=>{me.meta.nozzle&&V.add(me.meta.nozzle),me.meta.filamentType&&J.add(me.meta.filamentType),me.meta.layerHeight&&ie.add(me.meta.layerHeight)}),{printers:i.map(me=>({id:me.id.toString(),name:me.name})),nozzles:Array.from(V).sort((me,pe)=>parseFloat(me)-parseFloat(pe)),filaments:Array.from(J).sort(),layerHeights:Array.from(ie).sort((me,pe)=>parseFloat(me)-parseFloat(pe))}},[B,i]),D=w.useMemo(()=>f==="all"?null:i.find(J=>J.id.toString()===f)?.model||null,[f,i]),j=w.useMemo(()=>B.filter(V=>d==="all"||V.type===d).filter(V=>{if(m==="all")return!0;const J=kw(V.setting_id);return m==="custom"?J:!J}).filter(V=>{if(f==="all"||!D)return!0;const J=V.meta.printer?.toLowerCase()||"",ie=D.toLowerCase();return J.includes(ie)||ie.includes(J)}).filter(V=>v==="all"||V.meta.nozzle===v).filter(V=>g==="all"||V.meta.filamentType===g).filter(V=>k==="all"||V.meta.layerHeight===k).filter(V=>l===""||V.name.toLowerCase().includes(l.toLowerCase())).sort((V,J)=>V.name.localeCompare(J.name)),[B,d,m,f,D,v,g,k,l]),z=V=>{if(ee){const J=le[0]?.setting_id===V.setting_id,ie=le[1]?.setting_id===V.setting_id;if(J)de([le[1],null]);else if(ie)de([le[0],null]);else if(!le[0])de([V,null]);else if(le[1]){if(le[0].type!==V.type)return;de([le[0],V])}else{if(le[0].type!==V.type)return;de([le[0],V])}}else M(V)},W=V=>{if(le[0]?.setting_id===V.setting_id)return 0;if(le[1]?.setting_id===V.setting_id)return 1},q=async V=>{try{const J=await he.getCloudSettingDetail(V.setting_id),ie=V.type==="process"?"print":V.type;I({type:ie,name:V.name,base_id:J.base_id||"GFSA00",setting:J.setting||{}}),M(null)}catch(J){console.error("Failed to fetch preset details for duplication:",J)}},ce=async V=>{try{Ne.removeQueries({queryKey:["cloudSettingDetail",V.setting_id]});const J=await he.getCloudSettingDetail(V.setting_id),ie=V.type==="process"?"print":V.type;L({type:ie,name:V.name,base_id:J.base_id||"GFSA00",setting:J.setting||{},setting_id:V.setting_id}),M(null)}catch(J){console.error("Failed to fetch preset details for editing:",J)}},O=()=>{u("all"),p("all"),y("all"),b("all"),_("all"),P("all"),c("")},G=d!=="all"||m!=="all"||f!=="all"||v!=="all"||g!=="all"||k!=="all"||l!=="",X=t.filament.length+t.printer.length+t.process.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"space-y-4 mb-6",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:l,onChange:V=>c(V.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"})]}),a.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[a.jsxs(Ie,{variant:ee?"primary":"secondary",onClick:()=>{ee?(ue(!1),de([null,null])):ue(!0)},children:[a.jsx(tx,{className:"w-4 h-4"}),o(ee?"common.cancel":"profiles.presets.compare")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>F(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[a.jsx(wx,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),a.jsxs(Ie,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[a.jsx(vr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),a.jsxs(Ie,{onClick:()=>A(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),a.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a.jsx(kP,{className:"w-4 h-4 text-bambu-gray"}),a.jsx(Lb,{label:o("profiles.cloudView.filters.type"),value:d,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:X},{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:V=>u(V)}),a.jsx(Lb,{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:V=>p(V)}),Y.printers.length>0&&a.jsx(Lb,{label:o("profiles.cloudView.filters.printer"),value:f,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.printers.map(V=>({value:V.id,label:V.name}))],onChange:y}),Y.nozzles.length>0&&a.jsx(Lb,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.nozzles.map(V=>({value:V,label:V}))],onChange:b}),Y.filaments.length>0&&(d==="all"||d==="filament")&&a.jsx(Lb,{label:o("profiles.cloudView.filters.filament"),value:g,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.filaments.map(V=>({value:V,label:V}))],onChange:_}),Y.layerHeights.length>0&&(d==="all"||d==="process")&&a.jsx(Lb,{label:o("profiles.cloudView.filters.layer"),value:k,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...Y.layerHeights.map(V=>({value:V,label:V}))],onChange:P}),G&&a.jsx("button",{onClick:O,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),ee&&a.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(tx,{className:"w-5 h-5 text-blue-400"}),a.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),a.jsx("span",{className:"text-bambu-gray",children:le[0]?o("profiles.cloudView.selectAnotherPreset",{type:le[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[0]?le[0].name:o("profiles.cloudView.selectFirst")}),a.jsx(O3,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${le[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:le[1]?le[1].name:o("profiles.cloudView.selectSecond")})]}),le[0]&&le[1]&&a.jsxs(Ie,{size:"sm",onClick:async()=>{try{const[V,J]=await Promise.all([he.getCloudSettingDetail(le[0].setting_id),he.getCloudSettingDetail(le[1].setting_id)]);be([V.setting||{},J.setting||{}]),te(!0)}catch{}},children:[a.jsx(tx,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),a.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",Sx(e.toISOString(),"system",o)]}),a.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:j.length,total:X})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),a.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),j.length===0?a.jsxs("div",{className:"text-center py-16",children:[a.jsx(ea,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),a.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),G&&a.jsx("button",{onClick:O,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(SP,{className:"w-4 h-4 text-amber-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="filament").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="filament").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="filament").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Nd,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="process").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="process").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="process").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[a.jsx(Pr,{className:"w-4 h-4 text-purple-400"}),a.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",j.filter(V=>V.type==="printer").length,")"]})]}),a.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[j.filter(V=>V.type==="printer").map(V=>a.jsx(d3,{setting:V,onClick:()=>z(V),onDuplicate:()=>q(V),compareMode:ee,isCompareSelected:W(V)!==void 0,compareIndex:W(V),compareDisabled:ee&&!!le[0]&&le[0].type!==V.type,t:o},V.setting_id)),j.filter(V=>V.type==="printer").length===0&&a.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),N&&a.jsx(Qtt,{setting:N,onClose:()=>M(null),onDeleted:()=>M(null),onDuplicate:()=>q(N),onEdit:()=>ce(N),hasPermission:s,t:o}),(T||$||Q||re)&&a.jsx(Jtt,{onClose:()=>{A(!1),I(null),L(null),ae(null)},initialData:Q||$||(re?{type:re.type,name:"",base_id:"",setting:re.setting}:void 0),allPresets:t,t:o}),C&&a.jsx(Ztt,{onClose:()=>F(!1),onApply:V=>{ae({type:V.type,setting:V.settings}),F(!1)},t:o}),K&&se&&le[0]&&le[1]&&a.jsx(ple,{onClose:()=>{te(!1),be(null)},leftPreset:se[0],rightPreset:se[1],leftLabel:le[0].name,rightLabel:le[1].name,t:o})]})}function tnt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=Sr(),[i,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:d}=et({queryKey:["cloudStatus"],queryFn:he.getCloudStatus}),{data:u=[]}=et({queryKey:["printers"],queryFn:he.getPrinters}),{data:m,isLoading:p,refetch:f,dataUpdatedAt:y}=et({queryKey:["cloudSettings"],queryFn:()=>he.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{y&&l(new Date(y))},[y]);const v=lt({mutationFn:he.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),b=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return d?a.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-6 lg:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[a.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:[a.jsx(Jx,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),a.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:[a.jsx(ty,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),a.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:[a.jsx(Aw,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),i==="cloud"&&a.jsxs(a.Fragment,{children:[c?.is_authenticated&&a.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",a.jsx("span",{className:"text-white",children:c.email})]})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[a.jsx(B3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):m?a.jsx(ent,{settings:m,lastSyncTime:o,onRefresh:()=>f(),isRefreshing:p,printers:u,hasPermission:r,t}):a.jsxs("div",{className:"text-center py-16",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),a.jsx(Ie,{onClick:()=>f(),children:t("profiles.retry")})]}):a.jsx(Ytt,{onSuccess:b,t})]}),i==="local"&&a.jsx(Ktt,{}),i==="kprofiles"&&a.jsx($tt,{}),a.jsx(Xtt,{})]})}const r0={Droplet:SP,Flame:Qp,Ruler:bbe,Sparkles:wx,Square:eo,Cable:cO,Wrench:zf,Calendar:Wr,Timer:Pc,Cog:rfe,Fan:hQ,Zap:Xl,Wind:PQ,Thermometer:PP,Layers:ea,Box:si,Target:_Q,RefreshCw:vr,Settings:Ow,Filter:kP,CircleDot:Ipe};function A0(t){return t&&r0[t]||zf}function Ob(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const i=Math.round(t);return n?n("maintenance.days",{count:i}):`${i} days`}if(t<180){const i=Math.round(t/7);return i===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:i}):`${i} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} 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 r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const i=r/7;return i<12?`${i<2?i.toFixed(1):Math.round(i)}w`:`${Math.round(i/4)}mo`}}function u3(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function nnt(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),i=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),d=n.includes("H2S"),u=l||c||d,m=n.includes("P2S");switch(t){case"Lubricate Steel Rods":return m?"https://wiki.bambulab.com/en/p2s/maintenance/lubricate-x-y-z-axis":null;case"Clean Steel Rods":return m?"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 r||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":m?"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 r?"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":m?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||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 r||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}}function rnt({item:t,onPerform:e,onToggle:n,hasPermission:r,t:i}){const s=A0(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:Ob(Math.abs(f),"days",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ob(f,"days",i)}):i("maintenance.timeLeft",{duration:Ob(f,"days",i)})}else return t.is_due?i("maintenance.overdueBy",{duration:Ob(Math.abs(t.hours_until_due),"hours",i)}):t.is_warning?i("maintenance.dueIn",{duration:Ob(t.hours_until_due,"hours",i)}):i("maintenance.timeLeft",{duration:Ob(t.hours_until_due,"hours",i)})};return a.jsx("div",{className:`rounded-xl border p-4 transition-all ${m()}`,children:a.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[a.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:[a.jsx(s,{className:`w-5 h-5 ${d()}`}),t.enabled&&(t.is_due||t.is_warning)&&a.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`})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&a.jsx("span",{title:i("maintenance.timeBasedInterval"),children:a.jsx(Wr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const f=t.maintenance_type_wiki_url||nnt(t.maintenance_type_name,t.printer_model);return f?a.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:y=>y.stopPropagation(),children:a.jsx(sa,{className:"w-3.5 h-3.5"})}):null})()]}),a.jsx("div",{className:"mt-2 mb-1.5",children:a.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${u()}`,style:{width:`${c}%`}})})}),a.jsxs("div",{className:`text-xs flex items-center gap-1 ${d()}`,children:[t.is_due&&a.jsx(Ln,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&a.jsx(rr,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&a.jsx(Kr,{className:"w-3 h-3"}),p()]})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[a.jsx("span",{title:r("maintenance:update")?void 0:i("maintenance.noPermissionUpdate"),children:a.jsx(Vn,{checked:t.enabled,onChange:f=>n(t.id,f),disabled:!r("maintenance:update")})}),a.jsxs(Ie,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:i("maintenance.noPermissionPerform"),className:"!px-3",children:[a.jsx(jo,{className:"w-3.5 h-3.5"}),i("common.reset")]})]})]})})}function ant({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:i,t:s}){const[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.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)),y=()=>{const v=parseFloat(u);!isNaN(v)&&v>=0&&(r(t.printer_id,v),d(!1))};return a.jsxs(Dt,{className:"overflow-hidden",children:[a.jsxs("div",{className:"p-5",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),a.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&a.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:[a.jsx(Ln,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&a.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:[a.jsx(rr,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&a.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:[a.jsx(Kr,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),a.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?a.jsx(Yl,{className:"w-4 h-4"}):a.jsx(Fn,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),a.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:a.jsx(Pc,{className:"w-4 h-4 text-bambu-gray"})}),c?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",value:u,onChange:v=>m(v.target.value),onKeyDown:v=>{v.key==="Enter"&&y(),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}),a.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),a.jsx(Ie,{size:"sm",onClick:y,children:s("common.save")}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>d(!1),children:s("common.cancel")})]}):a.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:[a.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"),a.jsx(Of,{className:`w-3 h-3 text-bambu-gray ${i("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),a.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),f&&a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=A0(f.maintenance_type_icon);return a.jsx(v,{className:`w-4 h-4 ${f.is_due?"text-red-400":"text-amber-400"}`})})()}),a.jsxs("div",{children:[a.jsx("div",{className:`text-sm font-medium ${f.is_due?"text-red-400":"text-amber-400"}`,children:f.maintenance_type_name}),a.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&&a.jsx(Rt,{className:"pt-0 border-t border-bambu-dark-tertiary",children:a.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:p.map(v=>a.jsx(rnt,{item:v,onPerform:e,onToggle:n,hasPermission:i,t:s},v.id))})})]})}function int({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:i,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:d,hasPermission:u,t:m}){const[p,f]=w.useState(null),[y,v]=w.useState(""),[b,g]=w.useState("hours"),[_,k]=w.useState(!1),[P,N]=w.useState(""),[M,T]=w.useState("100"),[A,C]=w.useState("hours"),[F,$]=w.useState("Wrench"),[I,Q]=w.useState(""),[L,re]=w.useState(new Set),[ae,ee]=w.useState(null),[ue,le]=w.useState(null),de=w.useMemo(()=>t?t.map(U=>({id:U.printer_id,name:U.printer_name})):[],[t]),K=U=>t?t.filter(R=>R.maintenance_items.some(ne=>ne.maintenance_type_id===U)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(ne=>ne.maintenance_type_id===U)?.id})):[],te=U=>{if(!t)return[];const R=new Set(K(U).map(ne=>ne.printerId));return de.filter(ne=>!R.has(ne.id))},[se,be]=w.useState(null),[Ne,B]=w.useState(""),[Y,D]=w.useState(""),[j,z]=w.useState("hours"),[W,q]=w.useState("Wrench"),[ce,O]=w.useState(""),G=U=>{be(U),B(U.name),D(U.default_interval_hours.toString()),z(U.interval_type||"hours"),q(U.icon||"Wrench"),O(U.wiki_url||"")},X=()=>{se&&Ne.trim()&&parseFloat(Y)>0&&(i(se.id,{name:Ne.trim(),default_interval_hours:parseFloat(Y),interval_type:j,icon:W,wiki_url:ce.trim()||null}),be(null))},V=(U,R,ne)=>{const xe=parseFloat(y);if(!isNaN(xe)&&xe>0){const Se=Math.abs(xe-R)<.01?null:xe;n(U,{custom_interval_hours:Se,custom_interval_type:b!==ne?b:null})}f(null)},J=U=>{U.preventDefault(),P.trim()&&parseFloat(M)>0&&L.size>0&&(r({name:P.trim(),default_interval_hours:parseFloat(M),interval_type:A,icon:F,wiki_url:I.trim()||null},Array.from(L)),N(""),T("100"),C("hours"),Q(""),re(new Set),k(!1))},ie=U=>{re(R=>{const ne=new Set(R);return ne.has(U)?ne.delete(U):ne.add(U),ne})},me=t?.map(U=>({printerId:U.printer_id,printerName:U.printer_name,items:U.maintenance_items.sort((R,ne)=>R.maintenance_type_id-ne.maintenance_type_id)})).sort((U,R)=>U.printerName.localeCompare(R.printerName))||[],pe=e.filter(U=>U.is_system),oe=e.filter(U=>!U.is_system);return a.jsxs("div",{className:"space-y-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.maintenanceTypes")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.maintenanceTypesDescription")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ie,{variant:"secondary",onClick:o,disabled:!u("maintenance:delete")||l,title:u("maintenance:delete")?void 0:m("maintenance.noPermissionDeleteTypes"),children:m("maintenance.restoreDefaults")}),a.jsxs(Ie,{onClick:()=>k(!_),disabled:!u("maintenance:create"),title:u("maintenance:create")?void 0:m("maintenance.noPermissionEditTypes"),children:[a.jsx(ur,{className:"w-4 h-4"}),m("maintenance.addCustomType")]})]})]}),_&&a.jsx(Dt,{className:"mb-6",children:a.jsx(Rt,{className:"py-4",children:a.jsxs("form",{onSubmit:J,children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"lg:col-span-2",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("common.name")}),a.jsx("input",{type:"text",value:P,onChange:U=>N(U.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalType")}),a.jsxs("select",{value:A,onChange:U=>{C(U.target.value),U.target.value==="days"?T("30"):T("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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.intervalValue",{type:A==="days"?m("maintenance.calendarDays").toLowerCase():m("common.hours")})}),a.jsx("input",{type:"number",value:M,onChange:U=>T(U.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"})]})]}),a.jsx("div",{className:"mt-4 flex items-end justify-between",children:a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.icon")}),a.jsx("div",{className:"flex gap-1",children:Object.keys(r0).map(U=>{const R=r0[U];return a.jsx("button",{type:"button",onClick:()=>$(U),className:`p-2 rounded-lg transition-colors ${F===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:a.jsx(R,{className:"w-4 h-4"})},U)})})]})}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.documentationLink")}),a.jsx("input",{type:"url",value:I,onChange:U=>Q(U.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/..."})]}),a.jsxs("div",{className:"mt-4",children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:m("maintenance.assignToPrinters")}),a.jsx("div",{className:"flex flex-wrap gap-2",children:de.map(U=>a.jsx("button",{type:"button",onClick:()=>ie(U.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${L.has(U.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:U.name},U.id))}),L.size===0&&a.jsx("p",{className:"text-xs text-orange-400 mt-1",children:m("maintenance.selectAtLeastOnePrinter")})]}),a.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:()=>{k(!1),re(new Set)},children:m("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!P.trim()||L.size===0,children:m("maintenance.addType")})]})]})})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[pe.map(U=>{const R=A0(U.icon),ne=U.interval_type||"hours";return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("div",{className:"text-sm font-medium text-white truncate",children:U.name}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(U.default_interval_hours,ne,m)]})]}),a.jsx("button",{onClick:()=>{u("maintenance:delete")&&le(U)},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:a.jsx(un,{className:"w-4 h-4"})})]})},U.id)}),oe.map(U=>{const R=A0(U.icon),ne=U.interval_type||"hours";if(se?.id===U.id)return a.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:a.jsxs("div",{className:"space-y-3",children:[a.jsx("input",{type:"text",value:Ne,onChange:fe=>B(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",placeholder:m("common.name"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:j,onChange:fe=>z(fe.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:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:Y,onChange:fe=>D(fe.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"})]}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(r0).map(fe=>{const ke=r0[fe];return a.jsx("button",{type:"button",onClick:()=>q(fe),className:`p-1.5 rounded transition-colors ${W===fe?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:a.jsx(ke,{className:"w-3.5 h-3.5"})},fe)})}),a.jsx("input",{type:"url",value:ce,onChange:fe=>O(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",placeholder:m("maintenance.documentationLink")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Ie,{size:"sm",onClick:X,disabled:!Ne.trim(),children:m("common.save")}),a.jsx(Ie,{size:"sm",variant:"secondary",onClick:()=>be(null),children:m("common.cancel")})]})]})},U.id);const Se=K(U.id),ye=te(U.id),ve=ae===U.id;return a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:a.jsx(R,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-white truncate",children:U.name}),a.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")})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[ne==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(U.default_interval_hours,ne,m)]})]}),a.jsxs("button",{onClick:()=>ee(ve?null:U.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${Se.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:Se.length}),children:[a.jsx(Pr,{className:"w-3 h-3"}),a.jsx("span",{className:"text-xs font-medium",children:Se.length}),a.jsx(Fn,{className:`w-3 h-3 transition-transform ${ve?"rotate-180":""}`})]}),a.jsx("button",{onClick:()=>G(U),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:a.jsx(Of,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{confirm(m("maintenance.deleteTypeConfirm",{name:U.name}))&&s(U.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:a.jsx(un,{className:"w-4 h-4"})})]}),ve&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:m("maintenance.assignedToPrinters")}),Se.length===0?a.jsx("p",{className:"text-xs text-orange-400",children:m("maintenance.noPrintersAssigned")}):a.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:Se.map(fe=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[fe.printerName,a.jsx("button",{onClick:()=>fe.itemId&&d(fe.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:"×"})]},fe.printerId))}),ye.length>0&&a.jsxs("div",{className:"flex flex-wrap gap-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:m("maintenance.addPrinterShort")}),ye.map(fe=>a.jsxs("button",{onClick:()=>c(fe.id,U.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:["+ ",fe.name]},fe.id))]})]})]},U.id)})]})]}),me.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"mb-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:m("maintenance.intervalOverrides")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:m("maintenance.intervalOverridesDescription")})]}),a.jsx("div",{className:"space-y-4",children:me.map(U=>a.jsx(Dt,{children:a.jsxs(Rt,{className:"py-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:U.printerName}),a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:U.items.map(R=>{const ne=A0(R.maintenance_type_icon),xe=e.find(ke=>ke.id===R.maintenance_type_id),Se=xe?.default_interval_hours||R.interval_hours,ye=xe?.interval_type||"hours",ve=R.interval_type||"hours",fe=p===R.id;return a.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[a.jsx(ne,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),fe?a.jsxs("div",{className:"flex items-center gap-1",children:[b==="days"?a.jsx(Wr,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):a.jsx(Pc,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),a.jsxs("select",{value:b,onChange:ke=>g(ke.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[a.jsx("option",{value:"hours",children:m("maintenance.printHours")}),a.jsx("option",{value:"days",children:m("maintenance.calendarDays")})]}),a.jsx("input",{type:"number",value:y,onChange:ke=>v(ke.target.value),onKeyDown:ke=>{ke.key==="Enter"&&V(R.id,Se,ye),ke.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"}),a.jsx(Ie,{size:"sm",onClick:()=>V(R.id,Se,ye),children:"OK"})]}):a.jsxs("button",{onClick:()=>{u("maintenance:update")&&(f(R.id),v(R.interval_hours.toString()),g(ve))},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:[ve==="days"?a.jsx(Wr,{className:"w-3 h-3"}):a.jsx(Pc,{className:"w-3 h-3"}),u3(R.interval_hours,ve,m),a.jsx(Of,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},U.printerId))})]}),me.length===0&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-12",children:[a.jsx(rr,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-bambu-gray",children:m("common.noPrinters")}),a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:m("maintenance.intervalOverridesDescription")})]})}),ue&&a.jsx(kn,{title:m("maintenance.deleteSystemTypeTitle"),message:m("maintenance.deleteSystemTypeMessage",{name:ue.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(ue.id),le(null)},onCancel:()=>le(null)})]})}function snt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=Sr(),[i,s]=w.useState("status"),{data:o,isLoading:l}=et({queryKey:["maintenanceOverview"],queryFn:he.getMaintenanceOverview}),{data:c}=et({queryKey:["maintenanceTypes"],queryFn:he.getMaintenanceTypes}),d=lt({mutationFn:({id:M,notes:T})=>he.performMaintenance(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),u=lt({mutationFn:({id:M,data:T})=>he.updateMaintenanceItem(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),m=lt({mutationFn:({id:M,data:T})=>he.updateMaintenanceType(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),p=lt({mutationFn:he.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),f=lt({mutationFn:he.restoreDefaultMaintenanceTypes,onSuccess:M=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:M.restored}))},onError:M=>{n(M.message,"error")}}),y=lt({mutationFn:({printerId:M,hours:T})=>he.setPrinterHours(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),v=lt({mutationFn:({printerId:M,typeId:T})=>he.assignMaintenanceType(M,T),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),b=lt({mutationFn:he.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),g=M=>{d.mutate({id:M})},_=(M,T)=>{u.mutate({id:M,data:{enabled:T}})},k=(M,T)=>{y.mutate({printerId:M,hours:T})};if(l)return a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})});const P=o?.reduce((M,T)=>M+T.due_count,0)||0,N=o?.reduce((M,T)=>M+T.warning_count,0)||0;return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-6",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:i==="status"?a.jsxs(a.Fragment,{children:[P>0&&a.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:P})}),P>0&&N>0&&" · ",N>0&&a.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:N})}),P===0&&N===0&&a.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),a.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.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")}),a.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"?a.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((M,T)=>{const A=M.due_count*10+M.warning_count,C=T.due_count*10+T.warning_count;return A!==C?C-A:M.printer_name.localeCompare(T.printer_name)}).map(M=>a.jsx(ant,{overview:M,onPerform:g,onToggle:_,onSetHours:k,hasPermission:r,t},M.printer_id)):a.jsx(Dt,{children:a.jsxs(Rt,{className:"text-center py-16",children:[a.jsx(zf,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):a.jsx(int,{overview:o,types:c||[],onUpdateInterval:(M,T)=>u.mutate({id:M,data:T}),onAddType:async(M,T)=>{const A=await he.createMaintenanceType(M);for(const C of T)await he.assignMaintenanceType(C,A.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,T)=>m.mutate({id:M,data:T}),onDeleteType:M=>p.mutate(M),onRestoreDefaults:()=>f.mutate(),isRestoringDefaults:f.isPending,onAssignType:(M,T)=>v.mutate({printerId:M,typeId:T}),onRemoveItem:M=>b.mutate(M),hasPermission:r,t})]})}const tX=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function fle({project:t,onClose:e,onSave:n,isLoading:r,currencySymbol:i,t:s}){const[o,l]=w.useState(t?.name||""),[c,d]=w.useState(t?.description||""),[u,m]=w.useState(t?.color||tX[0]),[p,f]=w.useState(t?.target_count?.toString()||""),[y,v]=w.useState(t?.target_parts_count?.toString()||""),[b,g]=w.useState(t?.status||"active"),[_,k]=w.useState(t?.tags||""),[P,N]=w.useState(t?.due_date?.split("T")[0]||""),[M,T]=w.useState(t?.priority||"normal"),[A,C]=w.useState(t?.budget?.toString()||""),F=$=>{$.preventDefault(),n({name:o.trim(),description:c.trim()||void 0,color:u,target_count:p?parseInt(p,10):void 0,target_parts_count:y?parseInt(y,10):void 0,tags:_.trim()||void 0,due_date:P||void 0,priority:M,budget:A.trim()?parseFloat(A):null,...t&&{status:b}})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t?"projects.editProject":"projects.newProject")})}),a.jsxs("form",{onSubmit:F,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsx("input",{type:"text",value:o,onChange:$=>l($.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.description")}),a.jsx("textarea",{value:c,onChange:$=>d($.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})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.color")}),a.jsx("div",{className:"flex gap-2 flex-wrap",children:tX.map($=>a.jsx("button",{type:"button",onClick:()=>m($),className:`w-8 h-8 rounded-full transition-transform ${u===$?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:$}},$))})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetPlates")}),a.jsx("input",{type:"number",value:p,onChange:$=>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:s("projects.targetPlatesPlaceholder"),min:"1"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPlatesHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.targetParts")}),a.jsx("input",{type:"number",value:y,onChange:$=>v($.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:s("projects.targetPartsHelp")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.tagsLabel")}),a.jsx("input",{type:"text",value:_,onChange:$=>k($.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")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.dueDate")}),a.jsx("input",{type:"date",value:P,onChange:$=>N($.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"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projects.priority")}),a.jsxs("select",{value:M,onChange:$=>T($.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:[a.jsx("option",{value:"low",children:s("projects.priorityLow")}),a.jsx("option",{value:"normal",children:s("projects.priorityNormal")}),a.jsx("option",{value:"high",children:s("projects.priorityHigh")}),a.jsx("option",{value:"urgent",children:s("projects.priorityUrgent")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("projectDetail.cost.budget")}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray pointer-events-none",children:i}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:A,onChange:$=>C($.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&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.status")}),a.jsxs("select",{value:b,onChange:$=>g($.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:[a.jsx("option",{value:"active",children:s("projects.statusActive")}),a.jsx("option",{value:"completed",children:s("projects.statusCompleted")}),a.jsx("option",{value:"archived",children:s("projects.statusArchived")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:s("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!o.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s(t?"common.save":"projects.create")})]})]})]})})}function ont({project:t,onClick:e,onEdit:n,onDelete:r,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]=w.useState(!1),f=c?{icon:Cc,color:"text-bambu-green",bg:"bg-bambu-green/10"}:d?{icon:Qs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:rr,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:js,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return a.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:[a.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`}}),a.jsxs("div",{className:"p-5 pl-6",children:[a.jsxs("div",{className:"flex items-start justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg ${f.bg} flex-shrink-0`,children:a.jsx(f.icon,{className:`w-5 h-5 ${f.color}`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?a.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?a.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?a.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&&a.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&&a.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&&a.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const y=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(k=>k.trim())).filter(Boolean),v=[...new Set(y)],b=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(k=>k.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),g=[...new Set(b)];return v.length===0&&g.length===0?null:a.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>a.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),g.length>0&&a.jsxs("div",{className:"flex items-center gap-0.5",children:[g.slice(0,5).map(_=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),g.length>5&&a.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",g.length-5]})]})]})})()]})]}),a.jsxs("div",{className:"relative",onClick:y=>y.stopPropagation(),children:[a.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:a.jsx(Ah,{className:"w-4 h-4"})}),u&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>m(!1)}),a.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:[a.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")&&(n(),m(!1))},disabled:!i("projects:update"),title:i("projects:update")?void 0:s("projects.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4"}),s("common.edit")]}),a.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")&&(r(),m(!1))},disabled:!i("projects:delete"),title:i("projects:delete")?void 0:s("projects.noDeletePermission"),children:[a.jsx(un,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),a.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?a.jsxs("div",{className:"space-y-3",children:[t.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),a.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[a.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),a.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:a.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&&a.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?a.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[a.jsx(Qs,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),a.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):a.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&a.jsxs("div",{className:"mb-4",children:[a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(y=>a.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:y.print_name||"Unknown",children:[y.thumbnail_path?a.jsx("img",{src:he.getArchiveThumbnail(y.id),alt:y.print_name||"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:a.jsx(Na,{className:"w-6 h-6"})}),y.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:a.jsx(Ln,{className:"w-4 h-4 text-white"})})]},y.id))}),t.archive_count>4&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),a.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[a.jsx(ea,{className:"w-3.5 h-3.5 text-blue-400"}),a.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),a.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[a.jsx(Na,{className:"w-3.5 h-3.5 text-bambu-green"}),a.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[a.jsx(Ln,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&a.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[a.jsx(U3,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:t.queue_count})]})]}),a.jsx(Va,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function lnt(){const{t}=Lt(),e=Eo(),n=mn(),{showToast:r}=xn(),{hasPermission:i}=Sr(),[s,o]=w.useState(!1),[l,c]=w.useState(),[d,u]=w.useState("active"),[m,p]=w.useState(null),{data:f}=et({queryKey:["settings"],queryFn:he.getSettings}),y=yo(f?.currency||"USD"),{data:v,isLoading:b}=et({queryKey:["projects",d==="all"?void 0:d],queryFn:()=>he.getProjects(d==="all"?void 0:d)}),g=lt({mutationFn:re=>he.createProject(re),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:re=>{r(re.message,"error")}}),_=lt({mutationFn:({id:re,data:ae})=>he.updateProject(re,ae),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:re=>{r(re.message,"error")}}),k=lt({mutationFn:re=>he.deleteProject(re),onSuccess:()=>{p(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:re=>{p(null),r(re.message,"error")}}),P=lt({mutationFn:re=>he.importProject(re),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:re=>{r(re.message,"error")}}),N=w.useRef(null),M=async()=>{try{const re=await he.getProjects(),ae=await Promise.all(re.map(async de=>await he.exportProjectJson(de.id))),ee=new Blob([JSON.stringify(ae,null,2)],{type:"application/json"}),ue=URL.createObjectURL(ee),le=document.createElement("a");le.href=ue,le.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,le.click(),URL.revokeObjectURL(ue),r(t("projects.toast.exported"),"success")}catch(re){r(re.message,"error")}},T=()=>{N.current?.click()},A=async re=>{const ae=re.target.files?.[0];if(ae){try{if(ae.name.toLowerCase().endsWith(".zip"))await he.importProjectFile(ae),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const ue=await ae.text(),le=JSON.parse(ue),de=Array.isArray(le)?le:[le];for(const K of de)await P.mutateAsync(K);de.length>1&&r(t("projects.toast.multipleImported",{count:de.length}),"success")}}catch(ee){r(`${t("projects.toast.importFailed")}: ${ee.message}`,"error")}re.target.value=""}},C=re=>{l?_.mutate({id:l.id,data:re}):g.mutate(re)},F=re=>{c(re),o(!0)},$=re=>{e(`/projects/${re.id}`)},I=re=>{p(re)},Q=()=>{m!==null&&k.mutate(m)},L=v?.reduce((re,ae)=>(re[ae.status]=(re[ae.status]||0)+1,re.all=(re.all||0)+1,re),{})||{};return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:A,className:"hidden"}),a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(js,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",onClick:T,disabled:!i("projects:create"),title:i("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[a.jsx(Ca,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),a.jsxs(Ie,{variant:"secondary",onClick:M,disabled:!i("projects:read"),title:i("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[a.jsx(va,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),a.jsxs(Ie,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),a.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:rr},{key:"completed",label:t("projects.statusCompleted"),icon:Cc},{key:"archived",label:t("projects.statusArchived"),icon:Qs},{key:"all",label:t("common.all"),icon:js}].map(({key:re,label:ae,icon:ee})=>a.jsxs("button",{onClick:()=>u(re),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${d===re?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[a.jsx(ee,{className:"w-4 h-4"}),a.jsx("span",{children:ae}),L[re]>0&&a.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${d===re?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:L[re]})]},re))}),b?a.jsx("div",{className:"flex items-center justify-center py-20",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):v?.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(js,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:d==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:d})}),a.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"&&a.jsxs(Ie,{onClick:()=>o(!0),disabled:!i("projects:create"),title:i("projects:create")?void 0:t("projects.noCreatePermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:v?.map(re=>a.jsx(ont,{project:re,onClick:()=>$(re),onEdit:()=>F(re),onDelete:()=>I(re.id),hasPermission:i,t},re.id))}),m!==null&&a.jsx(kn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:Q,onCancel:()=>p(null)}),s&&a.jsx(fle,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:g.isPending||_.isPending,currencySymbol:y,t})]})}function cnt(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function dnt({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,i={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return a.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:i[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function nX({icon:t,label:e,value:n,subValue:r,hint:i,color:s="text-bambu-gray"}){return a.jsx(Dt,{children:a.jsx(Rt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",title:i,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:a.jsx(t,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:e}),a.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function unt({archives:t,t:e}){return t.length===0?a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Na,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:e("projectDetail.noPrints")})]}):a.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(n=>a.jsxs(vo,{to:`/archives?search=${encodeURIComponent(n.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:[n.thumbnail_path?a.jsx("img",{src:he.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(Na,{className:"w-8 h-8"})}),n.status==="failed"&&a.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:a.jsx($a,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&a.jsx("div",{className:"absolute top-1 right-1",children:a.jsx(fr,{className:"w-4 h-4 text-bambu-green"})}),a.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:a.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function mnt({priority:t,t:e}){const n={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:r,label:i}=n[t]||n.normal;return a.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&a.jsx(Ln,{className:"w-3 h-3"}),i]})}function m3(t,e){if(!t)return null;const n=Qn(t);if(!n)return null;const r=new Date,i=Math.ceil((n.getTime()-r.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 hnt(){const{id:t}=Cw(),e=Eo(),{t:n}=Lt(),r=mn(),{showToast:i}=xn(),{hasPermission:s}=Sr(),[o,l]=w.useState(!1),[c,d]=w.useState(!1),[u,m]=w.useState(""),p=parseInt(t||"0",10),{data:f,isLoading:y,error:v}=et({queryKey:["project",p],queryFn:()=>he.getProject(p),enabled:p>0}),{data:b,isLoading:g}=et({queryKey:["project-archives",p],queryFn:()=>he.getProjectArchives(p),enabled:p>0}),{data:_,isLoading:k}=et({queryKey:["project-bom",p],queryFn:()=>he.getProjectBOM(p),enabled:p>0}),{data:P,isLoading:N}=et({queryKey:["project-timeline",p],queryFn:()=>he.getProjectTimeline(p,20),enabled:p>0}),{data:M}=et({queryKey:["settings"],queryFn:he.getSettings}),{data:T}=et({queryKey:["project-folders",p],queryFn:()=>he.getLibraryFoldersByProject(p),enabled:p>0}),A=yo(M?.currency||"USD"),C=M?.time_format||"system",F=lt({mutationFn:Re=>he.updateProject(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project",p]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),d(!1),i(n("projectDetail.toast.projectUpdated"),"success")},onError:Re=>{i(Re.message,"error")}}),$=()=>{m(f?.notes||""),d(!0)},I=()=>{F.mutate({notes:u})},Q=()=>{d(!1),m("")},[L,re]=w.useState(""),[ae,ee]=w.useState(1),[ue,le]=w.useState(""),[de,K]=w.useState(""),[te,se]=w.useState(""),[be,Ne]=w.useState(!1),[B,Y]=w.useState(!1),[D,j]=w.useState(null),[z,W]=w.useState(""),[q,ce]=w.useState(1),[O,G]=w.useState(""),[X,V]=w.useState(""),[J,ie]=w.useState(""),[me,pe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),oe=lt({mutationFn:Re=>he.createBOMItem(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),re(""),ee(1),le(""),K(""),se(""),Ne(!1),i(n("projectDetail.toast.partAdded"),"success")},onError:Re=>i(Re.message,"error")}),U=lt({mutationFn:({itemId:Re,data:Ye})=>he.updateBOMItem(p,Re,Ye),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),j(null)},onError:Re=>i(Re.message,"error")}),R=lt({mutationFn:Re=>he.deleteBOMItem(p,Re),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",p]}),r.invalidateQueries({queryKey:["project",p]}),i(n("projectDetail.toast.partRemoved"),"success")},onError:Re=>i(Re.message,"error")}),ne=Re=>{Re.preventDefault(),L.trim()&&oe.mutate({name:L.trim(),quantity_needed:ae,unit_price:ue?parseFloat(ue):void 0,sourcing_url:de.trim()||void 0,remarks:te.trim()||void 0})},xe=Re=>{const Ye=Re.is_complete?0:Re.quantity_needed;U.mutate({itemId:Re.id,data:{quantity_acquired:Ye}})},Se=(Re,Ye)=>{pe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ye}),onConfirm:()=>{pe(we=>({...we,isOpen:!1})),R.mutate(Re)}})},ye=Re=>{j(Re),W(Re.name),ce(Re.quantity_needed),G(Re.unit_price?.toString()||""),V(Re.sourcing_url||""),ie(Re.remarks||"")},ve=Re=>{Re.preventDefault(),!(!D||!z.trim())&&U.mutate({itemId:D.id,data:{name:z.trim(),quantity_needed:q,unit_price:O?parseFloat(O):void 0,sourcing_url:X.trim()||void 0,remarks:J.trim()||void 0}})},fe=()=>{j(null)},ke=async()=>{try{const{blob:Re,filename:Ye}=await he.exportProjectZip(Number(p)),we=URL.createObjectURL(Re),$e=document.createElement("a");$e.href=we,$e.download=Ye||`${f?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,$e.click(),URL.revokeObjectURL(we),i(n("projectDetail.toast.projectExported"),"success")}catch(Re){i(Re.message,"error")}},Ee=lt({mutationFn:()=>he.createTemplateFromProject(p),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),i(n("projectDetail.toast.templateCreated"),"success")},onError:Re=>i(Re.message,"error")}),Ae=Re=>Bf(Re,C,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(y)return a.jsx("div",{className:"flex items-center justify-center py-24",children:a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!f)return a.jsxs("div",{className:"text-center py-24",children:[a.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),a.jsx(Ie,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const _e=f.stats,je=_e?.progress_percent??0,Be=_e?.parts_progress_percent??0;return a.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(vo,{to:"/projects",className:"hover:text-white transition-colors",children:n("nav.projects")}),a.jsx(Va,{className:"w-4 h-4"}),a.jsx("span",{className:"text-white",children:f.name})]}),a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:a.jsx(uQ,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:f.color||"#6b7280"}}),a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:f.name}),f.description&&a.jsx("p",{className:"text-bambu-gray mt-1",children:f.description})]})]}),a.jsx(dnt,{status:f.status,t:n})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",onClick:ke,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[a.jsx(va,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),a.jsxs(Ie,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(f.target_count||f.target_parts_count)&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4 space-y-4",children:[f.target_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.total_archives||0," / ",f.target_count," ",n("projectDetail.progress.printJobs")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(je,100)}%`,backgroundColor:je>=100?"#22c55e":f.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:je.toFixed(0)})}),_e?.remaining_prints!=null&&_e.remaining_prints>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_prints})})]})]}),f.target_parts_count&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),a.jsxs("span",{className:"text-sm font-medium text-white",children:[_e?.completed_prints||0," / ",f.target_parts_count," ",n("projectDetail.progress.parts")]})]}),a.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Be,100)}%`,backgroundColor:Be>=100?"#22c55e":f.color||"#6b7280"}})}),a.jsxs("div",{className:"flex justify-between mt-1",children:[a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Be.toFixed(0)})}),_e?.remaining_parts!=null&&_e.remaining_parts>0&&a.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:_e.remaining_parts})})]})]})]})}),_e&&a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsx(Dt,{children:a.jsx(Rt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(Na,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),a.jsxs("p",{className:"text-xl font-semibold text-white",children:[_e.total_archives," ",a.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),_e.failed_prints>0&&a.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:_e.failed_prints})}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:_e.completed_prints})})]})]})})}),a.jsx(nX,{icon:rr,label:n("projectDetail.stats.printTime"),value:Wxe(_e.total_print_time_hours),color:"text-yellow-400"}),a.jsx(nX,{icon:Pr,label:n("projectDetail.stats.filamentUsed"),value:cnt(_e.total_filament_grams),color:"text-purple-400"})]}),_e&&(()=>{const Re=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return _e.estimated_cost>0||Re>0||f.budget!==null})()&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[A,_e.estimated_cost.toFixed(2)]})]}),_e.total_energy_kwh>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),a.jsxs("p",{className:"text-lg font-semibold text-white",children:[_e.total_energy_kwh.toFixed(3)," kWh",_e.total_energy_cost>0&&a.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",A,_e.total_energy_cost.toFixed(2),")"]})]})]}),(()=>{const Re=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost;return Re<=0?null:a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.totalCost")}),a.jsxs("p",{className:"text-lg font-semibold text-bambu-green",children:[A,Re.toFixed(2)]}),_e.bom_cost>0&&a.jsx("p",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.cost.includesBom")})]})})(),f.budget!==null&&(()=>{const Re=_e.estimated_cost+_e.total_energy_cost+_e.bom_cost,Ye=f.budget-Re;return a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[n("projectDetail.cost.total"),": ",a.jsxs("span",{className:"text-white font-semibold",children:[A,f.budget.toFixed(2)]})]}),a.jsxs("p",{className:`text-sm ${Ye>=0?"text-bambu-green":"text-red-400"}`,children:[n("projectDetail.cost.remaining"),": ",a.jsxs("span",{className:"font-semibold",children:[A,Ye.toFixed(2)]})]})]})})()]})]})}),f.children&&f.children.length>0&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[a.jsx(Hfe,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:f.children.length})]}),a.jsx("div",{className:"space-y-2",children:f.children.map(Re=>a.jsxs(vo,{to:`/projects/${Re.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Re.color||"#6b7280"}}),a.jsx("span",{className:"text-white",children:Re.name}),a.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${Re.status==="completed"?"bg-status-ok/20 text-status-ok":Re.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:Re.status})]}),Re.progress_percent!==null&&a.jsxs("span",{className:"text-sm text-bambu-gray",children:[Re.progress_percent.toFixed(0),"%"]})]},Re.id))})]})}),f.parent_id&&f.parent_name&&a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(ea,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),a.jsx(vo,{to:`/projects/${f.parent_id}`,className:"text-bambu-green hover:underline",children:f.parent_name})]}),(f.tags||f.due_date||f.priority!=="normal")&&a.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[f.priority&&f.priority!=="normal"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),a.jsx(mnt,{priority:f.priority,t:n})]}),f.due_date&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Wr,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-white",children:Uf(f.due_date,{year:"numeric",month:"short",day:"numeric"})}),m3(f.due_date,n)&&a.jsxs("span",{className:`text-xs ${m3(f.due_date,n).color}`,children:["(",m3(f.due_date,n).label,")"]})]}),f.tags&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Vu,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:f.tags.split(",").map((Re,Ye)=>a.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:Re.trim()},Ye))})]})]}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:Q,disabled:F.isPending,children:[a.jsx(Bt,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),a.jsxs(Ie,{size:"sm",onClick:I,disabled:F.isPending,children:[F.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-1"}):a.jsx(cs,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:$,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[a.jsx(Of,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?a.jsx(FL,{content:u,onChange:m,placeholder:n("projectDetail.notes.placeholder")}):f.notes?a.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:Bae.sanitize(f.notes)}}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Fc,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),a.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[a.jsx(vo,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),T&&T.length>0?a.jsx("div",{className:"space-y-2",children:T.map(Re=>a.jsxs(vo,{to:`/files?folder=${Re.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsx(Fc,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:Re.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:Re.file_count})})]})]}),a.jsx(Va,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},Re.id))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(vQ,{className:"w-5 h-5"}),n("projectDetail.bom.title"),_e&&_e.bom_total_items>0&&a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:_e.bom_completed_items,total:_e.bom_total_items}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(Re=>Re.is_complete)&&a.jsx("button",{onClick:()=>Y(!B),className:`text-xs px-2 py-1 rounded transition-colors ${B?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(B?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!be&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Ne(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[a.jsx(ur,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),be&&a.jsxs("form",{onSubmit:ne,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:L,onChange:Re=>re(Re.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:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:ae,onChange:Re=>ee(parseInt(Re.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:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:ue,onChange:Re=>le(Re.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:n("projectDetail.bom.price",{currency:A})})]})]}),a.jsx("input",{type:"url",value:de,onChange:Re=>K(Re.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:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:te,onChange:Re=>se(Re.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:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:()=>Ne(!1),children:n("common.cancel")}),a.jsx(Ie,{type:"submit",size:"sm",disabled:!L.trim()||oe.isPending,children:oe.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),k?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?a.jsxs("div",{className:"space-y-2",children:[_.filter(Re=>!B||!Re.is_complete).map(Re=>a.jsx("div",{className:`p-3 rounded-lg transition-colors ${Re.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:D?.id===Re.id?a.jsxs("form",{onSubmit:ve,className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[a.jsx("input",{type:"text",value:z,onChange:Ye=>W(Ye.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:n("projectDetail.bom.partName"),autoFocus:!0}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"number",value:q,onChange:Ye=>ce(parseInt(Ye.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:n("projectDetail.bom.qty")}),a.jsx("input",{type:"number",step:"0.01",value:O,onChange:Ye=>G(Ye.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:n("projectDetail.bom.price",{currency:A})})]})]}),a.jsx("input",{type:"url",value:X,onChange:Ye=>V(Ye.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:n("projectDetail.bom.sourcingUrlPlaceholder")}),a.jsx("input",{type:"text",value:J,onChange:Ye=>ie(Ye.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:n("projectDetail.bom.remarksPlaceholder")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",size:"sm",onClick:fe,children:n("common.cancel")}),a.jsx(Ie,{type:"submit",size:"sm",disabled:!z.trim()||U.isPending,children:U.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("button",{onClick:()=>s("projects:update")&&xe(Re),disabled:U.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${Re.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:Re.is_complete&&a.jsx(fr,{className:"w-3 h-3"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsxs("p",{className:`text-sm font-medium ${Re.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[Re.name,a.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",Re.quantity_needed]})]}),Re.unit_price!==null&&a.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[A,(Re.unit_price*Re.quantity_needed).toFixed(2)]})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:()=>s("projects:update")&&ye(Re),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-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")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("projects:update")&&Se(Re.id,Re.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-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")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:a.jsx(un,{className:"w-4 h-4"})})]})]}),Re.sourcing_url&&a.jsxs("a",{href:Re.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:Ye=>Ye.stopPropagation(),children:[a.jsx(sa,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{className:"truncate",children:(()=>{try{return new URL(Re.sourcing_url).hostname.replace("www.","")}catch{return Re.sourcing_url}})()})]}),Re.remarks&&a.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:Re.remarks})]})]})},Re.id)),_e&&_e.bom_cost>0&&a.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),a.jsxs("span",{className:"text-white font-medium",children:[A,_e.bom_cost.toFixed(2)]})]})]}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsx("div",{className:"flex items-center justify-between mb-3",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(L0,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),N?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):P&&P.length>0?a.jsx("div",{className:"space-y-3",children:P.slice(0,10).map((Re,Ye)=>a.jsxs("div",{className:"flex gap-3",children:[a.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${Re.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":Re.event_type==="print_failed"?"bg-status-error/20 text-status-error":Re.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Re.event_type==="print_completed"&&a.jsx(fr,{className:"w-4 h-4"}),Re.event_type==="print_failed"&&a.jsx($a,{className:"w-4 h-4"}),Re.event_type==="print_started"&&a.jsx(Pr,{className:"w-4 h-4"}),Re.event_type==="queued"&&a.jsx(U3,{className:"w-4 h-4"}),Re.event_type==="project_created"&&a.jsx(ur,{className:"w-4 h-4"})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white",children:Re.title}),Re.description&&a.jsx("p",{className:"text-xs text-bambu-gray truncate",children:Re.description}),a.jsx("p",{className:"text-xs text-bambu-gray/70",children:Ae(Re.timestamp)})]})]},Ye))}):a.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!f.is_template&&a.jsx("div",{className:"flex justify-end",children:a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>Ee.mutate(),disabled:Ee.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Ee.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Mo,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),_e&&(_e.queued_prints>0||_e.in_progress_prints>0)&&a.jsx(Dt,{children:a.jsxs(Rt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(U3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),a.jsx(vo,{to:`/queue?project=${p}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[_e.in_progress_prints>0&&a.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:_e.in_progress_prints})}),_e.queued_prints>0&&a.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:_e.queued_prints})})]})]})}),a.jsxs("div",{children:[a.jsx("div",{className:"flex items-center justify-between mb-4",children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Na,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:b?.length||0})]})}),g?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(ct,{className:"w-6 h-6 animate-spin text-bambu-green"})}):a.jsx(unt,{archives:b||[],t:n})]}),o&&a.jsx(fle,{t:n,currencySymbol:A,project:{...f,archive_count:_e?.total_archives||0,total_items:_e?.total_items||0,completed_count:_e?.completed_prints||0,failed_count:_e?.failed_prints||0,queue_count:_e?.queued_prints||0,progress_percent:_e?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:Re=>F.mutate(Re),isLoading:F.isPending}),me.isOpen&&a.jsx(kn,{title:me.title,message:me.message,confirmText:n("common.delete"),variant:"danger",onConfirm:me.onConfirm,onCancel:()=>pe(Re=>({...Re,isOpen:!1}))})]})}function pnt({parentId:t,onClose:e,onSave:n,isLoading:r,t:i}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("fileManager.newFolder")})}),a.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:i("fileManager.folderName")}),a.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})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!s.trim()||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("common.create")})]})]})]})})}function fnt({onClose:t,onSave:e,isLoading:n,t:r}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,d]=w.useState(!0),[u,m]=w.useState(!1),p=f=>{f.preventDefault(),e({name:i.trim(),external_path:o.trim(),readonly:c,show_hidden:u})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(tN,{className:"w-5 h-5 text-bambu-green"}),r("fileManager.linkExternalFolder")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.linkExternalFolderDescription")})]}),a.jsxs("form",{onSubmit:p,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.folderName")}),a.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:r("fileManager.externalFolderNamePlaceholder"),autoFocus:!0,required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:r("fileManager.externalPath")}),a.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}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("fileManager.externalPathHelp")})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.readOnly")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",r("fileManager.readOnlyHelp"),")"]})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.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"}),a.jsx("span",{className:"text-sm text-white",children:r("fileManager.showHiddenFiles")})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:t,children:r("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!i.trim()||!o.trim()||n,children:n?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):r("fileManager.linkFolder")})]})]})]})})}function gnt({type:t,currentName:e,onClose:n,onSave:r,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]=w.useState(l),u=m=>{m.preventDefault();const p=t==="file"?c.trim()+o:c.trim();c.trim()&&p!==e&&r(p)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),a.jsxs("form",{onSubmit:u,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),a.jsxs("div",{className:"flex items-center bg-bambu-dark border border-bambu-dark-tertiary rounded focus-within:border-bambu-green",children:[a.jsx("input",{type:"text",value:c,onChange:m=>d(m.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&&a.jsx("span",{className:"pr-3 text-bambu-gray text-sm select-none whitespace-nowrap",children:o})]})]}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),a.jsx(Ie,{type:"submit",disabled:!c.trim()||c.trim()===l||i,children:i?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function bnt({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:i,isLoading:s,t:o}){const[l,c]=w.useState(null),d=(m,p=0)=>{const f=[];for(const y of m)f.push({id:y.id,name:y.name,depth:p}),y.children.length>0&&f.push(...d(y.children,p+1));return f},u=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...d(t)];return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[a.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:u.map(m=>a.jsxs("button",{onClick:()=>c(m.id),disabled:m.id===n,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===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+m.depth*16}px`},children:[a.jsx(Fc,{className:"w-4 h-4"}),m.name,m.id===n&&a.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},m.id??"root"))}),a.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[a.jsx(Ie,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),a.jsx(Ie,{onClick:()=>i(l),disabled:s,children:s?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function xnt({folder:t,onClose:e,onLink:n,isLoading:r,t:i}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:d}=et({queryKey:["projects"],queryFn:()=>he.getProjects()}),{data:u}=et({queryKey:["archives-for-link"],queryFn:()=>he.getArchives(void 0,void 0,100)}),m=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},p=()=>{n({project_id:0,archive_id:0})},f=t.project_id||t.archive_id;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ru,{className:"w-5 h-5 text-bambu-green"}),i("fileManager.linkFolder")]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:a.jsx(Bt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("fileManager.linkFolderDescription",{name:t.name})}),a.jsxs("div",{className:"flex gap-2",children:[a.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:[a.jsx(mQ,{className:"w-4 h-4"}),i("fileManager.project")]}),a.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:[a.jsx(Qs,{className:"w-4 h-4"}),i("fileManager.archive")]})]}),a.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(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:y.color||"#00ae42"}}),a.jsx("span",{className:"truncate",children:y.name})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noProjectsFound")}):u&&u.length>0?u.map(y=>a.jsxs("button",{onClick:()=>c(y.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===y.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[a.jsx(yf,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"truncate",children:y.print_name||y.filename})]},y.id)):a.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:i("fileManager.noArchivesFound")})})]}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[f&&a.jsxs(Ie,{variant:"danger",onClick:p,disabled:r,children:[a.jsx(qh,{className:"w-4 h-4 mr-2"}),i("fileManager.unlink")]}),a.jsxs("div",{className:`flex gap-2 ${f?"":"ml-auto"}`,children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:i("common.cancel")}),a.jsx(Ie,{onClick:m,disabled:!l||r,children:r?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):i("fileManager.link")})]})]})]})})}function gle({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:d}){const[u,m]=w.useState(!0),[p,f]=w.useState(!1),y=t.children.length>0,v=t.project_id||t.archive_id,b=t.is_external;return a.jsxs("div",{children:[a.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:()=>n(t.id),children:[y?a.jsx("button",{onClick:g=>{g.stopPropagation(),m(!u)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Va,{className:`w-3.5 h-3.5 transition-transform ${u?"rotate-90":""}`})}):a.jsx("div",{className:"w-4.5"}),b?a.jsx(tN,{className:"w-4 h-4 text-purple-400 flex-shrink-0"}):a.jsx(Fc,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),a.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&a.jsxs("button",{onClick:g=>{g.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:[a.jsx(Ru,{className:"w-3 h-3"}),t.project_name?a.jsx(mQ,{className:"w-3 h-3"}):a.jsx(Qs,{className:"w-3 h-3"})]}),b&&t.external_readonly&&a.jsx("span",{title:d("fileManager.readOnly"),children:a.jsx(ld,{className:"w-3 h-3 text-amber-400 flex-shrink-0"})}),t.file_count>0&&a.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&!b&&a.jsx("button",{onClick:g=>{g.stopPropagation(),i(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:d("fileManager.linkToProjectOrArchive"),children:a.jsx(Ru,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),a.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:g=>g.stopPropagation(),children:a.jsxs("div",{className:"relative",children:[a.jsx("button",{onClick:()=>f(!p),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray"})}),p&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>f(!1)}),a.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:[a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionRenameFolder"),children:[a.jsx(Za,{className:"w-3.5 h-3.5"}),d("common.rename")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(i(t),f(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:d("fileManager.noPermissionLinkFolder"),children:[a.jsx(Ru,{className:"w-3.5 h-3.5"}),d(v?"fileManager.changeLink":"fileManager.linkTo")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),f(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:d("fileManager.noPermissionDeleteFolder"),children:[a.jsx(un,{className:"w-3.5 h-3.5"}),d("common.delete")]})]})]})]})})]}),y&&u&&a.jsx("div",{children:t.children.map(g=>a.jsx(gle,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:i,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:d},g.id))})]})}function HL(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function ynt({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:i,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:d,onGenerateThumbnail:u,thumbnailVersion:m,hasPermission:p,canModify:f,authEnabled:y,t:v}){const[b,g]=w.useState(!1);return a.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:()=>r(t.id),children:[a.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?a.jsx("img",{src:`${he.getLibraryFileThumbnailUrl(t.id)}${m?(he.getLibraryFileThumbnailUrl(t.id).includes("?")?"&":"?")+`v=${m}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):a.jsx(yf,{className:"w-12 h-12 text-bambu-gray/30"}),a.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"?"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()})]}),a.jsxs("div",{className:"p-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),a.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[a.jsx("span",{children:_o(t.file_size)}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(rr,{className:"w-3 h-3"}),ls(t.print_time_seconds)]})]}),t.sliced_for_model&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Pr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&a.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),y&&t.created_by_username&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[a.jsx(Gu,{className:"w-3 h-3"}),t.created_by_username]})]}),a.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[a.jsx("button",{onClick:()=>g(!b),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:a.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}),b&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>g(!1)}),a.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&&HL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("printers:control")&&(l(t),g(!1))},disabled:!p("printers:control"),title:p("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[a.jsx(Pr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&HL(t.filename)&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("queue:create")&&(o(t.id),g(!1))},disabled:!p("queue:create"),title:p("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[a.jsx(rr,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(c(t),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:"You do not have permission to preview files",children:[a.jsx(si,{className:"w-3.5 h-3.5"}),"3D Preview"]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library:read")&&(s(t.id),g(!1))},disabled:!p("library:read"),title:p("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[a.jsx(va,{className:"w-3.5 h-3.5"}),v("common.download")]}),d&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(d(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[a.jsx(Za,{className:"w-3.5 h-3.5"}),v("common.rename")]}),u&&t.file_type==="stl"&&a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","update",t.created_by_id)&&(u(t),g(!1))},disabled:!f("library","update",t.created_by_id),title:f("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[a.jsx($u,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library","delete",t.created_by_id)&&(i(t.id),g(!1))},disabled:!f("library","delete",t.created_by_id),title:f("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[a.jsx(un,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),a.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 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function vnt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r,hasAnyPermission:i,canModify:s,authEnabled:o}=Sr(),[l]=eO(),c=l.get("folder"),d=c?parseInt(c,10):null,[u,m]=w.useState(d),[p,f]=w.useState([]),[y,v]=w.useState(!1),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(!1),[M,T]=w.useState(null),[A,C]=w.useState(null),[F,$]=w.useState(null),[I,Q]=w.useState(null),[L,re]=w.useState(null),[ae,ee]=w.useState(null),[ue,le]=w.useState({}),[de,K]=w.useState(null),[te,se]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[be,Ne]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[B,Y]=w.useState(()=>{const We=localStorage.getItem("library-sidebar-width");return We?parseInt(We,10):256}),[D,j]=w.useState(!1),z=w.useRef(null);w.useEffect(()=>{if(!D)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const We=Nt=>{if(!z.current)return;const ht=z.current.parentElement?.getBoundingClientRect();if(!ht)return;const Mt=Nt.clientX-ht.left,Qt=Math.min(500,Math.max(200,Mt));Y(Qt)},Ft=()=>{j(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(B))};return document.addEventListener("mousemove",We),document.addEventListener("mouseup",Ft),()=>{document.removeEventListener("mousemove",We),document.removeEventListener("mouseup",Ft),document.body.style.userSelect="",document.body.style.cursor=""}},[D,B]);const[W,q]=w.useState(""),[ce,O]=w.useState("all"),[G,X]=w.useState(""),[V,J]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[ie,me]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),pe=Eae();w.useEffect(()=>{const We=l.get("folder");if(We){const Ft=parseInt(We,10);m(Ft)}},[l]);const{data:oe}=et({queryKey:["settings"],queryFn:()=>he.getSettings()}),{data:U,isLoading:R}=et({queryKey:["library-folders"],queryFn:()=>he.getLibraryFolders()}),{data:ne,isLoading:xe}=et({queryKey:["library-files",u],queryFn:()=>he.getLibraryFiles(u,u===null)}),{data:Se}=et({queryKey:["library-stats"],queryFn:()=>he.getLibraryStats()}),{data:ye}=et({queryKey:["users"],queryFn:()=>he.getUsers()}),ve=w.useMemo(()=>{if(!ne)return[];const We=new Set(ne.map(Ft=>Ft.file_type));return Array.from(We).sort()},[ne]),fe=w.useMemo(()=>{if(!ne)return[];let We=[...ne];if(W.trim()){const Ft=W.toLowerCase();We=We.filter(Nt=>Nt.filename.toLowerCase().includes(Ft)||Nt.print_name&&Nt.print_name.toLowerCase().includes(Ft))}if(ce!=="all"&&(We=We.filter(Ft=>Ft.file_type===ce)),G.trim()){const Ft=G.toLowerCase();We=We.filter(Nt=>Nt.created_by_username&&Nt.created_by_username.toLowerCase().includes(Ft))}return We.sort((Ft,Nt)=>{let ht=0;switch(V){case"name":ht=(Ft.print_name||Ft.filename).localeCompare(Nt.print_name||Nt.filename);break;case"date":ht=(Qn(Ft.created_at)?.getTime()??0)-(Qn(Nt.created_at)?.getTime()??0);break;case"size":ht=Ft.file_size-Nt.file_size;break;case"type":ht=Ft.file_type.localeCompare(Nt.file_type);break;case"prints":ht=Ft.print_count-Nt.print_count;break}return ie==="asc"?ht:-ht}),We},[ne,W,ce,G,V,ie]),ke=w.useMemo(()=>{if(!Se||!oe)return!1;const We=(oe.library_disk_warning_gb||5)*1024*1024*1024;return Se.disk_free_byteshe.createLibraryFolder(We),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:We=>n(We.message,"error")}),Ae=lt({mutationFn:async We=>{const Ft=await he.createExternalFolder(We);return await he.scanExternalFolder(Ft.id),Ft},onSuccess:We=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),g(!1),m(We.id),n(t("fileManager.toast.externalFolderLinked"),"success")},onError:We=>n(We.message,"error")}),_e=lt({mutationFn:We=>he.scanExternalFolder(We),onSuccess:We=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.folderScanned",{added:We.added,removed:We.removed}),"success")},onError:We=>n(We.message,"error")}),je=lt({mutationFn:We=>he.deleteLibraryFolder(We),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),u===A?.id&&m(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:We=>{C(null),n(We.message,"error")}}),Be=lt({mutationFn:We=>he.deleteLibraryFile(We),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),f(We=>We.filter(Ft=>Ft!==A?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:We=>{C(null),n(We.message,"error")}}),Re=lt({mutationFn:We=>he.bulkDeleteLibrary(We,[]),onSuccess:(We,Ft)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:Ft.length}),"success"),f([]),C(null)},onError:We=>{C(null),n(We.message,"error")}}),Ye=lt({mutationFn:({fileIds:We,folderId:Ft})=>he.moveLibraryFiles(We,Ft),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),f([]),k(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:We=>n(We.message,"error")}),we=lt({mutationFn:({id:We,data:Ft})=>he.updateLibraryFolder(We,Ft),onSuccess:(We,Ft)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),T(null);const Nt=Ft.data.project_id===0&&Ft.data.archive_id===0;n(t(Nt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:We=>n(We.message,"error")}),$e=lt({mutationFn:({id:We,filename:Ft})=>he.updateLibraryFile(We,{filename:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:We=>{ee(null),n(We.message,"error")}}),De=lt({mutationFn:({id:We,name:Ft})=>he.updateLibraryFolder(We,{name:Ft}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),ee(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:We=>{ee(null),n(We.message,"error")}}),Xe=lt({mutationFn:()=>he.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:We=>{if(e.invalidateQueries({queryKey:["library-files"]}),We.succeeded>0){const Ft=Date.now(),Nt={};We.results.forEach(ht=>{ht.success&&(Nt[ht.file_id]=Ft)}),le(ht=>({...ht,...Nt}))}We.succeeded>0&&We.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:We.succeeded}),"success"):We.succeeded>0&&We.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:We.succeeded,failed:We.failed}),"success"):We.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:We.results[0]?.error||"Unknown error"}),"error")},onError:We=>n(We.message,"error")}),Ve=lt({mutationFn:We=>he.batchGenerateStlThumbnails({file_ids:[We]}),onSuccess:We=>{if(e.invalidateQueries({queryKey:["library-files"]}),We.succeeded>0){const Ft=We.results[0]?.file_id;Ft&&le(Nt=>({...Nt,[Ft]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:We.results[0]?.error||"Unknown error"}),"error")},onError:We=>n(We.message,"error")}),Te=w.useCallback(We=>{const Ft=We.toLowerCase();return Ft.endsWith(".gcode")||Ft.includes(".gcode.")},[]),Me=w.useMemo(()=>ne?ne.filter(We=>p.includes(We.id)&&Te(We.filename)):[],[ne,p,Te]),qe=w.useCallback(We=>{f(Ft=>Ft.includes(We)?Ft.filter(Nt=>Nt!==We):[...Ft,We])},[]),tt=w.useCallback(()=>{fe.length>0&&f(fe.map(We=>We.id))},[fe]),ut=w.useCallback(()=>{f([])},[]),xt=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},wt=We=>{he.downloadLibraryFile(We).catch(Ft=>{console.error("Library file download failed:",Ft)})},Ht=()=>{A&&(A.type==="file"?Be.mutate(A.id):A.type==="folder"?je.mutate(A.id):A.type==="bulk"&&Re.mutate(p))},Xt=je.isPending||Be.isPending||Re.isPending,Kt=We=>{se(We),localStorage.setItem("library-view-mode",We)},Ut=R||xe,en=w.useMemo(()=>{if(!u||!U)return null;const We=Ft=>{for(const Nt of Ft){if(Nt.id===u)return Nt;const ht=We(Nt.children);if(ht)return ht}return null};return We(U)},[u,U]);return a.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:a.jsx(Fc,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[a.jsx("button",{onClick:()=>Kt("grid"),className:`p-1.5 rounded transition-colors ${te==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:a.jsx(jw,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>Kt("list"),className:`p-1.5 rounded transition-colors ${te==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:a.jsx(Ew,{className:"w-4 h-4"})})]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>Xe.mutate(),disabled:Xe.isPending||!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Xe.isPending?a.jsx(ct,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx($u,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>g(!0),disabled:!r("library:upload"),title:r("library:upload")?t("fileManager.linkExternalFolder"):t("fileManager.noPermissionCreateFolder"),children:[a.jsx(tN,{className:"w-4 h-4 mr-2"}),t("fileManager.linkExternal")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[a.jsx(zfe,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),a.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(Ca,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ke&&Se&&oe&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[a.jsx(Ln,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),a.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:_o(Se.disk_free_bytes),total:_o(Se.disk_total_bytes),threshold:oe.library_disk_warning_gb})})]})]}),Se&&a.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:[a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(_P,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Se.total_files})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(Fc,{className:"w-4 h-4 text-blue-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),a.jsx("span",{className:"text-white font-medium",children:Se.total_folders})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(ty,{className:"w-4 h-4 text-amber-400"}),a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),a.jsx("span",{className:"text-white font-medium",children:_o(Se.total_size_bytes)})]}),a.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),a.jsx("span",{className:`font-medium ${ke?"text-amber-500":"text-white"}`,children:_o(Se.disk_free_bytes)})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[a.jsx("div",{className:"lg:hidden",children:a.jsxs("select",{value:u??"",onChange:We=>m(We.target.value?parseInt(We.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:[a.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),U&&(()=>{const We=(Ft,Nt=0)=>{const ht=[];for(const Mt of Ft)ht.push({id:Mt.id,name:Mt.name,fileCount:Mt.file_count,depth:Nt}),Mt.children.length>0&&ht.push(...We(Mt.children,Nt+1));return ht};return We(U).map(Ft=>a.jsxs("option",{value:Ft.id,children:["│ ".repeat(Ft.depth),"📂 ",Ft.name," ",Ft.fileCount>0?`(${Ft.fileCount})`:""]},Ft.id))})()]})}),a.jsxs("div",{ref:z,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:`${B}px`},children:[a.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 ${D?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:We=>{We.preventDefault(),j(!0)},onDoubleClick:()=>{Y(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:a.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${D?"opacity-100":""}`,children:[a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),a.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),a.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),a.jsx("button",{onClick:()=>{const We=!be;Ne(We),localStorage.setItem("library-wrap-folders",String(We))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${be?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(be?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[a.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${u===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>m(null),children:[a.jsx(yf,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),U?.map(We=>a.jsx(gle,{folder:We,selectedFolderId:u,onSelect:m,onDelete:Ft=>C({type:"folder",id:Ft}),onLink:T,onRename:Ft=>ee({type:"folder",id:Ft.id,name:Ft.name}),wrapNames:be,hasPermission:r,t},We.id))]})]}),a.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[en?.is_external&&a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:[a.jsx(tN,{className:"w-5 h-5 text-purple-400 flex-shrink-0"}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-purple-300",children:t("fileManager.externalFolder")}),en.external_readonly&&a.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:[a.jsx(ld,{className:"w-3 h-3"}),t("fileManager.readOnly")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray truncate font-mono",title:en.external_path||"",children:en.external_path})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>u&&_e.mutate(u),disabled:_e.isPending,title:t("fileManager.scanFolder"),children:[_e.isPending?a.jsx(ct,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),a.jsx("span",{className:"ml-1.5",children:t("fileManager.scanFolder")})]})]}),ne&&ne.length>0&&a.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:[a.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:W,onChange:We=>q(We.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"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(kP,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),a.jsxs("select",{value:ce,onChange:We=>O(We.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:[a.jsx("option",{value:"all",children:t("fileManager.allTypes")}),ve.map(We=>a.jsx("option",{value:We,children:We.toUpperCase()},We))]})]}),o&&a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:G,onChange:We=>X(We.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 ${G?"pr-7":""}`,style:G?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),G&&a.jsx("button",{onClick:()=>X(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:a.jsx(Bt,{className:"w-3 h-3"})}),a.jsx("datalist",{id:"usernames-list",children:ye?.map(We=>a.jsx("option",{value:We.username},We.id))})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{value:V,onChange:We=>{const Ft=We.target.value;J(Ft),localStorage.setItem("library-sort-field",Ft)},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:[a.jsx("option",{value:"name",children:t("common.name")}),a.jsx("option",{value:"date",children:t("common.date")}),a.jsx("option",{value:"size",children:t("fileManager.size")}),a.jsx("option",{value:"type",children:t("common.type")}),a.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),a.jsx("button",{onClick:()=>me(We=>{const Ft=We==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",Ft),Ft}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(ie==="asc"?"fileManager.ascending":"fileManager.descending"),children:ie==="asc"?a.jsx(Jhe,{className:"w-4 h-4 text-white"}):a.jsx(Ghe,{className:"w-4 h-4 text-white"})})]}),(W||ce!=="all"||G)&&a.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:fe.length,total:ne.length})})]}),fe.length>0&&a.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:[p.length===fe.length&&p.length>0?a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(eo,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:tt,children:[a.jsx(us,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),p.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:p.length})}),a.jsx("div",{className:"hidden sm:block flex-1"}),a.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Me.length===1&&a.jsxs(Ie,{variant:"primary",size:"sm",onClick:()=>Q(Me[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[a.jsx(Ds,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Me.length===1&&a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>re(Me[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[a.jsx(rr,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:()=>k(!0),disabled:!i("library:update_own","library:update_all"),title:i("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[a.jsx(Yge,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),a.jsxs(Ie,{variant:"danger",size:"sm",onClick:()=>{p.length===1?C({type:"file",id:p[0]}):C({type:"bulk",id:0,count:p.length})},disabled:!i("library:delete_own","library:delete_all"),title:i("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[a.jsx(un,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),a.jsxs(Ie,{variant:"secondary",size:"sm",onClick:ut,children:[a.jsx(Bt,{className:"w-4 h-4 sm:mr-1"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Ut?a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"flex flex-col items-center gap-3",children:[a.jsx(ct,{className:"w-8 h-8 animate-spin text-bambu-green"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):ne?.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(yf,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(u!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(u!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),a.jsxs(Ie,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[a.jsx(ur,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):fe.length===0?a.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[a.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:a.jsx(Cr,{className:"w-12 h-12 text-bambu-gray/50"})}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),a.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),a.jsx(Ie,{variant:"secondary",onClick:()=>{q(""),O("all")},children:t("fileManager.clearFilters")})]}):te==="grid"?a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.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:fe.map(We=>a.jsx(ynt,{file:We,isSelected:p.includes(We.id),isMobile:pe,t,onSelect:qe,onDelete:Ft=>C({type:"file",id:Ft}),onDownload:wt,onAddToQueue:Ft=>{const Nt=ne?.find(ht=>ht.id===Ft);Nt&&re(Nt)},onPrint:$,onPreview3d:K,onRename:Ft=>ee({type:"file",id:Ft.id,name:Ft.filename}),onGenerateThumbnail:Ft=>Ve.mutate(Ft.id),thumbnailVersion:ue[We.id],hasPermission:r,canModify:s,authEnabled:o},We.id))})}):a.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[a.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[a.jsx("div",{className:"w-6"}),a.jsx("div",{children:t("common.name")}),o&&a.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),a.jsx("div",{children:t("common.type")}),a.jsx("div",{children:t("fileManager.size")}),a.jsx("div",{children:t("fileManager.prints")}),a.jsx("div",{})]}),fe.map(We=>a.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} 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 ${p.includes(We.id)?"bg-bambu-green/10":""}`,onClick:()=>qe(We.id),children:[a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${p.includes(We.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:p.includes(We.id)&&a.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),a.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[a.jsxs("div",{className:"relative group/thumb",children:[a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:We.thumbnail_path?a.jsx("img",{src:`${he.getLibraryFileThumbnailUrl(We.id)}${ue[We.id]?(he.getLibraryFileThumbnailUrl(We.id).includes("?")?"&":"?")+`v=${ue[We.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(yf,{className:"w-5 h-5 text-bambu-gray/50"})})}),We.thumbnail_path&&a.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:a.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:a.jsx("img",{src:`${he.getLibraryFileThumbnailUrl(We.id)}${ue[We.id]?(he.getLibraryFileThumbnailUrl(We.id).includes("?")?"&":"?")+`v=${ue[We.id]}`:""}`,alt:We.filename,className:"w-full h-full object-contain"})})})]}),a.jsx("div",{className:"min-w-0",children:a.jsx("div",{className:"text-sm text-white truncate",children:We.print_name||We.filename})})]}),o&&a.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:We.created_by_username?a.jsxs(a.Fragment,{children:[a.jsx(Gu,{className:"w-3 h-3"}),a.jsx("span",{className:"truncate",children:We.created_by_username})]}):"-"}),a.jsx("div",{children:a.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":We.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:We.file_type.toUpperCase()})}),a.jsx("div",{className:"text-sm text-bambu-gray",children:_o(We.file_size)}),a.jsx("div",{className:"text-sm text-bambu-gray",children:We.print_count>0?`${We.print_count}x`:"-"}),a.jsxs("div",{className:"flex items-center gap-1",onClick:Ft=>Ft.stopPropagation(),children:[HL(We.filename)&&a.jsxs(a.Fragment,{children:[a.jsx("button",{onClick:()=>r("printers:control")&&$(We),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:a.jsx(Pr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>{r("queue:create")&&re(We)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:a.jsx(rr,{className:"w-4 h-4"})})]}),(We.file_type==="3mf"||We.file_type==="gcode"||We.file_type==="stl")&&a.jsx("button",{onClick:()=>r("library:read")&&K(We),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:a.jsx(si,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>r("library:read")&&wt(We.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:a.jsx(va,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","update",We.created_by_id)&&ee({type:"file",id:We.id,name:We.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",We.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",We.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",We.created_by_id),children:a.jsx(Za,{className:"w-4 h-4"})}),We.file_type==="stl"&&a.jsx("button",{onClick:()=>s("library","update",We.created_by_id)&&Ve.mutate(We.id),className:`p-1.5 rounded transition-colors ${s("library","update",We.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",We.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Ve.isPending||!s("library","update",We.created_by_id),children:a.jsx($u,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>s("library","delete",We.created_by_id)&&C({type:"file",id:We.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",We.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",We.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",We.created_by_id),children:a.jsx(un,{className:"w-4 h-4"})})]})]},We.id))]})})]})]}),y&&a.jsx(pnt,{parentId:u,onClose:()=>v(!1),onSave:We=>Ee.mutate(We),isLoading:Ee.isPending,t}),b&&a.jsx(fnt,{onClose:()=>g(!1),onSave:We=>Ae.mutate(We),isLoading:Ae.isPending,t}),_&&U&&a.jsx(bnt,{folders:U,selectedFiles:p,currentFolderId:u,onClose:()=>k(!1),onMove:We=>Ye.mutate({fileIds:p,folderId:We}),isLoading:Ye.isPending,t}),P&&a.jsx(kae,{folderId:u,onClose:()=>N(!1),onUploadComplete:xt}),M&&a.jsx(xnt,{folder:M,onClose:()=>T(null),onLink:We=>we.mutate({id:M.id,data:We}),isLoading:we.isPending,t}),A&&a.jsx(kn,{title:A.type==="folder"?t("fileManager.deleteFolder"):A.type==="bulk"?t("fileManager.deleteFilesCount",{count:A.count}):t("fileManager.deleteFile"),message:A.type==="folder"?t("fileManager.deleteFolderConfirm"):A.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:A.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Xt,loadingText:t("fileManager.deleting"),onConfirm:Ht,onCancel:()=>C(null)}),F&&a.jsx(kd,{mode:"reprint",libraryFileId:F.id,archiveName:F.print_name||F.filename,onClose:()=>$(null),onSuccess:()=>{$(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),I&&a.jsx(kd,{mode:"reprint",libraryFileId:I.id,archiveName:I.print_name||I.filename,onClose:()=>Q(null),onSuccess:()=>{Q(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),L&&a.jsx(kd,{mode:"add-to-queue",libraryFileId:L.id,archiveName:L.print_name||L.filename,onClose:()=>re(null),onSuccess:()=>{re(null),f([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),de&&a.jsx(ez,{libraryFileId:de.id,title:de.print_name||de.filename,fileType:de.file_type,onClose:()=>K(null)}),ae&&a.jsx(gnt,{type:ae.type,currentName:ae.name,onClose:()=>ee(null),onSave:We=>{ae.type==="file"?$e.mutate({id:ae.id,filename:We}):De.mutate({id:ae.id,name:We})},isLoading:$e.isPending||De.isPending,t})]})}const fk=5,wnt=2e3,Snt=3e4,_nt=5e3;function knt(){const{t}=Lt(),e=mn(),{showToast:n}=xn(),{hasPermission:r}=Sr(),{printerId:i}=Cw(),s=parseInt(i||"0",10),[o,l]=w.useState("stream"),[c,d]=w.useState(!1),[u,m]=w.useState(!1),[p,f]=w.useState(!0),[y,v]=w.useState(Date.now()),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(0),[M,T]=w.useState(!1),[A,C]=w.useState(0),[F,$]=w.useState(1),[I,Q]=w.useState({x:0,y:0}),[L,re]=w.useState(!1),[ae,ee]=w.useState({x:0,y:0}),[ue,le]=w.useState(null),[de,K]=w.useState(null),te=w.useRef(null),se=w.useRef(null),be=w.useRef(null),Ne=w.useRef(null),B=w.useRef(null),{data:Y}=et({queryKey:["printer",s],queryFn:()=>he.getPrinter(s),enabled:s>0}),{data:D}=et({queryKey:["printerStatus",s],queryFn:()=>he.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),j=lt({mutationFn:_e=>he.setChamberLight(s,_e),onMutate:async _e=>{await e.cancelQueries({queryKey:["printerStatus",s]});const je=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],Be=>({...Be,chamber_light:_e})),{previousStatus:je}},onSuccess:(_e,je)=>{n(`Chamber light ${je?"on":"off"}`)},onError:(_e,je,Be)=>{Be?.previousStatus&&e.setQueryData(["printerStatus",s],Be.previousStatus),n(_e.message||t("printers.toast.failedToControlChamberLight"),"error")}}),z=(D?.state==="RUNNING"||D?.state==="PAUSE")&&(D?.printable_objects_count??0)>=2;w.useEffect(()=>(Y&&(document.title=`${Y.name} - Camera`),()=>{document.title="Bambuddy"}),[Y]);const W=w.useRef(!1);w.useEffect(()=>{const _e=`/api/v1/printers/${s}/camera/stop`;W.current=!1;const je=()=>{if(s>0&&!W.current){W.current=!0;const Ye={},we=Ku();we&&(Ye.Authorization=`Bearer ${we}`),fetch(_e,{method:"POST",keepalive:!0,headers:Ye}).catch(()=>{})}},Be=()=>{je()};window.addEventListener("beforeunload",Be);const Re=te.current;return()=>{window.removeEventListener("beforeunload",Be),Re&&(Re.src=""),je()}},[s]),w.useEffect(()=>{if(p&&!b){const je=setTimeout(()=>{f(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(je)}},[o,p,y,b]),w.useEffect(()=>{const _e=()=>{const je=!!document.fullscreenElement;k(je),$(1),Q({x:0,y:0}),o==="stream"&&!b&&(te.current&&(te.current.src=""),setTimeout(()=>{f(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",_e),()=>document.removeEventListener("fullscreenchange",_e)},[o,b]),w.useEffect(()=>{let _e;const je=()=>{clearTimeout(_e),_e=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",je),()=>{clearTimeout(_e),window.removeEventListener("resize",je)}},[]),w.useEffect(()=>()=>{be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),B.current&&clearInterval(B.current)},[]);const q=w.useCallback(()=>{if(P>=fk){T(!1),m(!0);return}const _e=Math.min(wnt*Math.pow(2,P),Snt);T(!0),C(Math.ceil(_e/1e3)),Ne.current=setInterval(()=>{C(je=>je<=1?(Ne.current&&clearInterval(Ne.current),0):je-1)},1e3),be.current=setTimeout(()=>{N(je=>je+1),T(!1),f(!0),m(!1),te.current&&(te.current.src=""),v(Date.now())},_e)},[P]);w.useEffect(()=>{if(o!=="stream"||p||M||b){B.current&&(clearInterval(B.current),B.current=null);return}return B.current=setInterval(async()=>{try{const _e=await he.getCameraStatus(s);(_e.stalled||!_e.active&&!u)&&(console.log(`Stream issue detected: stalled=${_e.stalled}, active=${_e.active}, reconnecting...`),B.current&&(clearInterval(B.current),B.current=null),f(!1),q())}catch{}},_nt),()=>{B.current&&(clearInterval(B.current),B.current=null)}},[o,p,u,M,b,s,q]);const ce=()=>{f(!1),o==="stream"&&P{if(f(!1),m(!1),N(0),T(!1),be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),te.current&&!localStorage.getItem("cameraWindowState")){const _e=te.current,je=_e.naturalWidth,Be=_e.naturalHeight;if(je>0&&Be>0){const we=window.outerWidth-window.innerWidth,$e=window.outerHeight-window.innerHeight,De=je+16+we,Xe=Be+45+16+$e;try{window.resizeTo(De,Xe)}catch{}}}},G=()=>{if(s>0){const _e={},je=Ku();je&&(_e.Authorization=`Bearer ${je}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:_e}).catch(()=>{})}},X=_e=>{o===_e||b||(g(!0),f(!0),m(!1),N(0),T(!1),$(1),Q({x:0,y:0}),be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),te.current&&(te.current.src=""),o==="stream"&&G(),setTimeout(()=>{l(_e),v(Date.now()),g(!1)},100))},V=()=>{b||(g(!0),f(!0),m(!1),N(0),T(!1),be.current&&clearTimeout(be.current),Ne.current&&clearInterval(Ne.current),te.current&&(te.current.src=""),o==="stream"&&G(),setTimeout(()=>{v(Date.now()),g(!1)},100))},J=()=>{se.current&&(document.fullscreenElement?document.exitFullscreen():se.current.requestFullscreen())},ie=()=>{$(_e=>Math.min(_e+.5,4))},me=()=>{$(_e=>{const je=Math.max(_e-.5,1);return je===1&&Q({x:0,y:0}),je})},pe=_e=>{_e.preventDefault(),_e.deltaY<0?ie():me()},oe=_e=>{F>1&&(_e.preventDefault(),re(!0),ee({x:_e.clientX-I.x,y:_e.clientY-I.y}))},U=w.useCallback(()=>{if(!se.current)return{x:300,y:200};const _e=se.current.getBoundingClientRect(),je=_e.width*(F-1)/2,Be=_e.height*(F-1)/2;return{x:Math.max(50,je),y:Math.max(50,Be)}},[F]),R=_e=>{if(L&&F>1){const je=_e.clientX-ae.x,Be=_e.clientY-ae.y,Re=U();Q({x:Math.max(-Re.x,Math.min(Re.x,je)),y:Math.max(-Re.y,Math.min(Re.y,Be))})}},ne=()=>{re(!1)},xe=_e=>{if(_e.length<2)return 0;const je=_e[0].clientX-_e[1].clientX,Be=_e[0].clientY-_e[1].clientY;return Math.sqrt(je*je+Be*Be)},Se=_e=>_e.length<2?{x:_e[0].clientX,y:_e[0].clientY}:{x:(_e[0].clientX+_e[1].clientX)/2,y:(_e[0].clientY+_e[1].clientY)/2},ye=_e=>{_e.touches.length===2?(_e.preventDefault(),le(xe(_e.touches)),K(Se(_e.touches))):_e.touches.length===1&&F>1&&(_e.preventDefault(),re(!0),ee({x:_e.touches[0].clientX-I.x,y:_e.touches[0].clientY-I.y}))},ve=_e=>{if(_e.touches.length===2&&ue!==null){_e.preventDefault();const je=xe(_e.touches),Be=je/ue;$(Ye=>{const we=Math.max(1,Math.min(4,Ye*Be));return we===1&&Q({x:0,y:0}),we}),le(je);const Re=Se(_e.touches);if(de){const Ye=U();Q(we=>({x:Math.max(-Ye.x,Math.min(Ye.x,we.x+(Re.x-de.x))),y:Math.max(-Ye.y,Math.min(Ye.y,we.y+(Re.y-de.y)))}))}K(Re)}else if(_e.touches.length===1&&L&&F>1){_e.preventDefault();const je=_e.touches[0].clientX-ae.x,Be=_e.touches[0].clientY-ae.y,Re=U();Q({x:Math.max(-Re.x,Math.min(Re.x,je)),y:Math.max(-Re.y,Math.min(Re.y,Be))})}},fe=_e=>{_e.touches.length<2&&(le(null),K(null)),_e.touches.length===0&&re(!1)},ke=()=>{$(1),Q({x:0,y:0})},Ee=b?"":Ra(o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${y}`:`/api/v1/printers/${s}/camera/snapshot?t=${y}`),Ae=p||b||M;return s?a.jsxs("div",{ref:se,className:"min-h-screen bg-black flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[a.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[a.jsx(yx,{className:"w-4 h-4"}),Y?.name||`Printer ${s}`]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[a.jsx("button",{onClick:()=>X("stream"),disabled:Ae,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),a.jsx("button",{onClick:()=>X("snapshot"),disabled:Ae,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),a.jsx("button",{onClick:()=>j.mutate(!D?.chamber_light),disabled:!D?.connected||j.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${D?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:a.jsx(YO,{on:D?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>d(!0),disabled:!z||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${z&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(z?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:a.jsx(zP,{className:"w-4 h-4 text-bambu-gray"})}),a.jsx("button",{onClick:V,disabled:Ae,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:a.jsx(vr,{className:`w-4 h-4 text-bambu-gray ${Ae?"animate-spin":""}`})}),a.jsx("button",{onClick:J,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?a.jsx(bQ,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Ige,{className:"w-4 h-4 text-bambu-gray"})})]})]}),a.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:R,onMouseUp:ne,onMouseLeave:ne,onTouchStart:ye,onTouchMove:ve,onTouchEnd:fe,style:{touchAction:"none"},children:a.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(p||b)&&!M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:a.jsxs("div",{className:"text-center",children:[a.jsx(vr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Wu,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:A,attempt:Math.min(P+1,fk),max:fk})}),a.jsx("button",{onClick:V,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),u&&!M&&a.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:a.jsxs("div",{className:"text-center p-4",children:[a.jsx(Ln,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),a.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),a.jsx("button",{onClick:V,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),a.jsx("img",{ref:te,src:Ee,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${F}) translate(${I.x/F}px, ${I.y/F}px) rotate(${Y?.camera_rotation||0}deg)`,...Y?.camera_rotation===90||Y?.camera_rotation===270?{maxWidth:"100vh",maxHeight:"100vw"}:{},cursor:F>1?L?"grabbing":"grab":"default"},onError:Ee?ce:void 0,onLoad:Ee?O:void 0,onMouseDown:oe,draggable:!1},y),a.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:[a.jsx("button",{onClick:me,disabled:F<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:a.jsx(xO,{className:"w-4 h-4 text-white"})}),a.jsxs("button",{onClick:ke,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(F*100),"%"]}),a.jsx("button",{onClick:ie,disabled:F>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:a.jsx(bO,{className:"w-4 h-4 text-white"})})]})]})}),a.jsx(XO,{printerId:s,isOpen:c,onClose:()=>d(!1)})]}):a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function Nnt(t,e,n){if(!t)return"";if(!e)return t;const r=e.match(/plate_(\d+)\.gcode/);return r&&parseInt(r[1],10)>1?`${t} — ${n("printers.plateNumber","Plate {{number}}",{number:r[1]})}`:t}function Cnt(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),i=t.get("camera"),s=i!=="false"&&i!=="0";return{size:t.get("size")||"medium",fps:r,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 Pnt(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 Tnt(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 Ant(){const{printerId:t}=Cw(),[e]=eO(),{t:n}=Lt(),r=mn(),i=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>Cnt(e),[e]),c=Tnt(l.size),{data:d}=et({queryKey:["printer",i],queryFn:()=>he.getPrinter(i),enabled:i>0}),{data:u}=et({queryKey:["printerStatus",i],queryFn:()=>he.getPrinterStatus(i),enabled:i>0,refetchInterval:2e3}),{data:m}=et({queryKey:["settings"],queryFn:he.getSettings}),p=m?.time_format||"system";w.useEffect(()=>{if(!i)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(_);return k.onmessage=P=>{try{const N=JSON.parse(P.data);N.type==="printer_status"&&N.printer_id===i&&r.setQueryData(["printerStatus",i],N.status)}catch{}},k.onerror=()=>{},()=>{k.close()}},[i,r]),w.useEffect(()=>(document.title=d?`${d.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[d,n]);const f=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!i)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!u)return a.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:a.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const y=u.state==="RUNNING"||u.state==="PAUSE",v=u.progress||0,b=Ra(`/api/v1/printers/${i}/camera/stream?fps=${l.fps}&t=${s}`);return a.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&a.jsx("img",{src:b,alt:n("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),a.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:a.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),a.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:a.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&d&&a.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[a.jsx(Pr,{className:`${c.icon} text-white/70`}),a.jsx("span",{className:`${c.text} text-white font-medium`,children:d.name})]}),l.showFilename&&u.current_print&&a.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:Nnt(u.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,""),u.gcode_file,n)}),l.showStatus&&a.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:Pnt(u,n)}),l.showProgress&&y&&a.jsxs("div",{className:"mb-3",children:[a.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[a.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),a.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),a.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:a.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),y&&(l.showLayers||l.showEta)&&a.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&&a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(ea,{className:c.icon}),a.jsxs("span",{className:c.text,children:[a.jsx("span",{className:"text-white",children:u.layer_num}),a.jsx("span",{className:"mx-1",children:"/"}),a.jsx("span",{children:u.total_layers})]})]}),l.showEta&&u.remaining_time!=null&&u.remaining_time>0&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(Pc,{className:c.icon}),a.jsx("span",{className:`${c.text} text-white`,children:ls(u.remaining_time*60)})]}),a.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[a.jsx(rr,{className:c.icon}),a.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",vO(u.remaining_time,p,n)]})]})]})]}),!y&&a.jsx("div",{className:`${c.text} text-white/70 py-2`,children:u.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function Mnt(){const{t}=Lt(),{id:e}=Cw(),{mode:n}=cg(),{data:r,isLoading:i,error:s}=et({queryKey:["external-link",e],queryFn:()=>he.getExternalLink(Number(e)),enabled:!!e});return i?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[a.jsx(Ln,{className:"w-12 h-12"}),a.jsx("p",{children:t("common.linkNotFound")})]}):a.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function rX(){const{id:t}=Cw(),e=Eo(),n=mn(),{t:r}=Lt(),{showToast:i}=xn(),s=!!t,[o,l]=w.useState(""),[c,d]=w.useState(""),[u,m]=w.useState([]),[p,f]=w.useState(""),[y,v]=w.useState(!1),{data:b,isLoading:g}=et({queryKey:["group",t],queryFn:()=>he.getGroup(Number(t)),enabled:s}),{data:_,isLoading:k}=et({queryKey:["permissions"],queryFn:()=>he.getPermissions()});s&&b&&!y&&(l(b.name),d(b.description||""),m(b.permissions),v(!0));const P=lt({mutationFn:ee=>he.createGroup(ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.created")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),N=lt({mutationFn:ee=>he.updateGroup(Number(t),ee),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),i(r("groups.toast.updated")),e("/settings?tab=users")},onError:ee=>{i(ee.message,"error")}}),M=P.isPending||N.isPending,T=()=>{if(!o.trim()){i(r("groups.toast.enterGroupName"),"error");return}s?N.mutate({name:o!==b?.name?o:void 0,description:c,permissions:u}):P.mutate({name:o,description:c||void 0,permissions:u})},A=ee=>{m(ue=>ue.includes(ee)?ue.filter(le=>le!==ee):[...ue,ee])},C=(ee,ue)=>{const le=ee.permissions.map(de=>de.value);m(de=>{const K=de.filter(te=>!le.includes(te));return ue?[...K,...le]:K})},F=ee=>ee.permissions.every(ue=>u.includes(ue.value)),$=ee=>{const ue=ee.permissions.filter(le=>u.includes(le.value)).length;return ue>0&&ue{_&&m(_.all_permissions)},Q=()=>{m([])},L=p.toLowerCase(),re=w.useMemo(()=>_?L?_.categories.map(ee=>({...ee,permissions:ee.permissions.filter(ue=>ue.label.toLowerCase().includes(L))})).filter(ee=>ee.permissions.length>0):_.categories:[],[_,L]),ae=_?.all_permissions.length??0;return g||k?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(ct,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.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:a.jsx(uQ,{className:"w-5 h-5"})}),a.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&b?.is_system&&a.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:[a.jsx(Ln,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),a.jsx("input",{type:"text",value:o,onChange:ee=>l(ee.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:r("groups.form.groupNamePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),a.jsx("input",{type:"text",value:c,onChange:ee=>d(ee.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:r("groups.form.descriptionPlaceholder")})]})]}),a.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:u.length})," / ",ae]}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:I,children:r("groups.editor.selectAll")}),a.jsx(Ie,{size:"sm",variant:"ghost",onClick:Q,children:r("groups.editor.clearAll")})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),a.jsx("input",{type:"text",value:p,onChange:ee=>f(ee.target.value),placeholder:r("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"})]})]}),re.length===0?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:re.map(ee=>{const ue=_.categories.find(se=>se.name===ee.name),le=ue.permissions.filter(se=>u.includes(se.value)).length,de=ue.permissions.length,K=F(ue),te=$(ue);return a.jsxs(Dt,{children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>C(ue,!K),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${K?"bg-bambu-green border-bambu-green":te?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[K&&a.jsx(Kr,{className:"w-3 h-3 text-white"}),te&&!K&&a.jsx(rN,{className:"w-3 h-3 text-white"})]}),a.jsx(Wb,{className:"w-4 h-4 text-bambu-gray shrink-0"}),a.jsx("span",{className:"text-white font-medium text-sm",children:ee.name})]}),a.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[le,"/",de]})]}),a.jsx("div",{className:"p-3 space-y-1",children:ee.permissions.map(se=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u.includes(se.value),onChange:()=>A(se.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"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:se.label})]},se.value))})]},ee.name)})}),a.jsx("div",{className:"h-16"}),a.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:[a.jsx(Ie,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),a.jsx(Ie,{onClick:T,disabled:M||!o.trim(),children:M?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const qL={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function ble(t,e=!1){const n={};return e?(t.material||(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 xle=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],jnt=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],M0=["Basic","Matte","Silk","Silk+","Tough","Tough+","HF","High Flow","Engineering","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"],yle=[{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"}],Ent=[{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"}],aX=[...yle,...Ent],vle="bambuddy-recent-colors",Dnt=8,Fnt=[{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 Jh(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["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 r="",i=-1;for(const c of n){const d=e.toUpperCase().indexOf(c.toUpperCase());if(d!==-1){r=c,i=d;break}}let s="";i>0&&(s=e.substring(0,i).trim(),s=s.replace(/[-_\s]+$/,""));let o="";i!==-1&&r&&(o=e.substring(i+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of M0)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of M0){const d=new RegExp(`\\s+${c}$`,"i");if(d.test(s)){l=c,s=s.replace(d,"").trim();break}}return{brand:s,material:r,variant:l}}function wle(t,e){const n=new Set(jnt);for(const r of t){const{brand:i}=Jh(r.name);i&&i.length>1&&n.add(i)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:i}=Jh(r.name);i&&i.length>1&&n.add(i)}return Array.from(n).sort((r,i)=>r.localeCompare(i))}function Rnt(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const i=r.name.replace(/@.*$/,"").trim(),s=n.get(i);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(i,{code:o,name:i,displayName:i,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,i)=>r.displayName.localeCompare(i.displayName))}function Sle(t,e,n){if(t.length>0){const r=[],i=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=i.get(o);l?l.allCodes.push(s.setting_id):i.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(i.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=Rnt(n);if(r.length>0)return r}return Fnt}function _le(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(i=>i.code.toLowerCase()===r||i.allCodes.some(s=>s.toLowerCase()===r))}return n}function kle(){try{const t=localStorage.getItem(vle);if(t)return JSON.parse(t)}catch{}return[]}function Nle(t,e){const n=e.filter(i=>i.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,Dnt);try{localStorage.setItem(vle,JSON.stringify(r))}catch{}return r}function h3(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),i=Jh(r);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())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function Cle({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:i,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:d,quickAdd:u,quantity:m,onQuantityChange:p,errors:f}){const{t:y}=Lt(),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[k,P]=w.useState(!1),[N,M]=w.useState(!1),[T,A]=w.useState(""),[C,F]=w.useState(""),[$,I]=w.useState(""),[Q,L]=w.useState(String(t.label_weight)),[re,ae]=w.useState(!1),ee=w.useRef(null),ue=w.useRef(null),le=w.useRef(null),de=w.useRef(null);w.useEffect(()=>{const B=Y=>{ee.current&&!ee.current.contains(Y.target)&&b(!1),de.current&&!de.current.contains(Y.target)&&M(!1),ue.current&&!ue.current.contains(Y.target)&&_(!1),le.current&&!le.current.contains(Y.target)&&P(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]);const K=w.useMemo(()=>{if(!i)return l;const B=i.toLowerCase();return l.filter(Y=>Y.displayName.toLowerCase().includes(B)||Y.code.toLowerCase().includes(B))},[l,i]),te=w.useMemo(()=>{if(!T)return c;const B=T.toLowerCase();return c.filter(D=>D.toLowerCase().includes(B)).sort((D,j)=>{const z=D.toLowerCase()===B,W=j.toLowerCase()===B;return z&&!W?-1:!z&&W?1:D.localeCompare(j)})},[c,T]),se=w.useMemo(()=>{if(!C)return M0;const B=C.toLowerCase();return M0.filter(Y=>Y.toLowerCase().includes(B))},[C]),be=w.useMemo(()=>{if(!$)return d;const B=$.toLowerCase();return d.filter(D=>D.toLowerCase().includes(B)).sort((D,j)=>{const z=D.toLowerCase()===B,W=j.toLowerCase()===B;return z&&!W?-1:!z&&W?1:D.localeCompare(j)})},[$,d]);w.useEffect(()=>{re||L(String(t.label_weight))},[t.label_weight,re]);const Ne=B=>{e("slicer_filament",B.code),s(B.displayName),b(!1);const Y=Jh(B.name);Y.material&&e("material",Y.material),Y.brand&&e("brand",Y.brand),Y.variant&&e("subtype",Y.variant)};return a.jsxs("div",{className:"space-y-4",children:[!u&&a.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-3 h-3 animate-spin"})," ",y("inventory.loadingPresets")]}):n?a.jsxs(a.Fragment,{children:[a.jsx(Jx,{className:"w-3 h-3 text-bambu-green"})," ",y("inventory.cloudConnected")]}):a.jsxs(a.Fragment,{children:[a.jsx(Wpe,{className:"w-3 h-3"})," ",y("inventory.cloudNotConnected")]})}),!u&&a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.slicerPreset")," *"]}),a.jsxs("div",{className:"relative",ref:ee,children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:y("inventory.searchPresets"),value:i,onChange:B=>{s(B.target.value),b(!0)},onFocus:()=>{b(!0),s("")}}),v&&a.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:K.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noPresetsFound")}):K.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary truncate ${o?.code===B.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>Ne(B),children:B.displayName},B.code))})]}),o&&a.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[y("inventory.selectedPreset"),": ",a.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),f?.slicer_filament&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.slicer_filament})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.material")," *"]}),a.jsxs("div",{className:"relative",ref:de,children:[a.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:y("inventory.selectMaterial"),value:N?$:t.material,onChange:B=>{I(B.target.value),M(!0)},onFocus:()=>{M(!0),I("")}}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&a.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:[be.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):be.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",B),M(!1),I("")},children:B},B)),$&&!be.includes($)&&a.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",$),M(!1),I("")},children:y("inventory.useCustomMaterial",{material:$})})]})]}),f?.material&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.material})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.brand"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:ue,children:[a.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:y("inventory.searchBrand"),value:g?T:t.brand,onChange:B=>{A(B.target.value),_(!0)},onFocus:()=>{_(!0),A("")}}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),g&&a.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:[te.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):te.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",B),_(!1),A("")},children:B},B)),T&&!te.includes(T)&&a.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",T),_(!1),A("")},children:y("inventory.useCustomBrand",{brand:T})})]})]}),f?.brand&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.brand})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[y("inventory.subtype"),!u&&" *"]}),a.jsxs("div",{className:"relative",ref:le,children:[a.jsx("input",{type:"text",value:k?C:t.subtype,onChange:B=>{F(B.target.value),P(!0)},onFocus:()=>{P(!0),F("")},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"}),a.jsx(Fn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),k&&a.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:[se.length===0?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:y("inventory.noResults")}):se.map(B=>a.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===B?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",B),P(!1),F("")},children:B},B)),C&&!M0.some(B=>B.toLowerCase()===C.toLowerCase().trim())&&a.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",C),P(!1),F("")},children:y("inventory.useCustomBrand",{brand:C})})]})]}),f?.subtype&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:f.subtype})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.labelWeight")}),a.jsxs("div",{className:"relative",children:[a.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:Q,min:0,onFocus:()=>ae(!0),onChange:B=>L(B.target.value),onBlur:()=>{ae(!1);const B=Q.trim(),Y=Number(B);if(!B||!Number.isFinite(Y)||Y<0){L(String(t.label_weight));return}const D=Math.round(Y);e("label_weight",D),L(String(D))}}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),u&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:y("inventory.quantity")}),a.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:B=>{const Y=Math.max(1,Math.min(100,parseInt(B.target.value)||1));p(Y)}})]})]})}function Ple({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=t.rgba.replace("#","").substring(0,6),m=g=>u.toUpperCase()===g.toUpperCase(),p=(g,_)=>{e("rgba",g.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:g})},f=w.useMemo(()=>{if(i.length===0)return[];const g=t.brand?.trim(),_=t.material?.toLowerCase().trim(),k=t.subtype?.toLowerCase().trim();if(!g&&!_)return[];const P=g?g.toLowerCase().split(/[\s\-_]+/).filter(T=>T.length>=2):[],N=T=>{if(P.length===0)return!0;const A=T.toLowerCase();return P.some(C=>A.includes(C))};if(g&&!_){const T=i.filter(A=>N(A.manufacturer));if(T.length>0)return T.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}))}const M=_&&k?`${_} ${k}`:"";if(M){const T=i.filter(C=>N(C.manufacturer)&&C.material?.toLowerCase()===M);if(T.length>0)return T.map(C=>({name:C.color_name,hex:C.hex_color.replace("#","").substring(0,6),manufacturer:C.manufacturer,material:typeof C.material=="string"?C.material:void 0}));const A=M.replace(/\+$/,"");if(A!==M){const C=i.filter(F=>N(F.manufacturer)&&F.material?.toLowerCase()===A);if(C.length>0)return C.map(F=>({name:F.color_name,hex:F.hex_color.replace("#","").substring(0,6),manufacturer:F.manufacturer,material:typeof F.material=="string"?F.material:void 0}))}}if(_){const T=i.filter(A=>N(A.manufacturer)&&(!A.material||A.material.toLowerCase().startsWith(_)));if(T.length>0)return T.map(A=>({name:A.color_name,hex:A.hex_color.replace("#","").substring(0,6),manufacturer:A.manufacturer,material:typeof A.material=="string"?A.material:void 0}))}return[]},[i,t.brand,t.material,t.subtype]),y=w.useMemo(()=>{if(!c)return f;if(f.length===0)return[];const g=c.toLowerCase();return f.filter(k=>k.name.toLowerCase().includes(g)||(k.manufacturer?.toLowerCase().includes(g)??!1)||(k.material?.toLowerCase().includes(g)??!1))},[c,f]),v=f.length>0,b=w.useMemo(()=>c?aX.filter(g=>g.name.toLowerCase().includes(c.toLowerCase())):o?aX:yle,[c,o]);return a.jsxs("div",{className:"space-y-3",children:[a.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${u}`}}),n.length>0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[a.jsx(rr,{className:"w-3 h-3"}),a.jsx("span",{children:s("inventory.recentColors")})]}),a.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name},g.hex))})]}),a.jsxs("div",{className:"relative",children:[a.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),a.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:g=>d(g.target.value)})]}),v?a.jsxs("div",{className:"space-y-1.5",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[y.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name,children:a.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:g.manufacturer&&g.material?`${g.name} (${g.manufacturer} — ${g.material})`:g.manufacturer?`${g.name} (${g.manufacturer})`:g.name})},`${g.hex}-${g.name}-${g.manufacturer??""}`)),y.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):a.jsxs("div",{className:"space-y-1.5",children:[a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&a.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?a.jsxs(a.Fragment,{children:[s("inventory.showLess")," ",a.jsx(Yl,{className:"w-3 h-3"})]}):a.jsxs(a.Fragment,{children:[s("inventory.showAll")," ",a.jsx(Fn,{className:"w-3 h-3"})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[b.map(g=>a.jsx("button",{type:"button",onClick:()=>p(g.hex,g.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${m(g.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${g.hex}`},title:g.name,children:a.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:g.name})},g.hex)),b.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),a.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:g=>e("color_name",g.target.value)})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),a.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:u.toUpperCase(),onChange:g=>{const _=g.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),a.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${u}`,onChange:g=>{const _=g.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function Lnt({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:i}){const{t:s}=Lt(),[o,l]=w.useState(!1),[c,d]=w.useState(""),u=w.useRef(null),m=w.useRef(null);w.useEffect(()=>{const v=b=>{u.current&&!u.current.contains(b.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(b=>b.weight===e);if(r){const b=t.find(g=>g.id===r);if(b&&b.weight===e)return}v.length===1?i(v[0].id):v.length===0&&r!==null&&i(null)},[e,t,r,i]);const p=w.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=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),y=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(b=>b.id===r);if(v)return v.name}return f.length>0?f[0].name:""},[o,c,r,t,f]);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(vbe,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsxs("div",{className:"flex-1 min-w-0 relative",ref:u,children:[a.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:y,onFocus:()=>{l(!0),d("")},onChange:v=>{d(v.target.value),l(!0)}}),o&&a.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?a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):p.map(v=>a.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 ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{i(v.id),n(v.weight),l(!1),d("")},children:[a.jsx("span",{className:"truncate",children:v.name}),a.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),a.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[a.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&&n(b)}}),a.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function Tle({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:i}=Lt(),{showToast:s}=xn(),[o,l]=w.useState(""),[c,d]=w.useState(!1),[u,m]=w.useState(""),[p,f]=w.useState(!1),y=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+y;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{p||m(String(y))},[p,y]),a.jsxs("div",{className:"space-y-4",children:[a.jsx(Lnt,{catalog:n,value:t.core_weight,onChange:b=>e("core_weight",b),catalogId:t.core_weight_catalog_id,onCatalogIdChange:b=>e("core_weight_catalog_id",b)}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.currentWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:u,min:0,max:t.label_weight,onFocus:()=>f(!0),onChange:b=>{m(b.target.value)},onBlur:()=>{f(!1);const b=u.trim(),g=Number(b);if(!b||!Number.isFinite(g)||g<0||g>t.label_weight){m(String(y));return}const _=Math.round(g);e("weight_used",Math.max(0,t.label_weight-_)),m(String(_))},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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.measuredWeight")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:"number",value:o,min:0,onFocus:()=>d(!0),onChange:b=>{l(b.target.value)},onBlur:()=>{d(!1);const b=o.trim(),g=Number(b),_=t.core_weight,k=t.core_weight+t.label_weight;if(!b||!Number.isFinite(g)||g<_||g>k){s(i("inventory.measuredWeightError",{min:_,max:k}),"error"),l(String(v));return}const P=Math.round(g),N=Math.max(0,Math.min(t.label_weight,P-t.core_weight));e("weight_used",Math.max(0,t.label_weight-N)),l(String(P))},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"}),a.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),a.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.costPerKg","Cost per kg")}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsxs("div",{className:"relative flex-1",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),a.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:b=>{const g=b.target.value===""?null:parseFloat(b.target.value);e("cost_per_kg",g)},style:{paddingLeft:`${Math.max(2,r.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"})]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i("inventory.note")}),a.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:i("inventory.notePlaceholder"),value:t.note,onChange:b=>e("note",b.target.value)})]})]})}function Ale({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:i,setExpandedPrinters:s}){const{t:o}=Lt(),l=p=>{s(f=>{const y=new Set(f);return y.has(p)?y.delete(p):y.add(p),y})},c=(p,f,y)=>{const v=`${p}:${f}:${y??"null"}`,b=`${p}:${y??"null"}`;r(g=>{const _=new Set(g);if(_.has(v))_.delete(v);else{for(const k of Array.from(_)){const P=k.split(":");`${P[0]}:${P[2]}`===b&&_.delete(k)}_.add(v)}return _})},d=()=>{const p=new Set;for(const{printer:f,calibrations:y}of e){if(!f.connected)continue;const v=y.filter(g=>h3(g,t)),b=new Map;for(const g of v){const _=`${g.extruder_id??"null"}`;b.has(_)||b.set(_,[]),b.get(_).push(g)}for(const[g,_]of b)if(_.length>0){const P=[..._].sort((N,M)=>M.k_value-N.k_value)[0];p.add(`${f.id}:${P.cali_idx}:${g}`)}}r(p)};if(!t.material)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return a.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:a.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const u=e.reduce((p,{printer:f,calibrations:y})=>f.connected?p+y.filter(v=>h3(v,t)).length:p,0),m=(p,f)=>{const y=`${p.id}:${f.cali_idx}:${f.extruder_id??"null"}`,v=n.has(y);return a.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:[a.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"}),a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:f.name||f.filament_id})}),a.jsx("div",{className:"flex items-center gap-2 shrink-0",children:a.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 a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.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&&a.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:[a.jsx(wx,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",u,")"]})]}),a.jsx("div",{className:"space-y-3",children:e.map(({printer:p,calibrations:f})=>{const y=i.has(String(p.id)),v=f.filter(P=>h3(P,t)),b=v.length,g=v.some(P=>P.extruder_id!==void 0&&P.extruder_id!==null&&P.extruder_id>0),_=v.filter(P=>P.extruder_id===1),k=v.filter(P=>P.extruder_id===0||P.extruder_id===void 0||P.extruder_id===null);return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.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:[a.jsxs("div",{className:"flex items-center gap-3",children:[y?a.jsx(Fn,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Va,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"font-medium text-white",children:p.name}),b>0?a.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")]}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),a.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")})]}),y&&a.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:p.connected?b===0?a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):g?a.jsxs(a.Fragment,{children:[_.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),a.jsx("div",{className:"space-y-2",children:_.map(P=>m(p,P))})]}),k.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),a.jsx("div",{className:"space-y-2",children:k.map(P=>m(p,P))})]})]}):a.jsx("div",{className:"space-y-2",children:v.map(P=>m(p,P))}):a.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},p.id)})}),n.size>0&&a.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function Ont(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const Int={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function znt({spoolId:t}){const{t:e}=Lt(),n=mn(),{showToast:r}=xn(),{data:i,isLoading:s}=et({queryKey:["spool-usage",t],queryFn:()=>he.getSpoolUsageHistory(t)}),o=lt({mutationFn:()=>he.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(ct,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!i||i.length===0?a.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[a.jsx(rr,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),a.jsxs(Ie,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[a.jsx(un,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),a.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:i.map(l=>a.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-bambu-gray",children:Ont(l.created_at)}),l.print_name&&a.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[a.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),a.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),a.jsx("span",{className:Int[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function Unt({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:i,onSpoolsCreated:s}){const{t:o}=Lt(),l=mn(),{showToast:c}=xn(),d=!!n,[u,m]=w.useState(qL),[p,f]=w.useState({}),[y,v]=w.useState("filament"),[b,g]=w.useState(!1),[_,k]=w.useState(!1),[P,N]=w.useState(1),[M,T]=w.useState(!1),[A,C]=w.useState(!1),[F,$]=w.useState([]),[I,Q]=w.useState(""),[L,re]=w.useState([]),[ae,ee]=w.useState([]),[ue,le]=w.useState([]),[de,K]=w.useState([]),[te,se]=w.useState([]),[be,Ne]=w.useState(new Set),[B,Y]=w.useState(new Set),D=r.length>0?r:te,j=w.useMemo(()=>be.size,[be]);w.useEffect(()=>{K(kle())},[]),w.useEffect(()=>{t&&((async()=>{C(!0);try{const Ee=await he.getCloudStatus();if(T(Ee.is_authenticated),Ee.is_authenticated){const Ae=await he.getFilamentPresets();$(Ae)}}catch(Ee){console.error("Failed to fetch cloud presets:",Ee),T(!1)}finally{C(!1)}})(),he.getSpoolCatalog().then(re).catch(console.error),he.getColorCatalog().then(le).catch(console.error),he.getLocalPresets().then(Ee=>ee(Ee.filament)).catch(console.error),r.length===0&&(async()=>{try{const Ee=await he.getPrinters(),Ae=await Promise.all(Ee.map(je=>he.getPrinterStatus(je.id).catch(()=>null))),_e=[];for(let je=0;je({cali_idx:De.slot_id,filament_id:De.filament_id,setting_id:De.setting_id||"",name:De.name,k_value:parseFloat(De.k_value)||0,n_coef:parseFloat(De.n_coef)||0,extruder_id:De.extruder_id,nozzle_diameter:De.nozzle_diameter}))}catch{}_e.push({printer:{...Be,connected:Ye},calibrations:we})}se(_e)}catch(Ee){console.error("Failed to fetch printer calibrations:",Ee)}})())},[t,r.length]);const z=w.useMemo(()=>Sle(F,new Set,ae),[F,ae]),W=w.useMemo(()=>{const ke=wle(F,ae),Ee=ue.map(_e=>_e.manufacturer?.trim()).filter(_e=>!!_e),Ae=new Set([...ke,...Ee]);return Array.from(Ae).sort((_e,je)=>_e.localeCompare(je))},[F,ae,ue]),q=w.useMemo(()=>{const ke=ue.map(Ae=>Ae.material?.trim()).filter(Ae=>!!Ae),Ee=new Set([...xle,...ke]);return Array.from(Ee).sort((Ae,_e)=>Ae.localeCompare(_e))},[ue]),ce=w.useMemo(()=>{const ke=[];for(const Ee of ue){const Ae=Ee.manufacturer?.trim(),_e=Ee.material?.trim();Ae&&_e&&ke.push({brand:Ae,material:_e})}for(const Ee of F){const Ae=Jh(Ee.name);Ae.brand&&Ae.material&&ke.push({brand:Ae.brand,material:Ae.material})}for(const Ee of ae){const Ae=Jh(Ee.name),_e=Ee.filament_vendor?.trim()||Ae.brand,je=Ae.material;_e&&je&&ke.push({brand:_e,material:je})}return ke},[F,ue,ae]),O=w.useMemo(()=>{const ke=new Map;for(const Ee of ce){const Ae=Ee.brand.toLowerCase(),_e=Ee.material.toLowerCase();ke.has(Ae)||ke.set(Ae,new Set),ke.get(Ae).add(_e)}return ke},[ce]),G=w.useMemo(()=>{const ke=new Map;for(const Ee of ce){const Ae=Ee.brand.toLowerCase(),_e=Ee.material.toLowerCase();ke.has(_e)||ke.set(_e,new Set),ke.get(_e).add(Ae)}return ke},[ce]),X=w.useMemo(()=>{if(!u.material)return W;const ke=u.material.toLowerCase(),Ee=G.get(ke);return!Ee||Ee.size===0?W:W.filter(Ae=>Ee.has(Ae.toLowerCase()))},[W,u.material,G]),V=w.useMemo(()=>{if(!u.brand)return q;const ke=u.brand.toLowerCase(),Ee=O.get(ke);return!Ee||Ee.size===0?q:q.filter(Ae=>Ee.has(Ae.toLowerCase()))},[q,u.brand,O]),J=w.useMemo(()=>_le(u.slicer_filament,z),[u.slicer_filament,z]);w.useEffect(()=>{if(t){if(n)if(m({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),Q(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const ke=new Set;for(const Ee of n.k_profiles)Ee.cali_idx!==null&&Ee.cali_idx!==void 0&&ke.add(`${Ee.printer_id}:${Ee.cali_idx}:${Ee.extruder??"null"}`);Ne(ke)}else Ne(new Set);else m(qL),Q(""),Ne(new Set),k(!1),N(1);f({}),v("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&D.length>0&&Y(new Set(D.map(ke=>String(ke.printer.id))))},[t,D]);const ie=(ke,Ee)=>{m(Ae=>({...Ae,[ke]:Ee})),ke==="weight_used"&&g(!0),p[ke]&&f(Ae=>({...Ae,[ke]:void 0}))},me=ke=>{K(Ee=>Nle(ke,Ee))},pe=lt({mutationFn:ke=>he.createSpool(ke),onSuccess:async ke=>{be.size>0&&ke?.id&&await ye(ke.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s([ke]),c(o("inventory.spoolCreated"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),oe=lt({mutationFn:({data:ke,qty:Ee})=>he.bulkCreateSpools(ke,Ee),onSuccess:async ke=>{if(be.size>0)for(const Ee of ke)await ye(Ee.id);await l.invalidateQueries({queryKey:["inventory-spools"]}),s&&s(ke),c(o("inventory.spoolsCreated",{count:ke.length}),"success"),e()},onError:ke=>{c(ke.message,"error")}}),U=lt({mutationFn:ke=>he.updateSpool(n.id,ke),onSuccess:async()=>{n?.id&&await ye(n.id),await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.spoolUpdated"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),R=lt({mutationFn:()=>he.updateSpool(n.id,{tag_uid:null,tray_uuid:null,tag_type:null,data_origin:null}),onSuccess:async()=>{await l.invalidateQueries({queryKey:["inventory-spools"]}),c(o("inventory.tagDeleted","Tag removed"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),{data:ne}=et({queryKey:["spool-assignments"],queryFn:()=>he.getAssignments(),enabled:t&&d}),xe=n?ne?.find(ke=>ke.spool_id===n.id):void 0,Se=lt({mutationFn:()=>{if(!xe)throw new Error("No assignment");return he.unassignSpool(xe.printer_id,xe.ams_id,xe.tray_id)},onSuccess:async()=>{await l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.unassignSuccess","Spool unassigned"),"success"),e()},onError:ke=>{c(ke.message,"error")}}),ye=async ke=>{if(be.size===0){try{await he.saveSpoolKProfiles(ke,[])}catch{}return}const Ee=[];for(const Ae of be){const[_e,je,Be]=Ae.split(":"),Re=parseInt(_e),Ye=parseInt(je),we=Be==="null"?0:parseInt(Be),$e=D.find(De=>De.printer.id===Re);if($e){const De=$e.calibrations.find(Xe=>Xe.cali_idx===Ye);De&&Ee.push({printer_id:Re,extruder:we,nozzle_diameter:De.nozzle_diameter||"0.4",k_value:De.k_value,name:De.name||null,cali_idx:De.cali_idx,setting_id:De.setting_id||null})}}if(Ee.length>0)try{await he.saveSpoolKProfiles(ke,Ee)}catch(Ae){console.error("Failed to save K-profiles:",Ae)}};if(w.useEffect(()=>{if(!t)return;const ke=Ee=>{Ee.key==="Escape"&&e()};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[t,e]),!t)return null;const ve=()=>{const ke=ble(u,_);if(!ke.isValid){f(ke.errors),(ke.errors.slicer_filament||ke.errors.material||ke.errors.brand||ke.errors.subtype)&&v("filament");return}const Ee=J?.displayName||I||null,Ae={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Ee,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!d||b)&&(Ae.weight_used=u.weight_used),d?U.mutate(Ae):P>1?oe.mutate({data:Ae,qty:P}):pe.mutate(Ae)},fe=pe.isPending||oe.isPending||U.isPending||R.isPending||Se.isPending;return a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:o(d?"inventory.editSpool":"inventory.addSpool")}),a.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Bt,{className:"w-5 h-5"})})]}),!d&&a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4 text-amber-400"}),a.jsx("span",{className:"text-sm text-white",children:o("inventory.quickAdd")})]}),a.jsx("button",{type:"button",onClick:()=>{k(!_),_||v("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${_?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${_?"translate-x-4":"translate-x-0.5"}`})})]}),a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsxs("button",{onClick:()=>v("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(Dw,{className:"w-4 h-4"}),o("inventory.filamentInfoTab")]}),!_&&a.jsxs("button",{onClick:()=>v("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${y==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[a.jsx(npe,{className:"w-4 h-4"}),o("inventory.paProfileTab"),j>0&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:j})]})]}),a.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:y==="filament"?a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.filamentInfo")}),a.jsx(Cle,{formData:u,updateField:ie,cloudAuthenticated:M,loadingCloudPresets:A,presetInputValue:I,setPresetInputValue:Q,selectedPresetOption:J,filamentOptions:z,availableBrands:X,availableMaterials:V,quickAdd:_,quantity:P,onQuantityChange:N,errors:p})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.color")}),a.jsx(Ple,{formData:u,updateField:ie,recentColors:de,onColorUsed:me,catalogColors:ue})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:o("inventory.additional")}),a.jsx(Tle,{formData:u,updateField:ie,spoolCatalog:L,currencySymbol:i})]}),d&&n&&a.jsx("div",{children:a.jsx(znt,{spoolId:n.id})})]}):a.jsx(Ale,{formData:u,updateField:ie,printersWithCalibrations:D,selectedProfiles:be,setSelectedProfiles:Ne,expandedPrinters:B,setExpandedPrinters:Y})}),a.jsxs("div",{className:"flex gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[d&&a.jsxs("div",{className:"flex gap-2 mr-auto",children:[a.jsxs(Ie,{variant:"secondary",onClick:()=>R.mutate(),disabled:fe||!n?.tag_uid,children:[a.jsx(Vu,{className:"w-4 h-4"}),o("inventory.deleteTag","Delete Tag")]}),a.jsxs(Ie,{variant:"secondary",onClick:()=>Se.mutate(),disabled:fe||!xe,children:[a.jsx(qh,{className:"w-4 h-4"}),o("inventory.unassignSpool","Unassign")]})]}),a.jsxs("div",{className:"flex gap-2 ml-auto",children:[a.jsx(Ie,{variant:"secondary",onClick:e,children:o("common.cancel")}),a.jsx(Ie,{onClick:ve,disabled:fe,children:fe?a.jsxs(a.Fragment,{children:[a.jsx(ct,{className:"w-4 h-4 animate-spin"}),o("common.saving")]}):a.jsxs(a.Fragment,{children:[a.jsx(cs,{className:"w-4 h-4"}),o(d?"common.save":"inventory.addSpool")]})})]})]})]})]})}function Bnt({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:i}){const{t:s}=Lt(),[o,l]=w.useState(n),[c,d]=w.useState(null),u=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(P=>({...P})))},[t,n]),w.useEffect(()=>{if(!t)return;const P=N=>{N.key==="Escape"&&e()};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[t,e]),!t)return null;const m=P=>{l(N=>N.map((M,T)=>T===P?{...M,visible:!M.visible}:M))},p=(P,N)=>{N<0||N>=o.length||l(M=>{const T=[...M],[A]=T.splice(P,1);return T.splice(N,0,A),T})},f=(P,N)=>{u.current=N,d(N),P.dataTransfer.effectAllowed="move"},y=(P,N)=>{P.preventDefault(),P.dataTransfer.dropEffect="move";const M=u.current;M!==null&&M!==N&&(p(M,N),u.current=N,d(N))},v=P=>{P.preventDefault()},b=()=>{u.current=null,d(null)},g=()=>{l(r.map(P=>({...P})))},_=()=>{i(o),e()},k=o.filter(P=>P.visible).length;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsx(Dt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:P=>P.stopPropagation(),children:a.jsxs(Rt,{className:"p-6 flex flex-col min-h-0",children:[a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),a.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),a.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",k," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),a.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((P,N)=>a.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===N?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${P.visible?"":"opacity-50"}`,draggable:!0,onDragStart:M=>f(M,N),onDragOver:M=>y(M,N),onDrop:v,onDragEnd:b,children:[a.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:a.jsx(jh,{className:"w-4 h-4"})}),a.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:P.label}),a.jsxs("div",{className:"flex items-center gap-0.5",children:[a.jsx("button",{onClick:()=>p(N,N-1),disabled:N===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:a.jsx(Yl,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>p(N,N+1),disabled:N===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:a.jsx(Fn,{className:"w-4 h-4"})})]}),a.jsx("button",{onClick:()=>m(N),className:`p-1.5 rounded transition-colors ${P.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:P.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:P.visible?a.jsx(Dc,{className:"w-4 h-4"}):a.jsx(Tw,{className:"w-4 h-4"})})]},P.id))}),a.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs(Ie,{variant:"secondary",onClick:g,className:"mr-auto",children:[a.jsx(jo,{className:"w-4 h-4"}),s("inventory.reset")]}),a.jsx(Ie,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),a.jsx(Ie,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function iX(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const Mle="bambuddy-inventory-columns",$k=[{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:"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 Hnt(){try{const t=localStorage.getItem(Mle);if(t){const e=JSON.parse(t),n=new Set($k.map(o=>o.id)),r=new Set(e.map(o=>o.id)),i=e.filter(o=>n.has(o.id)),s=$k.filter(o=>!r.has(o.id));return[...i,...s]}}catch{}return $k.map(t=>({...t}))}function qnt(t){try{localStorage.setItem(Mle,JSON.stringify(t))}catch{}}function xd(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const $nt={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 p3(t,e="system"){if(!t)return"-";const n=Qn(t);return n?V3(n,e):"-"}const Vnt={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",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")},$L={id:({spool:t})=>a.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:p3(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:p3(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?p3(t.last_used,e):"Never"}),rgba:({spool:t})=>a.jsx("div",{className:"flex items-center justify-center",children:a.jsx("span",{className:"w-5 h-5 rounded-full border border-black/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:FT(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>a.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 n=e[t.id];if(!n)return a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,i=n.ams_id===254||n.ams_id===255,s=!i&&n.ams_id>=128,o=uS(n.ams_id,n.tray_id,s,i);return a.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:[r," ",o,n.ams_label?` (${n.ams_label})`:""]})},label_weight:({spool:t})=>a.jsx("span",{className:"text-sm text-white",children:xd(t.label_weight)}),net:({remaining:t})=>a.jsx("span",{className:"text-sm text-white",children:xd(t)}),gross:({spool:t,remaining:e})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:xd(e+t.core_weight)}),added_full:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?xd(t.weight_used):"-"}),printed_total:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>a.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?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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?a.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):a.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>a.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?a.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):a.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})=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:a.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)}%`}})}),a.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 n=t.core_weight_catalog_id!=null?e[t.core_weight_catalog_id]:void 0;return a.jsx("span",{className:"text-sm text-bambu-gray",children:n?.name||"-"})},cost_per_kg:({spool:t,currencySymbol:e})=>a.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 n=t.last_scale_weight;if(n==null)return a.jsx("span",{className:"text-sm text-bambu-gray/50",title:"No scale measurement",children:"-"});const r=t.core_weight||0,i=Math.max(0,t.label_weight-t.weight_used)+r;let s,o;n0?`+${Math.round(s)}`:`${Math.round(s)}`,c=o?`Scale: ${Math.round(n)}g
Calculated: ${Math.round(i)}g
Difference: ${l}g (within tolerance)`:`Scale: ${Math.round(n)}g
Calculated: ${Math.round(i)}g
diff --git a/static/index.html b/static/index.html
index cfee38271..bd9038522 100644
--- a/static/index.html
+++ b/static/index.html
@@ -23,7 +23,7 @@
-
+