diff --git a/CHANGELOG.md b/CHANGELOG.md index 637402f07..d70970c29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ All notable changes to Bambuddy will be documented in this file. - **Library File Print-Usage Tracking** ([#1008](https://github.com/maziggy/bambuddy/issues/1008)) — `LibraryFile.print_count` and `last_printed_at` are now updated on every successful queued print completion. Previously both fields were defined on the model and displayed in the File Manager, but nothing ever wrote to them — every file in every library showed as never printed. Now counts increment cumulatively and `last_printed_at` stamps the completion timestamp (UTC). Failed, cancelled and user-aborted prints are intentionally excluded, so the fields represent "successful usage" rather than "attempted usage." This unblocks sorting the File Manager by last-printed date and is a prerequisite for the scheduled-purge feature requested in #1008. Thanks to @cadtoolbox for the report. ### Improved +- **Color Catalog Default Filter Set to "All Manufacturers"** ([#1039](https://github.com/maziggy/bambuddy/issues/1039)) — Settings → Color Catalog opened with the manufacturer dropdown pre-filtered to *Bambu Lab*, so users searching for a third-party color had to change the dropdown to *All Manufacturers* on every visit. The page now defaults to *All Manufacturers* and lets you narrow down from there. Thanks to @VID-PRO for the suggestion. - **File Manager: Collapse Folders by Default** ([#996](https://github.com/maziggy/bambuddy/issues/996)) — Added a **Collapse** toggle next to **Wrap** in the File Manager sidebar header. When enabled, the folder tree opens with only top-level folders visible on every page load; disabling it restores the previous fully-expanded default. Toggling the preference also immediately re-collapses/re-expands the current tree — no reload required. Persisted to localStorage under `library-collapse-folders`, matching the existing `library-*` preference pattern. Thanks to @AshieTashi for the request. ### Changed diff --git a/frontend/src/components/ColorCatalogSettings.tsx b/frontend/src/components/ColorCatalogSettings.tsx index 8e31c04e0..35fdc742b 100644 --- a/frontend/src/components/ColorCatalogSettings.tsx +++ b/frontend/src/components/ColorCatalogSettings.tsx @@ -13,7 +13,7 @@ export function ColorCatalogSettings() { const [catalog, setCatalog] = useState([]); const [loading, setLoading] = useState(true); const [search, setSearch] = useState(''); - const [filterManufacturer, setFilterManufacturer] = useState('Bambu Lab'); + const [filterManufacturer, setFilterManufacturer] = useState(''); const fileInputRef = useRef(null); // Add/Edit form state diff --git a/static/assets/index-BM-WMBho.js b/static/assets/index-CFcQzo54.js similarity index 99% rename from static/assets/index-BM-WMBho.js rename to static/assets/index-CFcQzo54.js index f8a7287ff..56eeb1522 100644 --- a/static/assets/index-BM-WMBho.js +++ b/static/assets/index-CFcQzo54.js @@ -8704,7 +8704,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ys(t. ${d&&ae?"sm:border-bambu-dark-tertiary border-bambu-green/40":""} ${!d&&!Y?"border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80":""} ${ae?"sm:cursor-default":""} - `,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:J=>{J.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(zr,{className:"w-4 h-4"})}),L?a.jsx("div",{...A,...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(np,{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?ue.getArchivePlateThumbnail(t.archive_id,t.plate_id):ue.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?ue.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ue.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(ma,{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}`,(C?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${P.find(J=>J.index===t.plate_id)?.name||x("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?a.jsx(jo,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewArchive"),children:a.jsx(da,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(jo,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewInFileManager"),children:a.jsx(da,{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(Mr,{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?`${x("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?x("queue.filter.unassigned"):t.printer_name||`${x("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(Dd,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),ys(t.print_time_seconds)]}),t.filament_used_grams&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(XQ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Ttt(t.filament_used_grams)]}),t.created_by_username&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:x("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(xm,{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(Qn,{className:"w-3.5 h-3.5"}),t.scheduled_time?(Jn(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?x?.("queue.time.overdue")??"Overdue":ap(t.scheduled_time,c,x):x?.("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(IQ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("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:x("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(Jd,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("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(Sy,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.gcodeInjection")]})]}),Y&&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(Qn,{className:"w-3 h-3"}),ys(v.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:x("printers.estimatedCompletion"),children:["ETA ",zO(v.remaining_time,c,x)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(ma,{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:J=>J.stopPropagation(),children:[a.jsx(Att,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:x}),a.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[Y&&a.jsx(De,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("printers:control")?x("queue.actions.stopPrint"):x("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(ufe,{className:"w-4 h-4"})}),L&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(De,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("printers:control")?x("queue.actions.startPrint"):x("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(Ji,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?x("common.edit"):x("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:a.jsx(oi,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?x("common.cancel"):x("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"})})]}),te&&a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("queue:create")?x("queue.actions.requeue"):x("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(cr,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?x("common.remove"):x("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})]})]})}function Mtt(){const{t}=Dt(),e=rn(),{showToast:n}=hn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=_r(),[o,l]=w.useState(null),[c,d]=w.useState(""),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(null),[b,g]=w.useState(null),[_,C]=w.useState(null),[P,N]=w.useState([]),[A,T]=w.useState(!1),[F,k]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[D,H]=w.useState(()=>{const Te=localStorage.getItem("queue.historySortAsc");return Te!==null?Te==="true":!1}),[z,Y]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[L,te]=w.useState(()=>{const Te=localStorage.getItem("queue.pendingSortAsc");return Te!==null?Te==="true":!0}),[ae,J]=w.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[le,se]=w.useState(()=>localStorage.getItem("queue.viewMode")||"list");w.useEffect(()=>{localStorage.setItem("queue.historySortBy",F)},[F]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(D))},[D]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",z)},[z]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(L))},[L]),w.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ae))},[ae]),w.useEffect(()=>{localStorage.setItem("queue.viewMode",le)},[le]);const oe=cle(MP(gA,{activationConstraint:{distance:8}}),MP(fA,{coordinateGetter:Ele})),{data:W}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),ne=W?.time_format||"system",{data:fe,isLoading:be}=Ye({queryKey:["queue",o,c],queryFn:()=>ue.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:Pe}=Ye({queryKey:["printers"],queryFn:()=>ue.getPrinters()}),q=it({mutationFn:Te=>ue.updateSettings({queue_shortest_first:Te}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),Q=it({mutationFn:Te=>ue.cancelQueueItem(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),E=it({mutationFn:Te=>ue.removeFromQueue(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),j=it({mutationFn:Te=>ue.stopQueueItem(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),O=it({mutationFn:Te=>ue.startQueueItem(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),K=it({mutationFn:Te=>ue.reorderQueue(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),U=it({mutationFn:async()=>{const Te=fe?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];for(const ve of Te)await ue.removeFromQueue(ve.id);return Te.length},onSuccess:Te=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:Te}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),me=it({mutationFn:Te=>ue.bulkUpdateQueue(Te),onSuccess:Te=>{e.invalidateQueries({queryKey:["queue"]}),N([]),T(!1),n(Te.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),I=it({mutationFn:async Te=>{for(const ve of Te)await ue.cancelQueueItem(ve);return Te.length},onSuccess:Te=>{e.invalidateQueries({queryKey:["queue"]}),N([]),n(t("queue.toast.bulkCancelled",{count:Te}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),G=Te=>{N(ve=>ve.includes(Te)?ve.filter(Ae=>Ae!==Te):[...ve,Te])},X=w.useMemo(()=>{const Te=new Set;return Pe?.forEach(ve=>{ve.location&&Te.add(ve.location)}),fe?.forEach(ve=>{ve.target_location&&Te.add(ve.target_location)}),Array.from(Te).sort()},[Pe,fe]),V=w.useCallback(Te=>u?Te.target_location?Te.target_location===u:Te.printer_id?Pe?.find(Ae=>Ae.id===Te.printer_id)?.location===u:!1:!0,[u,Pe]),ee=w.useMemo(()=>{let Te=fe?.filter(Ae=>Ae.status==="pending")||[];u&&(Te=Te.filter(V));const ve=Ae=>{if(!Ae.scheduled_time)return 0;const Re=Jn(Ae.scheduled_time)?.getTime()??0,Me=Date.now()+4320*60*60*1e3;return Re>Me?0:Re};return W?.queue_shortest_first?[...Te].sort((Ae,Re)=>{const Me=Ae.printer_id??-(Ae.target_model?.charCodeAt(0)??0),Le=Re.printer_id??-(Re.target_model?.charCodeAt(0)??0);if(Me!==Le)return Me-Le;const Oe=Ae.been_jumped?1:0,qe=Re.been_jumped?1:0;if(Oe!==qe)return qe-Oe;const Qe=Ae.print_time_seconds??1/0,tt=Re.print_time_seconds??1/0;return Qe!==tt?Qe-tt:Ae.position-Re.position}):[...Te].sort((Ae,Re)=>{let Me;if(z==="name"){const Le=Ae.archive_name||Ae.library_file_name||"",Oe=Re.archive_name||Re.library_file_name||"";Me=Le.localeCompare(Oe)}else z==="printer"?Me=(Ae.printer_name||"").localeCompare(Re.printer_name||""):z==="time"?Me=ve(Ae)-ve(Re):Me=Ae.position-Re.position;return L?Me:-Me})},[fe,z,L,V,u,W?.queue_shortest_first]),ie=()=>{const Te=ee.map(ve=>ve.id);P.length===Te.length?N([]):N(Te)},ge=w.useMemo(()=>{let Te=fe?.filter(ve=>ve.status==="printing")||[];return u&&(Te=Te.filter(V)),Te},[fe,u,V]),pe=w.useMemo(()=>{const Te=new Set;return ge.forEach(ve=>{ve.printer_id&&Te.add(ve.printer_id)}),Array.from(Te)},[ge]),ce=Pp({queries:pe.map(Te=>({queryKey:["printerStatus",Te],queryFn:()=>ue.getPrinterStatus(Te),refetchInterval:5e3}))}),B=w.useMemo(()=>{const Te={};return pe.forEach((ve,Ae)=>{const Re=ce[Ae];Re?.data?.state&&(Te[ve]=Re.data.state)}),Te},[pe,ce]),R=w.useMemo(()=>{const Te={};return pe.forEach((ve,Ae)=>{const Re=ce[Ae];Re?.data&&(Te[ve]={progress:Re.data.progress??void 0,remaining_time:Re.data.remaining_time??void 0,state:Re.data.state??void 0})}),Te},[pe,ce]),re=w.useMemo(()=>{let Te=fe?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];return u&&(Te=Te.filter(V)),[...Te].sort((ve,Ae)=>{let Re;if(F==="name"){const Me=ve.archive_name||ve.library_file_name||"",Le=Ae.archive_name||Ae.library_file_name||"";Re=Me.localeCompare(Le)}else F==="printer"?Re=(ve.printer_name||"").localeCompare(Ae.printer_name||""):Re=(Jn(Ae.completed_at||Ae.created_at)?.getTime()??0)-(Jn(ve.completed_at||ve.created_at)?.getTime()??0);return D?-Re:Re})},[fe,F,D,V,u]),ke=w.useMemo(()=>ee.reduce((Te,ve)=>Te+(ve.print_time_seconds||0),0),[ee]),Se=w.useMemo(()=>ee.reduce((Te,ve)=>Te+(ve.filament_used_grams||0),0),[ee]),ye=Te=>{const{active:ve,over:Ae}=Te;if(!Ae||ve.id===Ae.id)return;const Re=ee.findIndex(Le=>Le.id===ve.id),Me=ee.findIndex(Le=>Le.id===Ae.id);if(Re!==-1&&Me!==-1){const Oe=yA(ee,Re,Me).map((qe,Qe)=>({id:qe.id,position:Qe+1}));K.mutate(Oe)}};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(vN,{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(vtt,{activeCount:ge.length,pendingCount:ee.length,totalTime:ke,totalWeight:Se,historyCount:re.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:Te=>{const ve=Te.target.value;l(ve==="unassigned"?-1:ve===""?null:Number(ve))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),Pe?.map(Te=>a.jsx("option",{value:Te.id,children:Te.name},Te.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:Te=>d(Te.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:Te=>m(Te.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),X.map(Te=>a.jsx("option",{value:Te,children:Te},Te))]}),a.jsx("div",{className:"hidden sm:block flex-1"}),re.length>0&&a.jsxs(De,{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(en,{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 ${le==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>se("list"),title:t("queue.timeline.listView"),children:a.jsx(Qw,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 transition-colors ${le==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>se("timeline"),title:t("queue.timeline.timelineView"),children:a.jsx(Ype,{className:"w-4 h-4"})})]}),a.jsxs("button",{onClick:()=>{const Te=!(W?.queue_shortest_first??!1);q.mutate(Te)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${W?.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(wxe,{className:"w-4 h-4"}),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 ${W?.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")}):fe?.length===0?a.jsxs(Tt,{className:"p-12 text-center border-dashed",children:[a.jsx(ea,{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")})]}):le==="timeline"?a.jsx(Ptt,{queueItems:fe||[],printerStatuses:R,onItemClick:Te=>{["completed","failed","skipped","cancelled"].includes(Te.status)?g(Te):Te.status==="pending"?v(Te):Te.status==="printing"&&C({type:"stop",item:Te})},t}):a.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[ge.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:ge.map(Te=>a.jsx(pY,{item:Te,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>C({type:"stop",item:Te}),onRequeue:()=>{},onStart:()=>{},timeFormat:ne,hasPermission:r,canModify:s,printerState:Te.printer_id?B[Te.printer_id]:null,t},Te.id))})]}),ee.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(Qn,{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:ee.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:z,onChange:Te=>Y(Te.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(De,{variant:"ghost",size:"sm",onClick:()=>te(!L),title:t(L?"common.ascending":"common.descending"),className:"px-2",children:L?a.jsx(fp,{className:"w-4 h-4"}):a.jsx(ig,{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(De,{variant:"ghost",size:"sm",onClick:ie,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[P.length===ee.length&&ee.length>0?a.jsx(_s,{className:"w-4 h-4 text-bambu-green"}):a.jsx(uo,{className:"w-4 h-4"}),P.length===ee.length&&ee.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(De,{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(oi,{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(De,{variant:"ghost",size:"sm",onClick:()=>I.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:I.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(Cle,{sensors:oe,collisionDetection:hle,onDragEnd:ye,children:a.jsx(Ale,{items:ee.map(Te=>Te.id),strategy:ltt,children:a.jsx("div",{className:"space-y-2 sm:space-y-3",children:ee.map((Te,ve)=>a.jsx(pY,{item:Te,position:ve+1,onEdit:()=>v(Te),onCancel:()=>C({type:"cancel",item:Te}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>O.mutate(Te.id),timeFormat:ne,isSelected:P.includes(Te.id),onToggleSelect:()=>G(Te.id),hasPermission:r,canModify:s,t},Te.id))})})})]}),re.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:()=>J(!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(Za,{className:"w-4 h-4 sm:w-5 sm:h-5"}):a.jsx(In,{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:re.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:F,onChange:Te=>k(Te.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(De,{variant:"ghost",size:"sm",onClick:()=>H(!D),title:t(D?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:D?a.jsx(fp,{className:"w-4 h-4"}):a.jsx(ig,{className:"w-4 h-4"})})]})]}),!ae&&a.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:re.slice(0,50).map(Te=>a.jsx(wtt,{item:Te,onRemove:()=>C({type:"remove",item:Te}),onRequeue:()=>g(Te),timeFormat:ne,hasPermission:r,canModify:s,t},Te.id))})]})]}),x&&a.jsx(ic,{mode:"edit-queue-item",archiveId:x.archive_id??void 0,libraryFileId:x.library_file_id??void 0,archiveName:x.archive_name||x.library_file_name||`File #${x.archive_id||x.library_file_id}`,queueItem:x,onClose:()=>v(null)}),b&&a.jsx(ic,{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(yn,{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"?Q.mutate(_.item.id):_.type==="stop"?j.mutate(_.item.id):E.mutate(_.item.id),C(null)},onCancel:()=>C(null)}),p&&a.jsx(yn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:re.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{U.mutate(),f(!1)},onCancel:()=>f(!1)}),A&&a.jsx(jtt,{selectedCount:P.length,printers:Pe?.map(Te=>({id:Te.id,name:Te.name}))||[],onSave:Te=>{Object.keys(Te).length>0&&me.mutate({item_ids:P,...Te})},onClose:()=>T(!1),isSaving:me.isPending,canControlPrinter:r("printers:control"),t})]})}function Ett({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const C=new ResizeObserver(P=>{const N=P[0]?.contentRect.width||0;i(N)});return C.observe(_),()=>C.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach(H=>{const z=H.split("T")[0];_[z]=(_[z]||0)+1});const C=new Date,P=new Date(C);P.setMonth(P.getMonth()-e),P.setDate(P.getDate()-P.getDay());const N=[],A=[];let T=[],F=-1;const k=new Date(P);let D=0;for(;k<=C;)k.getDay()===0&&T.length>0&&(N.push(T),T=[],D++),k.getMonth()!==F&&(A.push({month:k.toLocaleDateString("en-US",{month:"short"}),weekIndex:D}),F=k.getMonth()),T.push(new Date(k)),k.setDate(k.getDate()+1);return T.length>0&&N.push(T),{weeks:N,monthLabels:A,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),d=_=>{if(_===0)return"bg-bambu-dark";const C=_/c;return C<=.25?"bg-bambu-green/30":C<=.5?"bg-bambu-green/50":C<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,x=r-p-16,v=m>0?Math.floor((x-(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:C},P)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:g,marginLeft:P===0?0:`${(C-(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((_,C)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:g,visibility:C%2===1?"visible":"hidden"},children:_},_))}),s.map((_,C)=>a.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(P=>{const N=_.find(k=>k.getDay()===P);if(!N)return a.jsx("div",{style:{width:b,height:b}},P);const A=N.toISOString().split("T")[0],T=l[A]||0,F=A===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${d(T)} ${F?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${N.toLocaleDateString()}: ${T} print${T!==1?"s":""}`},P)})},C))]}),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 fY=["weight","prints","time"];function FP({value:t,onChange:e,exclude:n}){const{t:r}=Dt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=n?fY.filter(o=>!n.includes(o)):fY;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 Bh(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 jk=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],Dtt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],gY=["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 Ftt({archives:t,currency:e="$",dateFrom:n,dateTo:r}){const{t:i}=Dt(),[s,o]=w.useState("weight"),[l,c]=w.useState("weight"),d=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const D=Jn(k.completed_at||k.created_at)||new Date,H=`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,z=F.get(H)||{date:H,filament:0,cost:0,prints:0};z.filament+=k.filament_used_grams||0,z.cost+=k.cost||0,z.prints+=k.quantity||1,F.set(H,z)}),Array.from(F.values()).sort((k,D)=>k.date.localeCompare(D.date)).map(k=>({...k,dateLabel:new Date(k.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 F=t.map(k=>new Date(k.completed_at||k.created_at).getTime());return(Math.max(...F)-Math.min(...F))/864e5},[t,n,r]),m=w.useMemo(()=>{if(u>7)return[];const F=new Map,k=u>1;return t.forEach(D=>{const H=Jn(D.completed_at||D.created_at)||new Date,z=H.getHours(),Y=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}T${String(z).padStart(2,"0")}`,L=F.get(Y)||{date:Y,filament:0,cost:0,prints:0};L.filament+=D.filament_used_grams||0,L.cost+=D.cost||0,L.prints+=D.quantity||1,F.set(Y,L)}),Array.from(F.values()).sort((D,H)=>D.date.localeCompare(H.date)).map(D=>{const[H,z]=D.date.split("T"),Y=new Date(H),L=parseInt(z,10),te=k?`${Dtt[Y.getDay()]} ${gY[L]}`:gY[L];return{...D,dateLabel:te}})},[t,u]),p=w.useMemo(()=>{if(d.length<=60)return d;const F=new Map;return d.forEach(k=>{const D=new Date(k.date),H=new Date(D);H.setDate(D.getDate()-D.getDay());const z=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}`,Y=F.get(z)||{week:z,filament:0,cost:0,prints:0};Y.filament+=k.filament,Y.cost+=k.cost,Y.prints+=k.prints,F.set(z,Y)}),Array.from(F.values()).sort((k,D)=>k.week.localeCompare(D.week)).map(k=>({date:k.week,dateLabel:`Week of ${new Date(k.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...k}))},[d]),f=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const H=(k.filament_type||"Unknown").split(", ");H.forEach(z=>{const Y=(k.filament_used_grams||0)/H.length;F.set(z,(F.get(z)||0)+Y)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:Math.round(D)})).sort((k,D)=>D.value-k.value)},[t]),x=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{(k.filament_type||"Unknown").split(", ").forEach(z=>{F.set(z,(F.get(z)||0)+1)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:D})).sort((k,D)=>D.value-k.value)},[t]),v=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const H=(k.filament_type||"Unknown").split(", "),z=(k.actual_time_seconds||k.print_time_seconds||0)/H.length;H.forEach(Y=>{F.set(Y,(F.get(Y)||0)+z)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:Math.round(D/3600*10)/10})).sort((k,D)=>D.value-k.value)},[t]),b=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(k.status!=="completed"&&k.status!=="failed")return;(k.filament_type||"Unknown").split(", ").forEach(H=>{const z=F.get(H)||{completed:0,failed:0};k.status==="completed"?z.completed++:z.failed++,F.set(H,z)})}),Array.from(F.entries()).filter(([,k])=>k.completed+k.failed>=2).map(([k,D])=>{const H=D.completed+D.failed,z=Math.round(D.completed/H*100);return{name:k,rate:z,total:H}}).sort((k,D)=>D.rate-k.rate)},[t]),g=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(!k.filament_color)return;const D=k.filament_color.split(",").map(z=>z.trim()),H=(k.filament_used_grams||0)/D.length;D.forEach(z=>{const Y=F.get(z)||{count:0,weight:0};Y.count++,Y.weight+=H,F.set(z,Y)})}),Array.from(F.entries()).map(([k,D])=>({hex:k,value:l==="prints"?D.count:Math.round(D.weight)})).sort((k,D)=>D.value-k.value)},[t,l]),_=s==="weight"?f:s==="prints"?x:v,C=u<=7&&m.length>0?m:p,P=t.reduce((F,k)=>F+(k.filament_used_grams||0),0),N=t.reduce((F,k)=>F+(k.cost||0),0),A=t.reduce((F,k)=>F+(k.quantity||1),0),T=new Set(t.map(F=>F.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:Bh(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:[A," ",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:[A>0?(P/A).toFixed(0):0,"g"]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,A>0?(N/A).toFixed(2):"0.00"," avg"]})]})]}),C.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(Gh,{width:"100%",height:250,children:a.jsxs(a7e,{data:C,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(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:F=>`${F}g`}),a.jsx(Wh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:F=>[`${Number(F??0).toFixed(0)}g`,"Filament"]}),a.jsx(Cae,{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(FP,{value:s,onChange:o})]}),_.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Gh,{width:160,height:160,children:a.jsxs(VW,{children:[a.jsx(sL,{data:_,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:_.map((F,k)=>a.jsx(oy,{fill:jk[k%jk.length]},`cell-${k}`))}),a.jsx(Wh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:F=>[s==="weight"?Bh(Number(F??0)):s==="time"?`${Number(F??0)}h`:`${F??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:_.map((F,k)=>{const D=_.reduce((z,Y)=>z+Y.value,0),H=D>0?(F.value/D*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:jk[k%jk.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:F.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?Bh(F.value):s==="time"?`${F.value}h`:F.value," · ",H,"%"]})]},F.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(F=>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:F.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 ${F.rate>=90?"bg-status-ok":F.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${F.rate}%`}})}),a.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${F.rate>=90?"text-status-ok":F.rate>=70?"text-status-warning":"text-status-error"}`,children:[F.rate,"%"]}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",F.total,")"]})]},F.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(FP,{value:l,onChange:c,exclude:["time"]})]}),g.length>0?(()=>{const F=g.reduce((k,D)=>k+D.value,0);return a.jsxs("div",{children:[a.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[a.jsx(Gh,{width:"100%",height:"100%",children:a.jsxs(VW,{children:[a.jsx(sL,{data:g,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:g.map((k,D)=>a.jsx(oy,{fill:k.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${D}`))}),a.jsx(Wh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:k=>[l==="weight"?Bh(Number(k??0)):`${k??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"?Bh(F):F}),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(k=>{const D=F>0?(k.value/F*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:k.hex}}),a.jsxs("span",{className:"text-bambu-gray truncate",children:[D,"%"]})]},k.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 Rtt({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}=Mle({id:t}),x={transform:gy.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...x,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(np,{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(AO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(qP,{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(Eg,{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 Ltt({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const F={};return t.forEach(k=>{F[k.id]=k.defaultSize||4}),F},[c,d]=w.useState(()=>{const F=localStorage.getItem(e);if(F)try{const k=JSON.parse(F);if(!k.sizes)k.sizes=l();else{const D=l();for(const H in D)H in k.sizes||(k.sizes[H]=D[H])}return k}catch{}return{order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()}}),[u,m]=w.useState(!1),[p,f]=w.useState(!1);w.useEffect(()=>{if(!r)return;const F=window.matchMedia(`(max-width: ${r}px)`),k=H=>{f(H.matches)};k(F);const D=H=>k(H);return F.addEventListener?F.addEventListener("change",D):F.addListener(D),()=>{F.removeEventListener?F.removeEventListener("change",D):F.removeListener(D)}},[r]);const x=r&&p?1:n;w.useEffect(()=>{const F=()=>m(k=>!k);return window.addEventListener("toggle-hidden-panel",F),()=>window.removeEventListener("toggle-hidden-panel",F)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const k=t.map(D=>D.id).filter(D=>!c.order.includes(D));k.length>0&&d(D=>({...D,order:[...D.order,...k]}))},[t,c.order]);const v=cle(MP(gA,{activationConstraint:{distance:8}}),MP(fA,{coordinateGetter:Ele})),b=F=>{const{active:k,over:D}=F;D&&k.id!==D.id&&d(H=>{const z=H.order.indexOf(k.id),Y=H.order.indexOf(D.id);return{...H,order:yA(H.order,z,Y)}})},g=F=>{d(k=>({...k,hidden:k.hidden.includes(F)?k.hidden.filter(D=>D!==F):[...k.hidden,F]}))},_=F=>{d(k=>{const D=k.sizes[F]||4,H=D===1?2:D===2?4:1;return{...k,sizes:{...k.sizes,[F]:H}}})},C=()=>{const F={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()};d(F),s?.()},P=c.order.map(F=>t.find(k=>k.id===F)).filter(Boolean),N=P.filter(F=>!c.hidden.includes(F.id)),A=P.filter(F=>c.hidden.includes(F.id)),T=o?.({hiddenCount:A.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:C});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(De,{variant:"secondary",size:"sm",onClick:C,children:[a.jsx(co,{className:"w-4 h-4"}),"Reset Layout"]}),A.length>0&&a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[a.jsx(yl,{className:"w-4 h-4"}),A.length," Hidden"]})]}),u&&A.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:A.map(F=>a.jsxs("button",{onClick:()=>g(F.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(yl,{className:"w-3 h-3"}),F.title]},F.id))})]}),a.jsx(Cle,{sensors:v,collisionDetection:hle,onDragEnd:b,children:a.jsx(Ale,{items:N.map(F=>F.id),strategy:m5,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${x}, minmax(0, 1fr))`},children:N.map(F=>{const k=c.sizes[F.id]||2,D=Math.min(k,x);return a.jsx(Rtt,{id:F.id,title:F.title,component:F.component,isHidden:c.hidden.includes(F.id),size:k,columnSpan:D,onToggleVisibility:()=>g(F.id),onToggleSize:()=>_(F.id)},F.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(De,{className:"mt-4",onClick:C,children:"Reset Layout"})]})]})}function Ott(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 Itt=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],ztt=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],rO=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],y3=[{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}],Mk={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function Utt({stats:t,currency:e}){const{t:n}=Dt(),r=t?.energy_data_warming_up===!0,i=r?n("stats.energyWarmingUpTooltip"):void 0,s=[{icon:Ra,color:"text-bambu-green",label:n("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:Qn,color:"text-blue-400",label:n("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Ra,color:"text-orange-400",label:n("stats.filamentUsed"),value:Bh(t?.total_filament_grams||0)},{icon:gN,color:"text-green-400",label:n("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:dc,color:"text-yellow-400",label:n("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`,warning:r,tooltip:i},{icon:gN,color:"text-yellow-500",label:n("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`,warning:r,tooltip:i}];return a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:s.map(o=>a.jsxs("div",{className:"flex items-start gap-3",title:o.tooltip,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${o.color}`,children:a.jsx(o.icon,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[o.label,o.warning&&a.jsx(Dn,{className:"w-3 h-3 text-yellow-400","aria-label":o.tooltip})]}),a.jsx("p",{className:"text-xl font-bold text-white",children:o.value})]})]},o.label))})}function Btt({stats:t,printerMap:e,size:n=1}){const{t:r}=Dt(),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(vr,{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(ja,{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 Htt({stats:t,printerMap:e,size:n=1}){const{t:r}=Dt(),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,x=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(GQ,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),x.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:x.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 qtt({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")}`,x=new Date(u);for(;x<=m;)p.push({key:f(x),label:x.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),x.setDate(x.getDate()+1);const v={};let b=0;return t.forEach(g=>{const _=Jn(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:rO.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} ${rO[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 $tt({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(qtt,{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(Ett,{printDates:t,months:o})}function Vtt({stats:t,archives:e,printerMap:n}){const{t:r}=Dt(),[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(([_,C])=>{const P=g.get(_)||{prints:0,weight:0,time:0};P.prints=C,g.set(_,P)}),e.forEach(_=>{if(!_.printer_id)return;const C=String(_.printer_id),P=g.get(C)||{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(C,P)}),Array.from(g.entries()).map(([_,C])=>({name:n.get(_)||`${r("common.printer")} ${_}`,value:i==="prints"?C.prints:i==="weight"?Math.round(C.weight):Math.round(C.time/3600*10)/10})).sort((_,C)=>C.value-_.value)},[t,e,n,i,r]),d=w.useMemo(()=>{const g=Array.from({length:24},(_,C)=>({hour:C,label:rO[C],total:0,failures:0}));return e.forEach(_=>{if(!_.started_at)return;const C=Jn(_.started_at);if(!C)return;const P=C.getHours();g[P].total++,_.status==="failed"&&g[P].failures++}),g},[e]),u=w.useMemo(()=>{const g=y3.map(_=>({name:_.key,count:0}));return e.forEach(_=>{const C=_.actual_time_seconds||_.print_time_seconds;if(!(!C||C<=0)){for(let P=0;P{const g=[0,0,0,0,0,0,0],_=new Set;e.forEach(P=>{const N=Jn(P.created_at)||new Date(P.created_at);let A=N.getDay()-1;A<0&&(A=6),o==="prints"?g[A]++:o==="weight"?g[A]+=P.filament_used_grams||0:g[A]+=(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 C=Math.max(_.size,1);return ztt.map((P,N)=>({name:P,avg:Math.round(g[N]/C*10)/10}))},[e,o]),p=g=>({unit:g==="weight"?"g":g==="time"?"h":"",color:g==="weight"?"#00ae42":g==="time"?"#3b82f6":"#f59e0b"}),f=p(i),x=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(FP,{value:i,onChange:s})]}),c.length>0?a.jsx(Gh,{width:"100%",height:Math.max(140,c.length*40),children:a.jsxs(mk,{data:c,layout:"vertical",margin:{left:10},children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),a.jsx(If,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),a.jsx(Wh,{contentStyle:Mk,formatter:g=>[i==="weight"?Bh(Number(g??0)):`${g??0}${f.unit}`,x]}),a.jsx(px,{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(Gh,{width:"100%",height:160,children:a.jsxs(mk,{data:u,children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(Wh,{contentStyle:Mk}),a.jsx(px,{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(FP,{value:o,onChange:l})]}),e.length>0?a.jsx(Gh,{width:"100%",height:160,children:a.jsxs(mk,{data:m,children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:11},unit:v.unit}),a.jsx(Wh,{contentStyle:Mk,formatter:g=>[`${g??0}${v.unit}`,b]}),a.jsx(px,{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(Gh,{width:"100%",height:160,children:a.jsxs(mk,{data:d,children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(Wh,{contentStyle:Mk}),a.jsx(px,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),a.jsx(px,{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 Gtt({archives:t,currency:e,dateFrom:n,dateTo:r}){const{t:i}=Dt();return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):a.jsx(Ftt,{archives:t,currency:e,dateFrom:n,dateTo:r})}function Wtt({size:t=1,dateFrom:e,dateTo:n,createdById:r}){const{t:i}=Dt(),s=!!(e||n),{data:o,isLoading:l}=Ye({queryKey:["failureAnalysis",e,n,r??"all"],queryFn:()=>ue.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(ft,{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(Dn,{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(EO,{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 Ktt({archives:t,currency:e}){const{t:n}=Dt(),r=w.useMemo(()=>{const i=[];if(t.length===0)return i;const s=x=>{let v=null,b=0;return t.forEach(g=>{const _=x(g);_&&_>b&&(b=_,v=g)}),{archive:v,value:b}},o=s(x=>x.actual_time_seconds);o.archive&&i.push({icon:Qn,iconColor:"text-blue-400",label:n("stats.longestPrint"),value:ys(o.value),detail:o.archive.print_name||null});const l=s(x=>x.filament_used_grams);l.archive&&i.push({icon:Ra,iconColor:"text-orange-400",label:n("stats.heaviestPrint"),value:Bh(l.value),detail:l.archive.print_name||null});const c=s(x=>x.cost);c.archive&&i.push({icon:gN,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(x=>{const v=Jn(x.created_at)||new Date(x.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((x,v)=>{x>m&&(m=x,u=v)}),m>1&&i.push({icon:ea,iconColor:"text-purple-400",label:n("stats.busiestDay"),value:`${m} ${n("common.prints")}`,detail:(()=>{const[x,v,b]=u.split("-").map(Number);return new Date(x,v-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(x=>x.status==="completed"||x.status==="failed").sort((x,v)=>new Date(v.completed_at||v.created_at).getTime()-new Date(x.completed_at||x.created_at).getTime());let f=0;for(const x of p)if(x.status==="completed")f++;else break;return f>0&&i.push({icon:dc,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 Xtt(){const{t}=Dt(),{showToast:e}=hn(),{hasPermission:n,authEnabled:r}=_r(),[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),[x,v]=w.useState(null),[b,g]=w.useState(!1),_=r&&n("stats:filter_by_user"),[C,P]=w.useState(()=>{try{const Q=localStorage.getItem("bambusy-stats-timeframe");if(Q){const E=JSON.parse(Q);if(E.preset)return E}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[N,A]=w.useState(!1);w.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(C))},[C]);const T=w.useMemo(()=>C.preset==="custom"?{dateFrom:C.dateFrom,dateTo:C.dateTo}:Ott(C.preset),[C]);w.useEffect(()=>{const Q=()=>{try{const j=localStorage.getItem("bambusy-dashboard-layout-v2");if(j){const O=JSON.parse(j);m(O.hidden?.length||0)}}catch{m(0)}};Q(),window.addEventListener("storage",Q);const E=setInterval(Q,2e3);return()=>{window.removeEventListener("storage",Q),clearInterval(E)}},[c]);const F=x!==null?x:void 0,{data:k,isLoading:D,isFetching:H,refetch:z}=Ye({queryKey:["archiveStats",T.dateFrom,T.dateTo,F??"all"],queryFn:()=>ue.getArchiveStats({dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:F})}),{data:Y}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),{data:L,isFetching:te,refetch:ae}=Ye({queryKey:["archivesSlim",T.dateFrom,T.dateTo,F??"all"],queryFn:()=>ue.getArchivesSlim(T.dateFrom,T.dateTo,F)}),{data:J}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),{data:le}=Ye({queryKey:["users"],queryFn:ue.getUsers,enabled:_}),se=w.useMemo(()=>x===null?t("stats.allUsers","All Users"):x===-1?t("stats.noUser","No User (System)"):le?.find(Q=>Q.id===x)?.username??"?",[x,le,t]),oe=async Q=>{l(!1),s(!0);try{const{blob:E,filename:j}=await ue.exportStats({format:Q,days:90,createdById:F}),O=URL.createObjectURL(E),K=document.createElement("a");K.href=O,K.download=j,K.click(),URL.revokeObjectURL(O),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},W=async()=>{f(!0);try{const Q=await ue.recalculateCosts();await Promise.all([z(),ae()]),e(t("stats.recalculatedCosts",{count:Q.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},ne=(H||te)&&!D,fe=Ao(J?.currency||"USD"),be=new Map(Y?.map(Q=>[String(Q.id),Q.name])||[]),Pe=w.useMemo(()=>L?.map(Q=>Q.created_at)||[],[L]);if(D)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 q=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(Utt,{stats:k,currency:fe}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:Q=>a.jsx(Btt,{stats:k,printerMap:be,size:Q}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:Q=>a.jsx(Htt,{stats:k,printerMap:be,size:Q}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:Q=>a.jsx(Wtt,{size:Q,dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:F}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:Q=>a.jsx($tt,{printDates:Pe,size:Q,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:a.jsx(Ktt,{archives:L||[],currency:fe}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:a.jsx(Vtt,{stats:k,archives:L||[],printerMap:be}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(Gtt,{archives:L||[],currency:fe,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")}),ne&&a.jsx(ft,{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(De,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(yl,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(De,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(Q=>Q+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(co,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(De,{variant:"secondary",onClick:W,disabled:p||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(Upe,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(De,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(xN,{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:()=>oe("csv"),children:[a.jsx(Bs,{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:()=>oe("xlsx"),children:[a.jsx(xN,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),_&&le&&le.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(De,{variant:"secondary",onClick:()=>g(!b),children:[a.jsx(Gu,{className:"w-4 h-4"}),se,a.jsx(In,{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 ${x===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 ${x===-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"}),le.map(Q=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${x===Q.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(Q.id),g(!1)},children:Q.username},Q.id))]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsxs(De,{variant:"secondary",onClick:()=>A(!N),children:[a.jsx(ea,{className:"w-4 h-4"}),t(`stats.timeframe.${C.preset}`),a.jsx(In,{className:"w-3 h-3"})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>A(!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:[Itt.map(Q=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${C.preset===Q?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{P({preset:Q,dateFrom:void 0,dateTo:void 0}),A(!1)},children:t(`stats.timeframe.${Q}`)},Q)),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 ${C.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>P(Q=>({...Q,preset:"custom"})),children:t("stats.timeframe.custom")}),C.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:C.dateFrom||"",max:C.dateTo||new Date().toISOString().split("T")[0],onChange:Q=>P(E=>({...E,dateFrom:Q.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:C.dateTo||"",min:C.dateFrom,max:new Date().toISOString().split("T")[0],onChange:Q=>P(E=>({...E,dateTo:Q.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(De,{variant:"primary",onClick:()=>A(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),a.jsx(Ltt,{widgets:q,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function Ytt({plug:t,onEdit:e}){const{t:n}=Dt(),r=rn(),{showToast:i}=hn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[d,u]=w.useState(!1),[m,p]=w.useState(!1),{data:f,isLoading:x}=Ye({queryKey:["smart-plug-status",t.id],queryFn:()=>ue.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),b=v?.find(D=>D.id===t.printer_id),g=it({mutationFn:D=>ue.controlSmartPlug(t.id,D),onMutate:async D=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const H=r.getQueryData(["smart-plug-status",t.id]),z=D==="on"?"ON":D==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],Y=>({...Y,state:z})),{previousStatus:H}},onError:(D,H,z)=>{z?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],z.previousStatus),i(n("smartPlugs.failedToTurn",{action:H,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=it({mutationFn:D=>ue.updateSmartPlug(t.id,D),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),C=it({mutationFn:()=>ue.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,A=(f?.reachable??!1)||N,T=g.isPending,k=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const D=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${D}/`:`http://${D}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(Tt,{className:"relative",children:a.jsxs(jt,{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"?A?"bg-teal-500/20":"bg-red-500/20":A?P?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(MO,{className:`w-5 h-5 ${A?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Xw,{className:`w-5 h-5 ${A?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?a.jsx(ul,{className:`w-5 h-5 ${A?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(nc,{className:`w-5 h-5 ${A?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:[x?a.jsx(ft,{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"}),A&&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:A?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?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:A?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?f?.state||"?":n("smartPlugs.offline")})]}):A?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(rp,{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($d,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),k&&a.jsxs("a",{href:k,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(da,{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(yl,{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(Zh,{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(ea,{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(De,{size:"sm",variant:P?"primary":"secondary",disabled:!A||T,onClick:()=>c(!0),className:"flex-1",children:[T?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(Jd,{className:"w-4 h-4"}),n("smartPlugs.on")]}),a.jsxs(De,{size:"sm",variant:P?"secondary":"primary",disabled:!A||T,onClick:()=>u(!0),className:"flex-1",children:[T?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(eS,{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(qd,{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(Yw,{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:D=>_.mutate({show_in_switchbar:D.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:D=>_.mutate({enabled:D.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:D=>_.mutate({auto_on:D.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:D=>_.mutate({auto_off:D.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:D=>_.mutate({auto_off_persistent:D.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(Qn,{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(rS,{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:D=>_.mutate({off_delay_minutes:parseInt(D.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:D=>_.mutate({off_temp_threshold:parseInt(D.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(De,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(Yu,{className:"w-4 h-4"}),n("smartPlugs.edit")]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(yn,{title:n("smartPlugs.deleteSmartPlug"),message:n("smartPlugs.deleteConfirm",{name:t.name}),confirmText:n("smartPlugs.delete"),variant:"danger",onConfirm:()=>{C.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(yn,{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(yn,{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 Qtt({plug:t,onClose:e}){const{t:n}=Dt(),r=rn(),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,x]=w.useState(t?.password||""),[v,b]=w.useState(t?.ha_entity_id||""),[g,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[C,P]=w.useState(t?.mqtt_power_path||""),[N,A]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[T,F]=w.useState(t?.mqtt_energy_topic||""),[k,D]=w.useState(t?.mqtt_energy_path||""),[H,z]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[Y,L]=w.useState(t?.mqtt_state_topic||""),[te,ae]=w.useState(t?.mqtt_state_path||""),[J,le]=w.useState(t?.mqtt_state_on_value||""),[se,oe]=w.useState(t?.rest_on_url||""),[W,ne]=w.useState(t?.rest_on_body||""),[fe,be]=w.useState(t?.rest_off_url||""),[Pe,q]=w.useState(t?.rest_off_body||""),[Q,E]=w.useState(t?.rest_method||"POST"),[j,O]=w.useState(t?.rest_headers||""),[K,U]=w.useState(t?.rest_status_url||""),[me,I]=w.useState(t?.rest_status_path||""),[G,X]=w.useState(t?.rest_status_on_value||""),[V,ee]=w.useState(t?.rest_power_url||""),[ie,ge]=w.useState(t?.rest_power_path||""),[pe,ce]=w.useState((t?.rest_power_multiplier??1).toString()),[B,R]=w.useState(t?.rest_energy_url||""),[re,ke]=w.useState(t?.rest_energy_path||""),[Se,ye]=w.useState((t?.rest_energy_multiplier??1).toString()),[Te,ve]=w.useState(t?.ha_power_entity||""),[Ae,Re]=w.useState(t?.ha_energy_today_entity||""),[Me,Le]=w.useState(t?.ha_energy_total_entity||""),[Oe,qe]=w.useState(""),[Qe,tt]=w.useState(""),[he,Fe]=w.useState(!1),we=w.useRef(null),[Ve,je]=w.useState(""),[de,xe]=w.useState(!1),Be=w.useRef(null),[Ze,pt]=w.useState(""),[xt,yt]=w.useState(!1),Ut=w.useRef(null),[Kt,tn]=w.useState(""),[Vt,Yt]=w.useState(!1),an=w.useRef(null),[Nn,We]=w.useState(t?.printer_id||null),[at,dt]=w.useState(null),[It,Ft]=w.useState(null),[ze,lt]=w.useState(t?.power_alert_enabled||!1),[gt,rt]=w.useState(t?.power_alert_high?.toString()||""),[Ie,ot]=w.useState(t?.power_alert_low?.toString()||""),[Ce,Ge]=w.useState(t?.schedule_enabled||!1),[et,Ke]=w.useState(t?.schedule_on_time||""),[Xe,Ue]=w.useState(t?.schedule_off_time||""),[Je,At]=w.useState(t?.show_in_switchbar||!1),[vt,$e]=w.useState(t?.show_on_printer_card??!0),[wt,Mt]=w.useState(!1),[Gt,sn]=w.useState({scanned:0,total:0}),[pn,zn]=w.useState([]),cn=w.useRef(null),{data:dn}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),{data:gn}=Ye({queryKey:["smart-plugs"],queryFn:ue.getSmartPlugs}),{data:Sn}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),gr=!!(Sn?.ha_enabled&&Sn?.ha_url&&Sn?.ha_token);w.useEffect(()=>{const St=setTimeout(()=>{tt(Oe)},300);return()=>clearTimeout(St)},[Oe]),w.useEffect(()=>{const St=Bn=>{we.current&&!we.current.contains(Bn.target)&&Fe(!1),Be.current&&!Be.current.contains(Bn.target)&&xe(!1),Ut.current&&!Ut.current.contains(Bn.target)&&yt(!1),an.current&&!an.current.contains(Bn.target)&&Yt(!1)};return document.addEventListener("mousedown",St),()=>document.removeEventListener("mousedown",St)},[]);const{data:Dr,isLoading:En,error:Ea}=Ye({queryKey:["ha-entities",Qe],queryFn:()=>ue.getHAEntities(Qe||void 0),enabled:s==="homeassistant"&&gr,retry:!1,staleTime:0}),{data:Pn}=Ye({queryKey:["ha-sensor-entities"],queryFn:ue.getHASensorEntities,enabled:s==="homeassistant"&&gr,retry:!1,staleTime:0});w.useEffect(()=>{const St=Bn=>{Bn.key==="Escape"&&e()};return window.addEventListener("keydown",St),()=>{window.removeEventListener("keydown",St),cn.current&&clearInterval(cn.current)}},[e]);const na=async()=>{Mt(!0),zn([]),sn({scanned:0,total:0}),Ft(null);try{await ue.startTasmotaScan();const St=async()=>{try{const Bn=await ue.getTasmotaScanStatus();sn({scanned:Bn.scanned,total:Bn.total});const mr=await ue.getDiscoveredTasmotaDevices();zn(mr),Bn.running||(Mt(!1),cn.current&&(clearInterval(cn.current),cn.current=null))}catch(Bn){console.error("Polling error:",Bn)}};await St(),cn.current=setInterval(St,500)}catch(St){Mt(!1);const Bn=St instanceof Error?St.message:typeof St=="string"?St:JSON.stringify(St);Ft(Bn||n("smartPlugs.failedToStartScan"))}},qn=async()=>{try{await ue.stopTasmotaScan()}catch{}Mt(!1),cn.current&&(clearInterval(cn.current),cn.current=null)},ra=St=>{u(St.ip_address),c(St.name),dt(null)},br=it({mutationFn:()=>ue.testSmartPlugConnection(d,m||null,f||null),onSuccess:St=>{dt(St),Ft(null),!l&&St.device_name&&c(St.device_name)},onError:St=>{dt(null),Ft(St.message)}}),ki=it({mutationFn:St=>ue.createSmartPlug(St),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:St=>{Ft(St.message)}}),Ni=it({mutationFn:St=>ue.updateSmartPlug(t.id,St),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:St=>{Ft(St.message)}}),Rm=dn?.filter(St=>s==="tasmota"?!gn?.some(mr=>mr.printer_id===St.id&&mr.id!==t?.id&&mr.plug_type==="tasmota"):!0),au=St=>{if(St.preventDefault(),Ft(null),!l.trim()){Ft(n("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Ft("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Ft(n("smartPlugs.entityRequired"));return}if(s==="mqtt"){const mr=g.trim(),qt=T.trim(),ad=Y.trim();if(!mr&&!qt&&!ad){Ft(n("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!se.trim()&&!fe.trim()){Ft(n("smartPlugs.restUrlRequired"));return}const Bn={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"&&Te||null,ha_energy_today_entity:s==="homeassistant"&&Ae||null,ha_energy_total_entity:s==="homeassistant"&&Me||null,mqtt_power_topic:s==="mqtt"&&g.trim()||null,mqtt_power_path:s==="mqtt"&&C.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(N)||1,mqtt_energy_topic:s==="mqtt"&&T.trim()||null,mqtt_energy_path:s==="mqtt"&&k.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(H)||1,mqtt_state_topic:s==="mqtt"&&Y.trim()||null,mqtt_state_path:s==="mqtt"&&te.trim()||null,mqtt_state_on_value:s==="mqtt"&&J.trim()||null,rest_on_url:s==="rest"&&se.trim()||null,rest_on_body:s==="rest"&&W.trim()||null,rest_off_url:s==="rest"&&fe.trim()||null,rest_off_body:s==="rest"&&Pe.trim()||null,rest_method:s==="rest"?Q:null,rest_headers:s==="rest"&&j.trim()||null,rest_status_url:s==="rest"&&K.trim()||null,rest_status_path:s==="rest"&&me.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"&&B.trim()||null,rest_energy_path:s==="rest"&&re.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(Se)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:Nn,power_alert_enabled:ze,power_alert_high:gt?parseFloat(gt):null,power_alert_low:Ie?parseFloat(Ie):null,schedule_enabled:Ce,schedule_on_time:et||null,schedule_off_time:Xe||null,show_in_switchbar:Je,show_on_printer_card:vt};i?Ni.mutate(Bn):ki.mutate(Bn)},_l=ki.isPending||Ni.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:St=>St.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:au,className:"p-6 space-y-4 overflow-y-auto",children:[It&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:It}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),dt(null),Ft(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(nc,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),dt(null),Ft(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(Xw,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),dt(null),Ft(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(MO,{className:"w-4 h-4"}),"MQTT"]}),a.jsxs("button",{type:"button",onClick:()=>{o("rest"),dt(null),Ft(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(ul,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[wt?a.jsxs(De,{type:"button",variant:"secondary",onClick:qn,className:"w-full",children:[a.jsx(Bt,{className:"w-4 h-4"}),n("smartPlugs.stopScanning")]}):a.jsxs(De,{type:"button",variant:"primary",onClick:na,className:"w-full",children:[a.jsx(Cr,{className:"w-4 h-4"}),n("smartPlugs.discoverTasmota")]}),wt&&Gt.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:[Gt.scanned," / ",Gt.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:`${Gt.scanned/Gt.total*100}%`}})})]}),pn.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.foundDevices",{count:pn.length})}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:pn.map(St=>a.jsxs("button",{type:"button",onClick:()=>ra(St),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(nc,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:St.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:St.ip_address})]})]}),St.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${St.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(Jd,{className:"w-3 h-3"}),St.state]})]},St.ip_address))})]}),!wt&&pn.length===0&&Gt.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:[!gr&&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")})})]})]}),gr&&a.jsxs(a.Fragment,{children:[En&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(ft,{className:"w-5 h-5 animate-spin mr-2"}),n("smartPlugs.loadingEntities")]}),Ea&&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:Ea.message})}),(()=>{const St=gn?.filter(qt=>qt.ha_entity_id&&qt.id!==t?.id).map(qt=>qt.ha_entity_id)||[],Bn=(Dr||[]).filter(qt=>!St.includes(qt.entity_id)),mr=Dr?.find(qt=>qt.entity_id===v);return a.jsxs("div",{ref:we,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:he?Oe:mr?`${mr.friendly_name} (${mr.entity_id})`:"",onChange:qt=>{qe(qt.target.value),he||Fe(!0)},onFocus:()=>{Fe(!0),qe("")},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&&!he&&a.jsx("button",{type:"button",onClick:()=>{b(""),qe("")},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"})}),En&&a.jsx(ft,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),he&&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:[En&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("smartPlugs.loading")]}),!En&&Bn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Qe?n("smartPlugs.noEntitiesMatching",{search:Qe}):n("smartPlugs.noEntitiesAvailable")}),!En&&Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{b(qt.entity_id),Fe(!1),qe(""),l||c(qt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${qt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:qt.entity_id}),a.jsx("span",{className:qt.state==="on"?"text-bambu-green":"",children:qt.state})]})]},qt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Qe?n("smartPlugs.searchingEntities",{count:Bn.length}):n("smartPlugs.showingEntities",{count:Bn.length})})]})})(),v&&Pn&&Pn.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 St=Pn.filter(qt=>qt.unit_of_measurement==="W"||qt.unit_of_measurement==="kW"||qt.unit_of_measurement==="mW"),Bn=Ve?St.filter(qt=>qt.entity_id.toLowerCase().includes(Ve.toLowerCase())||qt.friendly_name.toLowerCase().includes(Ve.toLowerCase())):St,mr=Pn.find(qt=>qt.entity_id===Te);return a.jsxs("div",{ref:Be,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:de?Ve:mr?`${mr.friendly_name} (${mr.state} ${mr.unit_of_measurement})`:"",onChange:qt=>{je(qt.target.value),de||xe(!0)},onFocus:()=>{xe(!0),je("")},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"}),Te&&!de&&a.jsx("button",{type:"button",onClick:()=>{ve(""),je("")},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"})})]}),de&&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:()=>{ve(""),xe(!1),je("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{ve(qt.entity_id),xe(!1),je("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Te?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Bn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const St=Pn.filter(qt=>qt.unit_of_measurement==="kWh"||qt.unit_of_measurement==="Wh"||qt.unit_of_measurement==="MWh"),Bn=Ze?St.filter(qt=>qt.entity_id.toLowerCase().includes(Ze.toLowerCase())||qt.friendly_name.toLowerCase().includes(Ze.toLowerCase())):St,mr=Pn.find(qt=>qt.entity_id===Ae);return a.jsxs("div",{ref:Ut,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?Ze:mr?`${mr.friendly_name} (${mr.state} ${mr.unit_of_measurement})`:"",onChange:qt=>{pt(qt.target.value),xt||yt(!0)},onFocus:()=>{yt(!0),pt("")},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&&!xt&&a.jsx("button",{type:"button",onClick:()=>{Re(""),pt("")},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:()=>{Re(""),yt(!1),pt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{Re(qt.entity_id),yt(!1),pt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Bn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const St=Pn.filter(qt=>qt.unit_of_measurement==="kWh"||qt.unit_of_measurement==="Wh"||qt.unit_of_measurement==="MWh"),Bn=Kt?St.filter(qt=>qt.entity_id.toLowerCase().includes(Kt.toLowerCase())||qt.friendly_name.toLowerCase().includes(Kt.toLowerCase())):St,mr=Pn.find(qt=>qt.entity_id===Me);return a.jsxs("div",{ref:an,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:Vt?Kt:mr?`${mr.friendly_name} (${mr.state} ${mr.unit_of_measurement})`:"",onChange:qt=>{tn(qt.target.value),Vt||Yt(!0)},onFocus:()=>{Yt(!0),tn("")},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"}),Me&&!Vt&&a.jsx("button",{type:"button",onClick:()=>{Le(""),tn("")},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"})})]}),Vt&&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:()=>{Le(""),Yt(!1),tn("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{Le(qt.entity_id),Yt(!1),tn("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Me?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Bn.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:[!Sn?.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")]}),Sn?.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:St=>_(St.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:C,onChange:St=>P(St.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:St=>A(St.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:St=>F(St.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:k,onChange:St=>D(St.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:H,onChange:St=>z(St.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:Y,onChange:St=>L(St.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:te,onChange:St=>ae(St.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:J,onChange:St=>le(St.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:Q,onChange:St=>E(St.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:se,onChange:St=>{oe(St.target.value),dt(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:W,onChange:St=>ne(St.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:fe,onChange:St=>{be(St.target.value),dt(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:Pe,onChange:St=>q(St.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:St=>O(St.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:K,onChange:St=>U(St.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:me,onChange:St=>I(St.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:St=>X(St.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:St=>ee(St.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:St=>ge(St.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:St=>ce(St.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:B,onChange:St=>R(St.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:re,onChange:St=>ke(St.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:St=>ye(St.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")})]}),(se.trim()||fe.trim())&&a.jsx("div",{className:"flex gap-2",children:a.jsxs(De,{type:"button",variant:"secondary",onClick:async()=>{dt(null);try{const St=se.trim()||fe.trim(),Bn=await ue.testRESTConnection(St,Q,j.trim()||null);dt({success:Bn.success}),Bn.success||Ft(Bn.error||n("smartPlugs.addSmartPlug.connectionFailed"))}catch{dt({success:!1}),Ft(n("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[a.jsx(rp,{className:"w-4 h-4"}),n("smartPlugs.testConnection")]})}),at&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${at.success?"text-green-400":"text-red-400"}`,children:[at.success?a.jsx(vr,{className:"w-4 h-4"}):a.jsx($d,{className:"w-4 h-4"}),at.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:St=>{u(St.target.value),dt(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(De,{type:"button",variant:"secondary",onClick:()=>br.mutate(),disabled:!d.trim()||br.isPending,children:[br.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(rp,{className:"w-4 h-4"}),n("smartPlugs.test")]})]})]}),s==="tasmota"&&at&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${at.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:at.success?a.jsxs(a.Fragment,{children:[a.jsx(vr,{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:[at.device_name&&n("smartPlugs.deviceLabel",{name:at.device_name}),n("smartPlugs.stateLabel",{state:at.state})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx($d,{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:St=>c(St.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:St=>p(St.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:St=>x(St.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:Nn??"",onChange:St=>We(St.target.value?Number(St.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")}),Rm?.map(St=>a.jsx("option",{value:St.id,children:St.name},St.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(Zh,{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:St=>lt(St.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:gt,onChange:St=>rt(St.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:Ie,onChange:St=>ot(St.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(Qn,{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:Ce,onChange:St=>Ge(St.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"})]})]}),Ce&&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:et,onChange:St=>Ke(St.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:Xe,onChange:St=>Ue(St.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(Yw,{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:Je,onChange:St=>At(St.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(yl,{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:St=>$e(St.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(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("smartPlugs.cancel")}),a.jsxs(De,{type:"submit",disabled:_l,className:"flex-1",children:[_l?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(ws,{className:"w-4 h-4"}),n(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function On({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 Ztt({provider:t,onEdit:e}){const{t:n}=Dt(),r=rn(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(null),{data:u}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=it({mutationFn:b=>ue.updateNotificationProvider(t.id,b),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=it({mutationFn:()=>ue.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),x=it({mutationFn:()=>ue.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(Tt,{className:"relative",children:a.jsxs(jt,{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(Zh,{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:cg(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Jn(t.last_error_at)?.getTime()||0)>(Jn(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:n("notifications.error")}),a.jsx(On,{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(SN,{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(ea,{className:"w-3 h-3"}),n("notifications.digest",{time:t.daily_digest_time})]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(De,{size:"sm",variant:"secondary",disabled:x.isPending,onClick:()=>{d(null),x.mutate()},className:"w-full",children:[x.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(tS,{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(vr,{className:"w-4 h-4"}):a.jsx(ja,{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(qd,{className:"w-4 h-4"}),n("notifications.eventSettings")]}),o?a.jsx(cc,{className:"w-4 h-4"}):a.jsx(In,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(SN,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.quietHours")})]}),a.jsx(On,{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(Qn,{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(ea,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.dailyDigest")})]}),a.jsx(On,{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(Qn,{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(De,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(Yu,{className:"w-4 h-4"}),n("notifications.edit")]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),i&&a.jsx(yn,{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 Jtt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function ent({provider:t,onClose:e}){const{t:n}=Dt(),r=rn(),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,x]=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),[C,P]=w.useState(t?.daily_digest_time||"08:00"),[N,A]=w.useState(t?.on_print_start??!1),[T,F]=w.useState(t?.on_print_complete??!0),[k,D]=w.useState(t?.on_print_failed??!0),[H,z]=w.useState(t?.on_print_stopped??!0),[Y,L]=w.useState(t?.on_print_progress??!1),[te,ae]=w.useState(t?.on_printer_offline??!1),[J,le]=w.useState(t?.on_printer_error??!1),[se,oe]=w.useState(t?.on_filament_low??!1),[W,ne]=w.useState(t?.on_maintenance_due??!1),[fe,be]=w.useState(t?.on_bed_cooled??!1),[Pe,q]=w.useState(t?.on_first_layer_complete??!1),[Q,E]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([ce,B])=>[ce,String(B)])):{}),[j,O]=w.useState(null),[K,U]=w.useState(null),{data:me}=Ye({queryKey:["printers"],queryFn:ue.getPrinters});w.useEffect(()=>{const ce=B=>{B.key==="Escape"&&e()};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[e]);const I=it({mutationFn:()=>ue.testNotificationConfig({provider_type:l,config:Q}),onSuccess:ce=>{O(ce),U(null)},onError:ce=>{O({success:!1,message:ce.message})}}),G=it({mutationFn:ce=>ue.createNotificationProvider(ce),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:ce=>{U(ce.message)}}),X=it({mutationFn:ce=>ue.updateNotificationProvider(t.id,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:ce=>{U(ce.message)}}),V=ce=>{if(ce.preventDefault(),U(null),!s.trim()){U(n("notifications.nameRequired"));return}const B=ge(l);for(const re of B)if(!Q[re.key]?.trim()){U(n("notifications.fieldRequired",{field:re.label}));return}const R={name:s.trim(),provider_type:l,config:Q,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?C:null,on_print_start:N,on_print_complete:T,on_print_failed:k,on_print_stopped:H,on_print_progress:Y,on_printer_offline:te,on_printer_error:J,on_filament_low:se,on_maintenance_due:W,on_bed_cooled:fe,on_first_layer_complete:Pe};i?X.mutate(R):G.mutate(R)},ee=G.isPending||X.isPending,ie=ce=>{switch(ce){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:B=>B.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:B=>B.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},ge=ce=>ie(ce).filter(B=>B.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:ce=>ce.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:[K&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:K}),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:ce=>o(ce.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:ce=>{c(ce.target.value),E({}),O(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:Jtt.map(ce=>a.jsx("option",{value:ce,children:n(`notifications.providerTypes.${ce}`,ce)},ce))}),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(ce=>!("showIf"in ce)||ce.showIf?.(Q)!==!1).map(ce=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[ce.label," ",ce.required&&"*"]}),ce.type==="select"&&"options"in ce&&ce.options?a.jsx("select",{value:Q[ce.key]||ce.options[0]?.value||"",onChange:B=>{E({...Q,[ce.key]:B.target.value}),O(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:ce.options.map(B=>a.jsx("option",{value:B.value,children:B.label},B.value))}):a.jsx("input",{type:ce.type,value:Q[ce.key]||"",onChange:B=>{E({...Q,[ce.key]:B.target.value}),O(null)},placeholder:ce.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"})]},ce.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(De,{type:"button",variant:"secondary",onClick:()=>{O(null),I.mutate()},disabled:I.isPending||ge(l).length>0&&!Q[ge(l)[0]?.key],className:"flex-1",children:[I.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(tS,{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(vr,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]}):a.jsxs(a.Fragment,{children:[a.jsx(ja,{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:ce=>u(ce.target.value?Number(ce.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")}),me?.map(ce=>a.jsx("option",{value:ce.id,children:ce.name},ce.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(On,{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:ce=>x(ce.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:ce=>b(ce.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(On,{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:C,onChange:ce=>P(ce.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(On,{checked:N,onChange:A})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.complete")}),a.jsx(On,{checked:T,onChange:F})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.failed")}),a.jsx(On,{checked:k,onChange:D})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.stopped")}),a.jsx(On,{checked:H,onChange:z})]}),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(On,{checked:Y,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(On,{checked:fe,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(On,{checked:Pe,onChange:q})]})]})]}),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(On,{checked:te,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(On,{checked:J,onChange:le})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.lowFilament")}),a.jsx(On,{checked:se,onChange:oe})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.maintenance")}),a.jsx(On,{checked:W,onChange:ne})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("notifications.cancel")}),a.jsxs(De,{type:"submit",disabled:ee,className:"flex-1",children:[ee?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(ws,{className:"w-4 h-4"}),n(i?"notifications.save":"notifications.add")]})]})]})]})})}function tnt({template:t,onClose:e}){const{t:n}=Dt(),r=rn(),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}=Ye({queryKey:["template-variables"],queryFn:ue.getTemplateVariables}),x=f?.find(A=>A.event_type===t.event_type),{data:v,isLoading:b}=Ye({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>ue.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});w.useEffect(()=>{const A=T=>{T.key==="Escape"&&e()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e]);const g=it({mutationFn:A=>ue.updateNotificationTemplate(t.id,A),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:A=>{u(A.message)}}),_=it({mutationFn:()=>ue.resetNotificationTemplate(t.id),onSuccess:A=>{o(A.title_template),c(A.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:A=>{u(A.message)}}),C=A=>{if(A.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=A=>{const T=i.current;if(!T)return;const F=T.selectionStart,k=T.selectionEnd,D=l,H=D.substring(0,F),z=D.substring(k),Y=H+`{${A}}`+z;c(Y),setTimeout(()=>{T.focus();const L=F+A.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:C,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:A=>o(A.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:A=>c(A.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")})]}),x&&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:x.variables.map(A=>a.jsxs("button",{type:"button",onClick:()=>P(A),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(or,{className:"w-3 h-3"}),A]},A))}),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(yl,{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(ft,{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(De,{type:"button",variant:"ghost",onClick:()=>_.mutate(),disabled:_.isPending,className:"text-orange-400 hover:text-orange-300",children:[_.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(co,{className:"w-4 h-4 mr-2"}),n("notifications.resetToDefault")]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,children:n("notifications.cancel")}),a.jsxs(De,{onClick:C,disabled:g.isPending||!N,children:[g.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(ws,{className:"w-4 h-4 mr-2"}),n("notifications.save")]})]})]})]})})}const nnt={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 rnt({onClose:t}){const{t:e}=Dt(),n=rn(),{showToast:r}=hn(),[i,s]=w.useState(7),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:x,isRefetching:v}=Ye({queryKey:["notification-logs",i,c],queryFn:()=>ue.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=Ye({queryKey:["notification-log-stats",i],queryFn:()=>ue.getNotificationLogStats(i)}),g=it({mutationFn:()=>ue.clearNotificationLogs(30),onSuccess:C=>{r(C.message,"success"),n.invalidateQueries({queryKey:["notification-logs"]}),n.invalidateQueries({queryKey:["notification-log-stats"]})},onError:C=>{r(`Failed to clear logs: ${C.message}`,"error")}}),_=C=>{const P=Jn(C);if(!P)return"";const A=new Date().getTime()-P.getTime();return A<6e4?e("notifications.justNow"):A<36e5?`${Math.floor(A/6e4)}m ago`:A<864e5?`${Math.floor(A/36e5)}h ago`:P.toLocaleDateString()+" "+sZ(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(tw,{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(vr,{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(ja,{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:C=>s(Number(C.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:C=>d(C.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(De,{size:"sm",variant:"secondary",onClick:()=>x(),disabled:v,children:[v?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),e("notifications.refresh")]}),a.jsxs(De,{size:"sm",variant:"secondary",onClick:()=>g.mutate(),disabled:g.isPending,className:"text-red-400 hover:text-red-300",children:[g.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{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(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?a.jsx("div",{className:"space-y-2",children:p.map(C=>a.jsx(ant,{log:C,isExpanded:o===C.id,onToggle:()=>l(o===C.id?null:C.id),formatDate:_,formatFullDate:P=>dg(P,m)},C.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(tw,{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 ant({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){const{t:s}=Dt();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(vr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx(ja,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${nnt[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(cc,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(In,{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 int({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Dt();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(Tt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:[a.jsx(xn,{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(Gu,{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(De,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(jt,{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(De,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(De,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(or,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function snt(){const{t}=Dt(),e=rn(),{showToast:n}=hn(),[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,x]=w.useState("all"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[C,P]=w.useState(!1),{data:N,isLoading:A}=Ye({queryKey:["spoolman-settings"],queryFn:ue.getSpoolmanSettings}),{data:T,isLoading:F,refetch:k}=Ye({queryKey:["spoolman-status"],queryFn:ue.getSpoolmanStatus,refetchInterval:3e4}),{data:D}=Ye({queryKey:["printers"],queryFn:ue.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 ne=setTimeout(()=>{H.mutate()},500);return()=>clearTimeout(ne)}},[r,s,l,d,m,v]);const H=it({mutationFn:()=>ue.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"))}}),z=it({mutationFn:ue.connectSpoolman,onSuccess:()=>{k()}}),Y=it({mutationFn:ue.disconnectSpoolman,onSuccess:()=>{k()}}),L=it({mutationFn:ue.syncAllPrintersAms,onSuccess:W=>{W.success}}),te=it({mutationFn:W=>ue.syncPrinterAms(W),onSuccess:W=>{W.success}}),ae=()=>{f==="all"?L.mutate():te.mutate(f)},J=it({mutationFn:ue.syncWeightsFromAms,onSuccess:W=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:W.synced,skipped:W.skipped}),"success"),P(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),P(!1)}}),le=L.isPending||te.isPending,se=f==="all"?L.data:te.data,oe=f==="all"?L.isSuccess:te.isSuccess;return A?a.jsxs(Tt,{id:"card-spoolman",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Jl,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(jt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(Tt,{id:"card-spoolman",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Jl,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),H.isPending&&a.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(jt,{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(Ra,{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(zr,{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(da,{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(zr,{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(vs,{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(De,{variant:"secondary",size:"sm",onClick:()=>P(!0),disabled:J.isPending,children:[J.isPending?a.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(cr,{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(vs,{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:W=>o(W.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:W=>c(W.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:W=>u(W.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:W=>p(W.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"),":"]}),F?a.jsx(ft,{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(zr,{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(De,{variant:"secondary",size:"sm",onClick:()=>Y.mutate(),disabled:Y.isPending,children:[Y.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(Jge,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(De,{size:"sm",onClick:()=>z.mutate(),disabled:z.isPending||!s,children:[z.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(im,{className:"w-4 h-4"}),t("settings.connect")]})})]}),z.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:z.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:W=>x(W.target.value==="all"?"all":Number(W.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")}),D?.map(W=>a.jsx("option",{value:W.id,children:W.name},W.id))]}),a.jsx(In,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:ae,disabled:le,children:[le?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),oe&&se&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${se.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:se.success?`Synced ${se.synced_count} spool${se.synced_count!==1?"s":""} successfully`:`Synced ${se.synced_count} spool${se.synced_count!==1?"s":""} with ${se.errors.length} error${se.errors.length!==1?"s":""}`}),se.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(Dn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[se.skipped_count," spool",se.skipped_count!==1?"s":""," skipped"]})]}),se.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?se.skipped:se.skipped.slice(0,5)).map((W,ne)=>a.jsxs("li",{className:"flex items-center gap-2",children:[W.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${W.color}`}}),a.jsx("span",{children:W.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",W.reason]})]},ne)),!g&&se.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",se.skipped_count-5," more"]})]})]}),se.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:se.errors.map((W,ne)=>a.jsx("li",{children:W},ne))})]})]})]})]})]}),C&&a.jsx(yn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:J.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>J.mutate(),onCancel:()=>P(!1)})]})}function ont(){const{t}=Dt(),{showToast:e}=hn(),[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,x]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(!1),[C,P]=w.useState(new Set),[N,A]=w.useState(!1),[T,F]=w.useState(null),[k,D]=w.useState(!1),H=w.useCallback(async()=>{try{const be=await ue.getSpoolCatalog();r(be)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{H()},[H]);const z=n.filter(be=>be.name.toLowerCase().includes(o.toLowerCase())),Y=async()=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const be=await ue.addCatalogEntry({name:f.trim(),weight:parseInt(v)});r(Pe=>[...Pe,be].sort((q,Q)=>q.name.localeCompare(Q.name))),u(!1),x(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},L=be=>{p(be.id),x(be.name),b(be.weight.toString())},te=()=>{p(null),x(""),b("")},ae=async be=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const Pe=await ue.updateCatalogEntry(be,{name:f.trim(),weight:parseInt(v)});r(q=>q.map(Q=>Q.id===be?Pe:Q).sort((Q,E)=>Q.name.localeCompare(E.name))),p(null),x(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},J=async()=>{if(T)try{await ue.deleteCatalogEntry(T.id),r(be=>be.filter(Pe=>Pe.id!==T.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{F(null)}},le=async()=>{D(!1),s(!0);try{await ue.resetSpoolCatalog(),await H(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},se=be=>{P(Pe=>{const q=new Set(Pe);return q.has(be)?q.delete(be):q.add(be),q})},oe=()=>{C.size===z.length?P(new Set):P(new Set(z.map(be=>be.id)))},W=async()=>{if(A(!1),C.size!==0)try{const be=await ue.bulkDeleteCatalogEntries([...C]);r(Pe=>Pe.filter(q=>!C.has(q.id))),P(new Set),e(t("settings.catalog.bulkDeleted",{count:be.deleted}),"success")}catch{e(t("settings.catalog.bulkDeleteFailed"),"error")}},ne=()=>{const be=n.map(({name:E,weight:j})=>({name:E,weight:j})),Pe=new Blob([JSON.stringify(be,null,2)],{type:"application/json"}),q=URL.createObjectURL(Pe),Q=document.createElement("a");Q.href=q,Q.download="spool-catalog.json",document.body.appendChild(Q),Q.click(),document.body.removeChild(Q),URL.revokeObjectURL(q),e(t("settings.catalog.exported",{count:n.length}),"success")},fe=async be=>{const Pe=be.target.files?.[0];if(Pe){try{const q=await Pe.text(),Q=JSON.parse(q);if(!Array.isArray(Q))throw new Error("Invalid format");let E=0,j=0;for(const O of Q){if(!O.name||typeof O.weight!="number"){j++;continue}if(n.some(U=>U.name.toLowerCase()===O.name.toLowerCase())){j++;continue}try{const U=await ue.addCatalogEntry({name:O.name,weight:O.weight});r(me=>[...me,U].sort((I,G)=>I.name.localeCompare(G.name))),E++}catch{j++}}e(t("settings.catalog.imported",{added:E,skipped:j}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(Tt,{id:"card-spool-catalog",children:[a.jsxs(xn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Jl,{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:ne,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(ga,{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(La,{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:fe}),a.jsxs("button",{onClick:()=>D(!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(co,{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(or,{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.catalog.selectedCount",{count:C.size})}),a.jsxs("button",{onClick:()=>A(!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(en,{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(jt,{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=>x(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:Y,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(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(zr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{u(!1),x(""),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(ft,{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:z.length>0&&C.size===z.length,onChange:oe,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:z.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")})}):z.map(be=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${C.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:C.has(be.id),onChange:()=>se(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:Pe=>x(Pe.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:Pe=>b(Pe.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(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(zr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:te,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(be.id),onChange:()=>se(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(oi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>F(be),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(en,{className:"w-4 h-4"})})]})})]})},be.id))})]})})]}),T&&a.jsx(yn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:T.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:J,onCancel:()=>F(null)}),N&&a.jsx(yn,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:C.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:W,onCancel:()=>A(!1)}),k&&a.jsx(yn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:le,onCancel:()=>D(!1)})]})}function lnt(){const{t}=Dt(),{showToast:e}=hn(),[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,x]=w.useState(null),[v,b]=w.useState(""),[g,_]=w.useState(""),[C,P]=w.useState("#FFFFFF"),[N,A]=w.useState(""),[T,F]=w.useState(!1),[k,D]=w.useState(new Set),[H,z]=w.useState(!1),[Y,L]=w.useState(!1),[te,ae]=w.useState(null),[J,le]=w.useState(null),[se,oe]=w.useState(!1),W=w.useCallback(async()=>{try{const V=await ue.getColorCatalog();r(V)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{W()},[W]);const ne=[...new Set(n.map(V=>V.manufacturer))].sort(),fe=n.filter(V=>{const ee=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 ee&&ie}),be=()=>{b(""),_(""),P("#FFFFFF"),A("")},Pe=async()=>{if(!v.trim()||!g.trim()||!C){e(t("settings.colorCatalog.fieldsRequired"),"error");return}F(!0);try{const V=await ue.addColorEntry({manufacturer:v.trim(),color_name:g.trim(),hex_color:C,material:N.trim()||null});r(ee=>[...ee,V].sort((ie,ge)=>ie.manufacturer.localeCompare(ge.manufacturer)||(ie.material||"").localeCompare(ge.material||"")||ie.color_name.localeCompare(ge.color_name))),p(!1),be(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{F(!1)}},q=V=>{x(V.id),b(V.manufacturer),_(V.color_name),P(V.hex_color),A(V.material||"")},Q=()=>{x(null),be()},E=async V=>{if(!v.trim()||!g.trim()||!C){e(t("settings.colorCatalog.fieldsRequired"),"error");return}F(!0);try{const ee=await ue.updateColorEntry(V,{manufacturer:v.trim(),color_name:g.trim(),hex_color:C,material:N.trim()||null});r(ie=>ie.map(ge=>ge.id===V?ee:ge).sort((ge,pe)=>ge.manufacturer.localeCompare(pe.manufacturer)||(ge.material||"").localeCompare(pe.material||"")||ge.color_name.localeCompare(pe.color_name))),x(null),be(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{F(!1)}},j=async()=>{if(J)try{await ue.deleteColorEntry(J.id),r(V=>V.filter(ee=>ee.id!==J.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{le(null)}},O=async()=>{oe(!1),s(!0);try{await ue.resetColorCatalog(),await W(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},K=async()=>{L(!0),ae(null);try{const V={},ee=ym();ee&&(V.Authorization=`Bearer ${ee}`);const ie=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:V});if(!ie.ok)throw new Error("Failed to start sync");const ge=ie.body?.getReader();if(!ge)throw new Error("No response body");const pe=new TextDecoder;let ce="";for(;;){const{done:B,value:R}=await ge.read();if(B)break;ce+=pe.decode(R,{stream:!0});const re=ce.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:J=>{J.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(zr,{className:"w-4 h-4"})}),L?a.jsx("div",{...A,...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(np,{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?ue.getArchivePlateThumbnail(t.archive_id,t.plate_id):ue.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?ue.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ue.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(ma,{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}`,(C?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${P.find(J=>J.index===t.plate_id)?.name||x("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?a.jsx(jo,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewArchive"),children:a.jsx(da,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(jo,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewInFileManager"),children:a.jsx(da,{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(Mr,{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?`${x("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?x("queue.filter.unassigned"):t.printer_name||`${x("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(Dd,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),ys(t.print_time_seconds)]}),t.filament_used_grams&&a.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[a.jsx(XQ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Ttt(t.filament_used_grams)]}),t.created_by_username&&a.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:x("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(xm,{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(Qn,{className:"w-3.5 h-3.5"}),t.scheduled_time?(Jn(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?x?.("queue.time.overdue")??"Overdue":ap(t.scheduled_time,c,x):x?.("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(IQ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("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:x("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(Jd,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("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(Sy,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.gcodeInjection")]})]}),Y&&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(Qn,{className:"w-3 h-3"}),ys(v.remaining_time*60)]}),a.jsxs("span",{className:"text-bambu-green font-medium",title:x("printers.estimatedCompletion"),children:["ETA ",zO(v.remaining_time,c,x)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&a.jsxs("span",{className:"flex items-center gap-1",children:[a.jsx(ma,{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:J=>J.stopPropagation(),children:[a.jsx(Att,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:x}),a.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[Y&&a.jsx(De,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("printers:control")?x("queue.actions.stopPrint"):x("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(ufe,{className:"w-4 h-4"})}),L&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(De,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("printers:control")?x("queue.actions.startPrint"):x("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(Ji,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?x("common.edit"):x("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:a.jsx(oi,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?x("common.cancel"):x("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"})})]}),te&&a.jsxs(a.Fragment,{children:[a.jsx(De,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("queue:create")?x("queue.actions.requeue"):x("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(cr,{className:"w-4 h-4"})}),a.jsx(De,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?x("common.remove"):x("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})]})]})}function Mtt(){const{t}=Dt(),e=rn(),{showToast:n}=hn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=_r(),[o,l]=w.useState(null),[c,d]=w.useState(""),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(null),[b,g]=w.useState(null),[_,C]=w.useState(null),[P,N]=w.useState([]),[A,T]=w.useState(!1),[F,k]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[D,H]=w.useState(()=>{const Te=localStorage.getItem("queue.historySortAsc");return Te!==null?Te==="true":!1}),[z,Y]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[L,te]=w.useState(()=>{const Te=localStorage.getItem("queue.pendingSortAsc");return Te!==null?Te==="true":!0}),[ae,J]=w.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[le,se]=w.useState(()=>localStorage.getItem("queue.viewMode")||"list");w.useEffect(()=>{localStorage.setItem("queue.historySortBy",F)},[F]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(D))},[D]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",z)},[z]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(L))},[L]),w.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ae))},[ae]),w.useEffect(()=>{localStorage.setItem("queue.viewMode",le)},[le]);const oe=cle(MP(gA,{activationConstraint:{distance:8}}),MP(fA,{coordinateGetter:Ele})),{data:W}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),ne=W?.time_format||"system",{data:fe,isLoading:be}=Ye({queryKey:["queue",o,c],queryFn:()=>ue.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:Pe}=Ye({queryKey:["printers"],queryFn:()=>ue.getPrinters()}),q=it({mutationFn:Te=>ue.updateSettings({queue_shortest_first:Te}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),Q=it({mutationFn:Te=>ue.cancelQueueItem(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),E=it({mutationFn:Te=>ue.removeFromQueue(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),j=it({mutationFn:Te=>ue.stopQueueItem(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),O=it({mutationFn:Te=>ue.startQueueItem(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),K=it({mutationFn:Te=>ue.reorderQueue(Te),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),U=it({mutationFn:async()=>{const Te=fe?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];for(const ve of Te)await ue.removeFromQueue(ve.id);return Te.length},onSuccess:Te=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:Te}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),me=it({mutationFn:Te=>ue.bulkUpdateQueue(Te),onSuccess:Te=>{e.invalidateQueries({queryKey:["queue"]}),N([]),T(!1),n(Te.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),I=it({mutationFn:async Te=>{for(const ve of Te)await ue.cancelQueueItem(ve);return Te.length},onSuccess:Te=>{e.invalidateQueries({queryKey:["queue"]}),N([]),n(t("queue.toast.bulkCancelled",{count:Te}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),G=Te=>{N(ve=>ve.includes(Te)?ve.filter(Ae=>Ae!==Te):[...ve,Te])},X=w.useMemo(()=>{const Te=new Set;return Pe?.forEach(ve=>{ve.location&&Te.add(ve.location)}),fe?.forEach(ve=>{ve.target_location&&Te.add(ve.target_location)}),Array.from(Te).sort()},[Pe,fe]),V=w.useCallback(Te=>u?Te.target_location?Te.target_location===u:Te.printer_id?Pe?.find(Ae=>Ae.id===Te.printer_id)?.location===u:!1:!0,[u,Pe]),ee=w.useMemo(()=>{let Te=fe?.filter(Ae=>Ae.status==="pending")||[];u&&(Te=Te.filter(V));const ve=Ae=>{if(!Ae.scheduled_time)return 0;const Re=Jn(Ae.scheduled_time)?.getTime()??0,Me=Date.now()+4320*60*60*1e3;return Re>Me?0:Re};return W?.queue_shortest_first?[...Te].sort((Ae,Re)=>{const Me=Ae.printer_id??-(Ae.target_model?.charCodeAt(0)??0),Le=Re.printer_id??-(Re.target_model?.charCodeAt(0)??0);if(Me!==Le)return Me-Le;const Oe=Ae.been_jumped?1:0,qe=Re.been_jumped?1:0;if(Oe!==qe)return qe-Oe;const Qe=Ae.print_time_seconds??1/0,tt=Re.print_time_seconds??1/0;return Qe!==tt?Qe-tt:Ae.position-Re.position}):[...Te].sort((Ae,Re)=>{let Me;if(z==="name"){const Le=Ae.archive_name||Ae.library_file_name||"",Oe=Re.archive_name||Re.library_file_name||"";Me=Le.localeCompare(Oe)}else z==="printer"?Me=(Ae.printer_name||"").localeCompare(Re.printer_name||""):z==="time"?Me=ve(Ae)-ve(Re):Me=Ae.position-Re.position;return L?Me:-Me})},[fe,z,L,V,u,W?.queue_shortest_first]),ie=()=>{const Te=ee.map(ve=>ve.id);P.length===Te.length?N([]):N(Te)},ge=w.useMemo(()=>{let Te=fe?.filter(ve=>ve.status==="printing")||[];return u&&(Te=Te.filter(V)),Te},[fe,u,V]),pe=w.useMemo(()=>{const Te=new Set;return ge.forEach(ve=>{ve.printer_id&&Te.add(ve.printer_id)}),Array.from(Te)},[ge]),ce=Pp({queries:pe.map(Te=>({queryKey:["printerStatus",Te],queryFn:()=>ue.getPrinterStatus(Te),refetchInterval:5e3}))}),B=w.useMemo(()=>{const Te={};return pe.forEach((ve,Ae)=>{const Re=ce[Ae];Re?.data?.state&&(Te[ve]=Re.data.state)}),Te},[pe,ce]),R=w.useMemo(()=>{const Te={};return pe.forEach((ve,Ae)=>{const Re=ce[Ae];Re?.data&&(Te[ve]={progress:Re.data.progress??void 0,remaining_time:Re.data.remaining_time??void 0,state:Re.data.state??void 0})}),Te},[pe,ce]),re=w.useMemo(()=>{let Te=fe?.filter(ve=>["completed","failed","skipped","cancelled"].includes(ve.status))||[];return u&&(Te=Te.filter(V)),[...Te].sort((ve,Ae)=>{let Re;if(F==="name"){const Me=ve.archive_name||ve.library_file_name||"",Le=Ae.archive_name||Ae.library_file_name||"";Re=Me.localeCompare(Le)}else F==="printer"?Re=(ve.printer_name||"").localeCompare(Ae.printer_name||""):Re=(Jn(Ae.completed_at||Ae.created_at)?.getTime()??0)-(Jn(ve.completed_at||ve.created_at)?.getTime()??0);return D?-Re:Re})},[fe,F,D,V,u]),ke=w.useMemo(()=>ee.reduce((Te,ve)=>Te+(ve.print_time_seconds||0),0),[ee]),Se=w.useMemo(()=>ee.reduce((Te,ve)=>Te+(ve.filament_used_grams||0),0),[ee]),ye=Te=>{const{active:ve,over:Ae}=Te;if(!Ae||ve.id===Ae.id)return;const Re=ee.findIndex(Le=>Le.id===ve.id),Me=ee.findIndex(Le=>Le.id===Ae.id);if(Re!==-1&&Me!==-1){const Oe=yA(ee,Re,Me).map((qe,Qe)=>({id:qe.id,position:Qe+1}));K.mutate(Oe)}};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(vN,{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(vtt,{activeCount:ge.length,pendingCount:ee.length,totalTime:ke,totalWeight:Se,historyCount:re.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:Te=>{const ve=Te.target.value;l(ve==="unassigned"?-1:ve===""?null:Number(ve))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),Pe?.map(Te=>a.jsx("option",{value:Te.id,children:Te.name},Te.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:Te=>d(Te.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:Te=>m(Te.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),X.map(Te=>a.jsx("option",{value:Te,children:Te},Te))]}),a.jsx("div",{className:"hidden sm:block flex-1"}),re.length>0&&a.jsxs(De,{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(en,{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 ${le==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>se("list"),title:t("queue.timeline.listView"),children:a.jsx(Qw,{className:"w-4 h-4"})}),a.jsx("button",{className:`p-2 transition-colors ${le==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>se("timeline"),title:t("queue.timeline.timelineView"),children:a.jsx(Ype,{className:"w-4 h-4"})})]}),a.jsxs("button",{onClick:()=>{const Te=!(W?.queue_shortest_first??!1);q.mutate(Te)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${W?.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(wxe,{className:"w-4 h-4"}),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 ${W?.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")}):fe?.length===0?a.jsxs(Tt,{className:"p-12 text-center border-dashed",children:[a.jsx(ea,{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")})]}):le==="timeline"?a.jsx(Ptt,{queueItems:fe||[],printerStatuses:R,onItemClick:Te=>{["completed","failed","skipped","cancelled"].includes(Te.status)?g(Te):Te.status==="pending"?v(Te):Te.status==="printing"&&C({type:"stop",item:Te})},t}):a.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[ge.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:ge.map(Te=>a.jsx(pY,{item:Te,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>C({type:"stop",item:Te}),onRequeue:()=>{},onStart:()=>{},timeFormat:ne,hasPermission:r,canModify:s,printerState:Te.printer_id?B[Te.printer_id]:null,t},Te.id))})]}),ee.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(Qn,{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:ee.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:z,onChange:Te=>Y(Te.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(De,{variant:"ghost",size:"sm",onClick:()=>te(!L),title:t(L?"common.ascending":"common.descending"),className:"px-2",children:L?a.jsx(fp,{className:"w-4 h-4"}):a.jsx(ig,{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(De,{variant:"ghost",size:"sm",onClick:ie,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[P.length===ee.length&&ee.length>0?a.jsx(_s,{className:"w-4 h-4 text-bambu-green"}):a.jsx(uo,{className:"w-4 h-4"}),P.length===ee.length&&ee.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(De,{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(oi,{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(De,{variant:"ghost",size:"sm",onClick:()=>I.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:I.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(Cle,{sensors:oe,collisionDetection:hle,onDragEnd:ye,children:a.jsx(Ale,{items:ee.map(Te=>Te.id),strategy:ltt,children:a.jsx("div",{className:"space-y-2 sm:space-y-3",children:ee.map((Te,ve)=>a.jsx(pY,{item:Te,position:ve+1,onEdit:()=>v(Te),onCancel:()=>C({type:"cancel",item:Te}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>O.mutate(Te.id),timeFormat:ne,isSelected:P.includes(Te.id),onToggleSelect:()=>G(Te.id),hasPermission:r,canModify:s,t},Te.id))})})})]}),re.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:()=>J(!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(Za,{className:"w-4 h-4 sm:w-5 sm:h-5"}):a.jsx(In,{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:re.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:F,onChange:Te=>k(Te.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(De,{variant:"ghost",size:"sm",onClick:()=>H(!D),title:t(D?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:D?a.jsx(fp,{className:"w-4 h-4"}):a.jsx(ig,{className:"w-4 h-4"})})]})]}),!ae&&a.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:re.slice(0,50).map(Te=>a.jsx(wtt,{item:Te,onRemove:()=>C({type:"remove",item:Te}),onRequeue:()=>g(Te),timeFormat:ne,hasPermission:r,canModify:s,t},Te.id))})]})]}),x&&a.jsx(ic,{mode:"edit-queue-item",archiveId:x.archive_id??void 0,libraryFileId:x.library_file_id??void 0,archiveName:x.archive_name||x.library_file_name||`File #${x.archive_id||x.library_file_id}`,queueItem:x,onClose:()=>v(null)}),b&&a.jsx(ic,{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(yn,{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"?Q.mutate(_.item.id):_.type==="stop"?j.mutate(_.item.id):E.mutate(_.item.id),C(null)},onCancel:()=>C(null)}),p&&a.jsx(yn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:re.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{U.mutate(),f(!1)},onCancel:()=>f(!1)}),A&&a.jsx(jtt,{selectedCount:P.length,printers:Pe?.map(Te=>({id:Te.id,name:Te.name}))||[],onSave:Te=>{Object.keys(Te).length>0&&me.mutate({item_ids:P,...Te})},onClose:()=>T(!1),isSaving:me.isPending,canControlPrinter:r("printers:control"),t})]})}function Ett({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const C=new ResizeObserver(P=>{const N=P[0]?.contentRect.width||0;i(N)});return C.observe(_),()=>C.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach(H=>{const z=H.split("T")[0];_[z]=(_[z]||0)+1});const C=new Date,P=new Date(C);P.setMonth(P.getMonth()-e),P.setDate(P.getDate()-P.getDay());const N=[],A=[];let T=[],F=-1;const k=new Date(P);let D=0;for(;k<=C;)k.getDay()===0&&T.length>0&&(N.push(T),T=[],D++),k.getMonth()!==F&&(A.push({month:k.toLocaleDateString("en-US",{month:"short"}),weekIndex:D}),F=k.getMonth()),T.push(new Date(k)),k.setDate(k.getDate()+1);return T.length>0&&N.push(T),{weeks:N,monthLabels:A,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),d=_=>{if(_===0)return"bg-bambu-dark";const C=_/c;return C<=.25?"bg-bambu-green/30":C<=.5?"bg-bambu-green/50":C<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,x=r-p-16,v=m>0?Math.floor((x-(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:C},P)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:g,marginLeft:P===0?0:`${(C-(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((_,C)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:g,visibility:C%2===1?"visible":"hidden"},children:_},_))}),s.map((_,C)=>a.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(P=>{const N=_.find(k=>k.getDay()===P);if(!N)return a.jsx("div",{style:{width:b,height:b}},P);const A=N.toISOString().split("T")[0],T=l[A]||0,F=A===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${d(T)} ${F?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${N.toLocaleDateString()}: ${T} print${T!==1?"s":""}`},P)})},C))]}),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 fY=["weight","prints","time"];function FP({value:t,onChange:e,exclude:n}){const{t:r}=Dt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=n?fY.filter(o=>!n.includes(o)):fY;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 Bh(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 jk=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],Dtt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],gY=["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 Ftt({archives:t,currency:e="$",dateFrom:n,dateTo:r}){const{t:i}=Dt(),[s,o]=w.useState("weight"),[l,c]=w.useState("weight"),d=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const D=Jn(k.completed_at||k.created_at)||new Date,H=`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,z=F.get(H)||{date:H,filament:0,cost:0,prints:0};z.filament+=k.filament_used_grams||0,z.cost+=k.cost||0,z.prints+=k.quantity||1,F.set(H,z)}),Array.from(F.values()).sort((k,D)=>k.date.localeCompare(D.date)).map(k=>({...k,dateLabel:new Date(k.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 F=t.map(k=>new Date(k.completed_at||k.created_at).getTime());return(Math.max(...F)-Math.min(...F))/864e5},[t,n,r]),m=w.useMemo(()=>{if(u>7)return[];const F=new Map,k=u>1;return t.forEach(D=>{const H=Jn(D.completed_at||D.created_at)||new Date,z=H.getHours(),Y=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}T${String(z).padStart(2,"0")}`,L=F.get(Y)||{date:Y,filament:0,cost:0,prints:0};L.filament+=D.filament_used_grams||0,L.cost+=D.cost||0,L.prints+=D.quantity||1,F.set(Y,L)}),Array.from(F.values()).sort((D,H)=>D.date.localeCompare(H.date)).map(D=>{const[H,z]=D.date.split("T"),Y=new Date(H),L=parseInt(z,10),te=k?`${Dtt[Y.getDay()]} ${gY[L]}`:gY[L];return{...D,dateLabel:te}})},[t,u]),p=w.useMemo(()=>{if(d.length<=60)return d;const F=new Map;return d.forEach(k=>{const D=new Date(k.date),H=new Date(D);H.setDate(D.getDate()-D.getDay());const z=`${H.getFullYear()}-${String(H.getMonth()+1).padStart(2,"0")}-${String(H.getDate()).padStart(2,"0")}`,Y=F.get(z)||{week:z,filament:0,cost:0,prints:0};Y.filament+=k.filament,Y.cost+=k.cost,Y.prints+=k.prints,F.set(z,Y)}),Array.from(F.values()).sort((k,D)=>k.week.localeCompare(D.week)).map(k=>({date:k.week,dateLabel:`Week of ${new Date(k.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...k}))},[d]),f=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const H=(k.filament_type||"Unknown").split(", ");H.forEach(z=>{const Y=(k.filament_used_grams||0)/H.length;F.set(z,(F.get(z)||0)+Y)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:Math.round(D)})).sort((k,D)=>D.value-k.value)},[t]),x=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{(k.filament_type||"Unknown").split(", ").forEach(z=>{F.set(z,(F.get(z)||0)+1)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:D})).sort((k,D)=>D.value-k.value)},[t]),v=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{const H=(k.filament_type||"Unknown").split(", "),z=(k.actual_time_seconds||k.print_time_seconds||0)/H.length;H.forEach(Y=>{F.set(Y,(F.get(Y)||0)+z)})}),Array.from(F.entries()).map(([k,D])=>({name:k,value:Math.round(D/3600*10)/10})).sort((k,D)=>D.value-k.value)},[t]),b=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(k.status!=="completed"&&k.status!=="failed")return;(k.filament_type||"Unknown").split(", ").forEach(H=>{const z=F.get(H)||{completed:0,failed:0};k.status==="completed"?z.completed++:z.failed++,F.set(H,z)})}),Array.from(F.entries()).filter(([,k])=>k.completed+k.failed>=2).map(([k,D])=>{const H=D.completed+D.failed,z=Math.round(D.completed/H*100);return{name:k,rate:z,total:H}}).sort((k,D)=>D.rate-k.rate)},[t]),g=w.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(!k.filament_color)return;const D=k.filament_color.split(",").map(z=>z.trim()),H=(k.filament_used_grams||0)/D.length;D.forEach(z=>{const Y=F.get(z)||{count:0,weight:0};Y.count++,Y.weight+=H,F.set(z,Y)})}),Array.from(F.entries()).map(([k,D])=>({hex:k,value:l==="prints"?D.count:Math.round(D.weight)})).sort((k,D)=>D.value-k.value)},[t,l]),_=s==="weight"?f:s==="prints"?x:v,C=u<=7&&m.length>0?m:p,P=t.reduce((F,k)=>F+(k.filament_used_grams||0),0),N=t.reduce((F,k)=>F+(k.cost||0),0),A=t.reduce((F,k)=>F+(k.quantity||1),0),T=new Set(t.map(F=>F.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:Bh(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:[A," ",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:[A>0?(P/A).toFixed(0):0,"g"]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,A>0?(N/A).toFixed(2):"0.00"," avg"]})]})]}),C.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(Gh,{width:"100%",height:250,children:a.jsxs(a7e,{data:C,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(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:F=>`${F}g`}),a.jsx(Wh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:F=>[`${Number(F??0).toFixed(0)}g`,"Filament"]}),a.jsx(Cae,{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(FP,{value:s,onChange:o})]}),_.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(Gh,{width:160,height:160,children:a.jsxs(VW,{children:[a.jsx(sL,{data:_,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:_.map((F,k)=>a.jsx(oy,{fill:jk[k%jk.length]},`cell-${k}`))}),a.jsx(Wh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:F=>[s==="weight"?Bh(Number(F??0)):s==="time"?`${Number(F??0)}h`:`${F??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:_.map((F,k)=>{const D=_.reduce((z,Y)=>z+Y.value,0),H=D>0?(F.value/D*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:jk[k%jk.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:F.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?Bh(F.value):s==="time"?`${F.value}h`:F.value," · ",H,"%"]})]},F.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(F=>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:F.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 ${F.rate>=90?"bg-status-ok":F.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${F.rate}%`}})}),a.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${F.rate>=90?"text-status-ok":F.rate>=70?"text-status-warning":"text-status-error"}`,children:[F.rate,"%"]}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",F.total,")"]})]},F.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(FP,{value:l,onChange:c,exclude:["time"]})]}),g.length>0?(()=>{const F=g.reduce((k,D)=>k+D.value,0);return a.jsxs("div",{children:[a.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[a.jsx(Gh,{width:"100%",height:"100%",children:a.jsxs(VW,{children:[a.jsx(sL,{data:g,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:g.map((k,D)=>a.jsx(oy,{fill:k.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${D}`))}),a.jsx(Wh,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:k=>[l==="weight"?Bh(Number(k??0)):`${k??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"?Bh(F):F}),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(k=>{const D=F>0?(k.value/F*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:k.hex}}),a.jsxs("span",{className:"text-bambu-gray truncate",children:[D,"%"]})]},k.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 Rtt({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}=Mle({id:t}),x={transform:gy.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...x,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(np,{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(AO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(qP,{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(Eg,{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 Ltt({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const F={};return t.forEach(k=>{F[k.id]=k.defaultSize||4}),F},[c,d]=w.useState(()=>{const F=localStorage.getItem(e);if(F)try{const k=JSON.parse(F);if(!k.sizes)k.sizes=l();else{const D=l();for(const H in D)H in k.sizes||(k.sizes[H]=D[H])}return k}catch{}return{order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()}}),[u,m]=w.useState(!1),[p,f]=w.useState(!1);w.useEffect(()=>{if(!r)return;const F=window.matchMedia(`(max-width: ${r}px)`),k=H=>{f(H.matches)};k(F);const D=H=>k(H);return F.addEventListener?F.addEventListener("change",D):F.addListener(D),()=>{F.removeEventListener?F.removeEventListener("change",D):F.removeListener(D)}},[r]);const x=r&&p?1:n;w.useEffect(()=>{const F=()=>m(k=>!k);return window.addEventListener("toggle-hidden-panel",F),()=>window.removeEventListener("toggle-hidden-panel",F)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const k=t.map(D=>D.id).filter(D=>!c.order.includes(D));k.length>0&&d(D=>({...D,order:[...D.order,...k]}))},[t,c.order]);const v=cle(MP(gA,{activationConstraint:{distance:8}}),MP(fA,{coordinateGetter:Ele})),b=F=>{const{active:k,over:D}=F;D&&k.id!==D.id&&d(H=>{const z=H.order.indexOf(k.id),Y=H.order.indexOf(D.id);return{...H,order:yA(H.order,z,Y)}})},g=F=>{d(k=>({...k,hidden:k.hidden.includes(F)?k.hidden.filter(D=>D!==F):[...k.hidden,F]}))},_=F=>{d(k=>{const D=k.sizes[F]||4,H=D===1?2:D===2?4:1;return{...k,sizes:{...k.sizes,[F]:H}}})},C=()=>{const F={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()};d(F),s?.()},P=c.order.map(F=>t.find(k=>k.id===F)).filter(Boolean),N=P.filter(F=>!c.hidden.includes(F.id)),A=P.filter(F=>c.hidden.includes(F.id)),T=o?.({hiddenCount:A.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:C});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(De,{variant:"secondary",size:"sm",onClick:C,children:[a.jsx(co,{className:"w-4 h-4"}),"Reset Layout"]}),A.length>0&&a.jsxs(De,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[a.jsx(yl,{className:"w-4 h-4"}),A.length," Hidden"]})]}),u&&A.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:A.map(F=>a.jsxs("button",{onClick:()=>g(F.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(yl,{className:"w-3 h-3"}),F.title]},F.id))})]}),a.jsx(Cle,{sensors:v,collisionDetection:hle,onDragEnd:b,children:a.jsx(Ale,{items:N.map(F=>F.id),strategy:m5,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${x}, minmax(0, 1fr))`},children:N.map(F=>{const k=c.sizes[F.id]||2,D=Math.min(k,x);return a.jsx(Rtt,{id:F.id,title:F.title,component:F.component,isHidden:c.hidden.includes(F.id),size:k,columnSpan:D,onToggleVisibility:()=>g(F.id),onToggleSize:()=>_(F.id)},F.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(De,{className:"mt-4",onClick:C,children:"Reset Layout"})]})]})}function Ott(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 Itt=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],ztt=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],rO=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],y3=[{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}],Mk={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function Utt({stats:t,currency:e}){const{t:n}=Dt(),r=t?.energy_data_warming_up===!0,i=r?n("stats.energyWarmingUpTooltip"):void 0,s=[{icon:Ra,color:"text-bambu-green",label:n("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:Qn,color:"text-blue-400",label:n("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Ra,color:"text-orange-400",label:n("stats.filamentUsed"),value:Bh(t?.total_filament_grams||0)},{icon:gN,color:"text-green-400",label:n("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:dc,color:"text-yellow-400",label:n("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`,warning:r,tooltip:i},{icon:gN,color:"text-yellow-500",label:n("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`,warning:r,tooltip:i}];return a.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:s.map(o=>a.jsxs("div",{className:"flex items-start gap-3",title:o.tooltip,children:[a.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${o.color}`,children:a.jsx(o.icon,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[o.label,o.warning&&a.jsx(Dn,{className:"w-3 h-3 text-yellow-400","aria-label":o.tooltip})]}),a.jsx("p",{className:"text-xl font-bold text-white",children:o.value})]})]},o.label))})}function Btt({stats:t,printerMap:e,size:n=1}){const{t:r}=Dt(),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(vr,{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(ja,{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 Htt({stats:t,printerMap:e,size:n=1}){const{t:r}=Dt(),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,x=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(GQ,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),x.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:x.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 qtt({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")}`,x=new Date(u);for(;x<=m;)p.push({key:f(x),label:x.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),x.setDate(x.getDate()+1);const v={};let b=0;return t.forEach(g=>{const _=Jn(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:rO.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} ${rO[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 $tt({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(qtt,{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(Ett,{printDates:t,months:o})}function Vtt({stats:t,archives:e,printerMap:n}){const{t:r}=Dt(),[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(([_,C])=>{const P=g.get(_)||{prints:0,weight:0,time:0};P.prints=C,g.set(_,P)}),e.forEach(_=>{if(!_.printer_id)return;const C=String(_.printer_id),P=g.get(C)||{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(C,P)}),Array.from(g.entries()).map(([_,C])=>({name:n.get(_)||`${r("common.printer")} ${_}`,value:i==="prints"?C.prints:i==="weight"?Math.round(C.weight):Math.round(C.time/3600*10)/10})).sort((_,C)=>C.value-_.value)},[t,e,n,i,r]),d=w.useMemo(()=>{const g=Array.from({length:24},(_,C)=>({hour:C,label:rO[C],total:0,failures:0}));return e.forEach(_=>{if(!_.started_at)return;const C=Jn(_.started_at);if(!C)return;const P=C.getHours();g[P].total++,_.status==="failed"&&g[P].failures++}),g},[e]),u=w.useMemo(()=>{const g=y3.map(_=>({name:_.key,count:0}));return e.forEach(_=>{const C=_.actual_time_seconds||_.print_time_seconds;if(!(!C||C<=0)){for(let P=0;P{const g=[0,0,0,0,0,0,0],_=new Set;e.forEach(P=>{const N=Jn(P.created_at)||new Date(P.created_at);let A=N.getDay()-1;A<0&&(A=6),o==="prints"?g[A]++:o==="weight"?g[A]+=P.filament_used_grams||0:g[A]+=(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 C=Math.max(_.size,1);return ztt.map((P,N)=>({name:P,avg:Math.round(g[N]/C*10)/10}))},[e,o]),p=g=>({unit:g==="weight"?"g":g==="time"?"h":"",color:g==="weight"?"#00ae42":g==="time"?"#3b82f6":"#f59e0b"}),f=p(i),x=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(FP,{value:i,onChange:s})]}),c.length>0?a.jsx(Gh,{width:"100%",height:Math.max(140,c.length*40),children:a.jsxs(mk,{data:c,layout:"vertical",margin:{left:10},children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),a.jsx(If,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),a.jsx(Wh,{contentStyle:Mk,formatter:g=>[i==="weight"?Bh(Number(g??0)):`${g??0}${f.unit}`,x]}),a.jsx(px,{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(Gh,{width:"100%",height:160,children:a.jsxs(mk,{data:u,children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(Wh,{contentStyle:Mk}),a.jsx(px,{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(FP,{value:o,onChange:l})]}),e.length>0?a.jsx(Gh,{width:"100%",height:160,children:a.jsxs(mk,{data:m,children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:11},unit:v.unit}),a.jsx(Wh,{contentStyle:Mk,formatter:g=>[`${g??0}${v.unit}`,b]}),a.jsx(px,{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(Gh,{width:"100%",height:160,children:a.jsxs(mk,{data:d,children:[a.jsx(Lf,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(Of,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),a.jsx(If,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),a.jsx(Wh,{contentStyle:Mk}),a.jsx(px,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),a.jsx(px,{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 Gtt({archives:t,currency:e,dateFrom:n,dateTo:r}){const{t:i}=Dt();return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):a.jsx(Ftt,{archives:t,currency:e,dateFrom:n,dateTo:r})}function Wtt({size:t=1,dateFrom:e,dateTo:n,createdById:r}){const{t:i}=Dt(),s=!!(e||n),{data:o,isLoading:l}=Ye({queryKey:["failureAnalysis",e,n,r??"all"],queryFn:()=>ue.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(ft,{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(Dn,{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(EO,{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 Ktt({archives:t,currency:e}){const{t:n}=Dt(),r=w.useMemo(()=>{const i=[];if(t.length===0)return i;const s=x=>{let v=null,b=0;return t.forEach(g=>{const _=x(g);_&&_>b&&(b=_,v=g)}),{archive:v,value:b}},o=s(x=>x.actual_time_seconds);o.archive&&i.push({icon:Qn,iconColor:"text-blue-400",label:n("stats.longestPrint"),value:ys(o.value),detail:o.archive.print_name||null});const l=s(x=>x.filament_used_grams);l.archive&&i.push({icon:Ra,iconColor:"text-orange-400",label:n("stats.heaviestPrint"),value:Bh(l.value),detail:l.archive.print_name||null});const c=s(x=>x.cost);c.archive&&i.push({icon:gN,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(x=>{const v=Jn(x.created_at)||new Date(x.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((x,v)=>{x>m&&(m=x,u=v)}),m>1&&i.push({icon:ea,iconColor:"text-purple-400",label:n("stats.busiestDay"),value:`${m} ${n("common.prints")}`,detail:(()=>{const[x,v,b]=u.split("-").map(Number);return new Date(x,v-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(x=>x.status==="completed"||x.status==="failed").sort((x,v)=>new Date(v.completed_at||v.created_at).getTime()-new Date(x.completed_at||x.created_at).getTime());let f=0;for(const x of p)if(x.status==="completed")f++;else break;return f>0&&i.push({icon:dc,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 Xtt(){const{t}=Dt(),{showToast:e}=hn(),{hasPermission:n,authEnabled:r}=_r(),[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),[x,v]=w.useState(null),[b,g]=w.useState(!1),_=r&&n("stats:filter_by_user"),[C,P]=w.useState(()=>{try{const Q=localStorage.getItem("bambusy-stats-timeframe");if(Q){const E=JSON.parse(Q);if(E.preset)return E}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[N,A]=w.useState(!1);w.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(C))},[C]);const T=w.useMemo(()=>C.preset==="custom"?{dateFrom:C.dateFrom,dateTo:C.dateTo}:Ott(C.preset),[C]);w.useEffect(()=>{const Q=()=>{try{const j=localStorage.getItem("bambusy-dashboard-layout-v2");if(j){const O=JSON.parse(j);m(O.hidden?.length||0)}}catch{m(0)}};Q(),window.addEventListener("storage",Q);const E=setInterval(Q,2e3);return()=>{window.removeEventListener("storage",Q),clearInterval(E)}},[c]);const F=x!==null?x:void 0,{data:k,isLoading:D,isFetching:H,refetch:z}=Ye({queryKey:["archiveStats",T.dateFrom,T.dateTo,F??"all"],queryFn:()=>ue.getArchiveStats({dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:F})}),{data:Y}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),{data:L,isFetching:te,refetch:ae}=Ye({queryKey:["archivesSlim",T.dateFrom,T.dateTo,F??"all"],queryFn:()=>ue.getArchivesSlim(T.dateFrom,T.dateTo,F)}),{data:J}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),{data:le}=Ye({queryKey:["users"],queryFn:ue.getUsers,enabled:_}),se=w.useMemo(()=>x===null?t("stats.allUsers","All Users"):x===-1?t("stats.noUser","No User (System)"):le?.find(Q=>Q.id===x)?.username??"?",[x,le,t]),oe=async Q=>{l(!1),s(!0);try{const{blob:E,filename:j}=await ue.exportStats({format:Q,days:90,createdById:F}),O=URL.createObjectURL(E),K=document.createElement("a");K.href=O,K.download=j,K.click(),URL.revokeObjectURL(O),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},W=async()=>{f(!0);try{const Q=await ue.recalculateCosts();await Promise.all([z(),ae()]),e(t("stats.recalculatedCosts",{count:Q.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},ne=(H||te)&&!D,fe=Ao(J?.currency||"USD"),be=new Map(Y?.map(Q=>[String(Q.id),Q.name])||[]),Pe=w.useMemo(()=>L?.map(Q=>Q.created_at)||[],[L]);if(D)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 q=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(Utt,{stats:k,currency:fe}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:Q=>a.jsx(Btt,{stats:k,printerMap:be,size:Q}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:Q=>a.jsx(Htt,{stats:k,printerMap:be,size:Q}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:Q=>a.jsx(Wtt,{size:Q,dateFrom:T.dateFrom,dateTo:T.dateTo,createdById:F}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:Q=>a.jsx($tt,{printDates:Pe,size:Q,dateFrom:T.dateFrom,dateTo:T.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:a.jsx(Ktt,{archives:L||[],currency:fe}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:a.jsx(Vtt,{stats:k,archives:L||[],printerMap:be}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(Gtt,{archives:L||[],currency:fe,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")}),ne&&a.jsx(ft,{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(De,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(yl,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(De,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(Q=>Q+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(co,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(De,{variant:"secondary",onClick:W,disabled:p||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(Upe,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(De,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(xN,{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:()=>oe("csv"),children:[a.jsx(Bs,{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:()=>oe("xlsx"),children:[a.jsx(xN,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),_&&le&&le.length>0&&a.jsxs("div",{className:"relative",children:[a.jsxs(De,{variant:"secondary",onClick:()=>g(!b),children:[a.jsx(Gu,{className:"w-4 h-4"}),se,a.jsx(In,{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 ${x===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 ${x===-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"}),le.map(Q=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${x===Q.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{v(Q.id),g(!1)},children:Q.username},Q.id))]})]})]}),a.jsxs("div",{className:"relative",children:[a.jsxs(De,{variant:"secondary",onClick:()=>A(!N),children:[a.jsx(ea,{className:"w-4 h-4"}),t(`stats.timeframe.${C.preset}`),a.jsx(In,{className:"w-3 h-3"})]}),N&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>A(!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:[Itt.map(Q=>a.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${C.preset===Q?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{P({preset:Q,dateFrom:void 0,dateTo:void 0}),A(!1)},children:t(`stats.timeframe.${Q}`)},Q)),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 ${C.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>P(Q=>({...Q,preset:"custom"})),children:t("stats.timeframe.custom")}),C.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:C.dateFrom||"",max:C.dateTo||new Date().toISOString().split("T")[0],onChange:Q=>P(E=>({...E,dateFrom:Q.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:C.dateTo||"",min:C.dateFrom,max:new Date().toISOString().split("T")[0],onChange:Q=>P(E=>({...E,dateTo:Q.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(De,{variant:"primary",onClick:()=>A(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),a.jsx(Ltt,{widgets:q,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function Ytt({plug:t,onEdit:e}){const{t:n}=Dt(),r=rn(),{showToast:i}=hn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[d,u]=w.useState(!1),[m,p]=w.useState(!1),{data:f,isLoading:x}=Ye({queryKey:["smart-plug-status",t.id],queryFn:()=>ue.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),b=v?.find(D=>D.id===t.printer_id),g=it({mutationFn:D=>ue.controlSmartPlug(t.id,D),onMutate:async D=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const H=r.getQueryData(["smart-plug-status",t.id]),z=D==="on"?"ON":D==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],Y=>({...Y,state:z})),{previousStatus:H}},onError:(D,H,z)=>{z?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],z.previousStatus),i(n("smartPlugs.failedToTurn",{action:H,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=it({mutationFn:D=>ue.updateSmartPlug(t.id,D),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),C=it({mutationFn:()=>ue.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,A=(f?.reachable??!1)||N,T=g.isPending,k=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const D=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${D}/`:`http://${D}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(Tt,{className:"relative",children:a.jsxs(jt,{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"?A?"bg-teal-500/20":"bg-red-500/20":A?P?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(MO,{className:`w-5 h-5 ${A?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(Xw,{className:`w-5 h-5 ${A?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?a.jsx(ul,{className:`w-5 h-5 ${A?P?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(nc,{className:`w-5 h-5 ${A?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:[x?a.jsx(ft,{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"}),A&&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:A?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?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:A?P?"text-status-ok":"text-bambu-gray":"text-status-error",children:A?f?.state||"?":n("smartPlugs.offline")})]}):A?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(rp,{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($d,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),k&&a.jsxs("a",{href:k,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(da,{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(yl,{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(Zh,{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(ea,{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(De,{size:"sm",variant:P?"primary":"secondary",disabled:!A||T,onClick:()=>c(!0),className:"flex-1",children:[T?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(Jd,{className:"w-4 h-4"}),n("smartPlugs.on")]}),a.jsxs(De,{size:"sm",variant:P?"secondary":"primary",disabled:!A||T,onClick:()=>u(!0),className:"flex-1",children:[T?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(eS,{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(qd,{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(Yw,{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:D=>_.mutate({show_in_switchbar:D.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:D=>_.mutate({enabled:D.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:D=>_.mutate({auto_on:D.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:D=>_.mutate({auto_off:D.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:D=>_.mutate({auto_off_persistent:D.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(Qn,{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(rS,{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:D=>_.mutate({off_delay_minutes:parseInt(D.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:D=>_.mutate({off_temp_threshold:parseInt(D.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(De,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(Yu,{className:"w-4 h-4"}),n("smartPlugs.edit")]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(yn,{title:n("smartPlugs.deleteSmartPlug"),message:n("smartPlugs.deleteConfirm",{name:t.name}),confirmText:n("smartPlugs.delete"),variant:"danger",onConfirm:()=>{C.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(yn,{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(yn,{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 Qtt({plug:t,onClose:e}){const{t:n}=Dt(),r=rn(),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,x]=w.useState(t?.password||""),[v,b]=w.useState(t?.ha_entity_id||""),[g,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[C,P]=w.useState(t?.mqtt_power_path||""),[N,A]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[T,F]=w.useState(t?.mqtt_energy_topic||""),[k,D]=w.useState(t?.mqtt_energy_path||""),[H,z]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[Y,L]=w.useState(t?.mqtt_state_topic||""),[te,ae]=w.useState(t?.mqtt_state_path||""),[J,le]=w.useState(t?.mqtt_state_on_value||""),[se,oe]=w.useState(t?.rest_on_url||""),[W,ne]=w.useState(t?.rest_on_body||""),[fe,be]=w.useState(t?.rest_off_url||""),[Pe,q]=w.useState(t?.rest_off_body||""),[Q,E]=w.useState(t?.rest_method||"POST"),[j,O]=w.useState(t?.rest_headers||""),[K,U]=w.useState(t?.rest_status_url||""),[me,I]=w.useState(t?.rest_status_path||""),[G,X]=w.useState(t?.rest_status_on_value||""),[V,ee]=w.useState(t?.rest_power_url||""),[ie,ge]=w.useState(t?.rest_power_path||""),[pe,ce]=w.useState((t?.rest_power_multiplier??1).toString()),[B,R]=w.useState(t?.rest_energy_url||""),[re,ke]=w.useState(t?.rest_energy_path||""),[Se,ye]=w.useState((t?.rest_energy_multiplier??1).toString()),[Te,ve]=w.useState(t?.ha_power_entity||""),[Ae,Re]=w.useState(t?.ha_energy_today_entity||""),[Me,Le]=w.useState(t?.ha_energy_total_entity||""),[Oe,qe]=w.useState(""),[Qe,tt]=w.useState(""),[he,Fe]=w.useState(!1),we=w.useRef(null),[Ve,je]=w.useState(""),[de,xe]=w.useState(!1),Be=w.useRef(null),[Ze,pt]=w.useState(""),[xt,yt]=w.useState(!1),Ut=w.useRef(null),[Kt,tn]=w.useState(""),[Vt,Yt]=w.useState(!1),an=w.useRef(null),[Nn,We]=w.useState(t?.printer_id||null),[at,dt]=w.useState(null),[It,Ft]=w.useState(null),[ze,lt]=w.useState(t?.power_alert_enabled||!1),[gt,rt]=w.useState(t?.power_alert_high?.toString()||""),[Ie,ot]=w.useState(t?.power_alert_low?.toString()||""),[Ce,Ge]=w.useState(t?.schedule_enabled||!1),[et,Ke]=w.useState(t?.schedule_on_time||""),[Xe,Ue]=w.useState(t?.schedule_off_time||""),[Je,At]=w.useState(t?.show_in_switchbar||!1),[vt,$e]=w.useState(t?.show_on_printer_card??!0),[wt,Mt]=w.useState(!1),[Gt,sn]=w.useState({scanned:0,total:0}),[pn,zn]=w.useState([]),cn=w.useRef(null),{data:dn}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),{data:gn}=Ye({queryKey:["smart-plugs"],queryFn:ue.getSmartPlugs}),{data:Sn}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),gr=!!(Sn?.ha_enabled&&Sn?.ha_url&&Sn?.ha_token);w.useEffect(()=>{const St=setTimeout(()=>{tt(Oe)},300);return()=>clearTimeout(St)},[Oe]),w.useEffect(()=>{const St=Bn=>{we.current&&!we.current.contains(Bn.target)&&Fe(!1),Be.current&&!Be.current.contains(Bn.target)&&xe(!1),Ut.current&&!Ut.current.contains(Bn.target)&&yt(!1),an.current&&!an.current.contains(Bn.target)&&Yt(!1)};return document.addEventListener("mousedown",St),()=>document.removeEventListener("mousedown",St)},[]);const{data:Dr,isLoading:En,error:Ea}=Ye({queryKey:["ha-entities",Qe],queryFn:()=>ue.getHAEntities(Qe||void 0),enabled:s==="homeassistant"&&gr,retry:!1,staleTime:0}),{data:Pn}=Ye({queryKey:["ha-sensor-entities"],queryFn:ue.getHASensorEntities,enabled:s==="homeassistant"&&gr,retry:!1,staleTime:0});w.useEffect(()=>{const St=Bn=>{Bn.key==="Escape"&&e()};return window.addEventListener("keydown",St),()=>{window.removeEventListener("keydown",St),cn.current&&clearInterval(cn.current)}},[e]);const na=async()=>{Mt(!0),zn([]),sn({scanned:0,total:0}),Ft(null);try{await ue.startTasmotaScan();const St=async()=>{try{const Bn=await ue.getTasmotaScanStatus();sn({scanned:Bn.scanned,total:Bn.total});const mr=await ue.getDiscoveredTasmotaDevices();zn(mr),Bn.running||(Mt(!1),cn.current&&(clearInterval(cn.current),cn.current=null))}catch(Bn){console.error("Polling error:",Bn)}};await St(),cn.current=setInterval(St,500)}catch(St){Mt(!1);const Bn=St instanceof Error?St.message:typeof St=="string"?St:JSON.stringify(St);Ft(Bn||n("smartPlugs.failedToStartScan"))}},qn=async()=>{try{await ue.stopTasmotaScan()}catch{}Mt(!1),cn.current&&(clearInterval(cn.current),cn.current=null)},ra=St=>{u(St.ip_address),c(St.name),dt(null)},br=it({mutationFn:()=>ue.testSmartPlugConnection(d,m||null,f||null),onSuccess:St=>{dt(St),Ft(null),!l&&St.device_name&&c(St.device_name)},onError:St=>{dt(null),Ft(St.message)}}),ki=it({mutationFn:St=>ue.createSmartPlug(St),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:St=>{Ft(St.message)}}),Ni=it({mutationFn:St=>ue.updateSmartPlug(t.id,St),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:St=>{Ft(St.message)}}),Rm=dn?.filter(St=>s==="tasmota"?!gn?.some(mr=>mr.printer_id===St.id&&mr.id!==t?.id&&mr.plug_type==="tasmota"):!0),au=St=>{if(St.preventDefault(),Ft(null),!l.trim()){Ft(n("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Ft("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Ft(n("smartPlugs.entityRequired"));return}if(s==="mqtt"){const mr=g.trim(),qt=T.trim(),ad=Y.trim();if(!mr&&!qt&&!ad){Ft(n("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!se.trim()&&!fe.trim()){Ft(n("smartPlugs.restUrlRequired"));return}const Bn={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"&&Te||null,ha_energy_today_entity:s==="homeassistant"&&Ae||null,ha_energy_total_entity:s==="homeassistant"&&Me||null,mqtt_power_topic:s==="mqtt"&&g.trim()||null,mqtt_power_path:s==="mqtt"&&C.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(N)||1,mqtt_energy_topic:s==="mqtt"&&T.trim()||null,mqtt_energy_path:s==="mqtt"&&k.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(H)||1,mqtt_state_topic:s==="mqtt"&&Y.trim()||null,mqtt_state_path:s==="mqtt"&&te.trim()||null,mqtt_state_on_value:s==="mqtt"&&J.trim()||null,rest_on_url:s==="rest"&&se.trim()||null,rest_on_body:s==="rest"&&W.trim()||null,rest_off_url:s==="rest"&&fe.trim()||null,rest_off_body:s==="rest"&&Pe.trim()||null,rest_method:s==="rest"?Q:null,rest_headers:s==="rest"&&j.trim()||null,rest_status_url:s==="rest"&&K.trim()||null,rest_status_path:s==="rest"&&me.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"&&B.trim()||null,rest_energy_path:s==="rest"&&re.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(Se)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:Nn,power_alert_enabled:ze,power_alert_high:gt?parseFloat(gt):null,power_alert_low:Ie?parseFloat(Ie):null,schedule_enabled:Ce,schedule_on_time:et||null,schedule_off_time:Xe||null,show_in_switchbar:Je,show_on_printer_card:vt};i?Ni.mutate(Bn):ki.mutate(Bn)},_l=ki.isPending||Ni.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:St=>St.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:au,className:"p-6 space-y-4 overflow-y-auto",children:[It&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:It}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),dt(null),Ft(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(nc,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),dt(null),Ft(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(Xw,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),dt(null),Ft(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(MO,{className:"w-4 h-4"}),"MQTT"]}),a.jsxs("button",{type:"button",onClick:()=>{o("rest"),dt(null),Ft(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(ul,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[wt?a.jsxs(De,{type:"button",variant:"secondary",onClick:qn,className:"w-full",children:[a.jsx(Bt,{className:"w-4 h-4"}),n("smartPlugs.stopScanning")]}):a.jsxs(De,{type:"button",variant:"primary",onClick:na,className:"w-full",children:[a.jsx(Cr,{className:"w-4 h-4"}),n("smartPlugs.discoverTasmota")]}),wt&&Gt.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:[Gt.scanned," / ",Gt.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:`${Gt.scanned/Gt.total*100}%`}})})]}),pn.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("smartPlugs.foundDevices",{count:pn.length})}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:pn.map(St=>a.jsxs("button",{type:"button",onClick:()=>ra(St),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(nc,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:St.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:St.ip_address})]})]}),St.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${St.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(Jd,{className:"w-3 h-3"}),St.state]})]},St.ip_address))})]}),!wt&&pn.length===0&&Gt.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:[!gr&&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")})})]})]}),gr&&a.jsxs(a.Fragment,{children:[En&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(ft,{className:"w-5 h-5 animate-spin mr-2"}),n("smartPlugs.loadingEntities")]}),Ea&&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:Ea.message})}),(()=>{const St=gn?.filter(qt=>qt.ha_entity_id&&qt.id!==t?.id).map(qt=>qt.ha_entity_id)||[],Bn=(Dr||[]).filter(qt=>!St.includes(qt.entity_id)),mr=Dr?.find(qt=>qt.entity_id===v);return a.jsxs("div",{ref:we,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:he?Oe:mr?`${mr.friendly_name} (${mr.entity_id})`:"",onChange:qt=>{qe(qt.target.value),he||Fe(!0)},onFocus:()=>{Fe(!0),qe("")},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&&!he&&a.jsx("button",{type:"button",onClick:()=>{b(""),qe("")},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"})}),En&&a.jsx(ft,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),he&&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:[En&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),n("smartPlugs.loading")]}),!En&&Bn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Qe?n("smartPlugs.noEntitiesMatching",{search:Qe}):n("smartPlugs.noEntitiesAvailable")}),!En&&Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{b(qt.entity_id),Fe(!1),qe(""),l||c(qt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${qt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:qt.entity_id}),a.jsx("span",{className:qt.state==="on"?"text-bambu-green":"",children:qt.state})]})]},qt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Qe?n("smartPlugs.searchingEntities",{count:Bn.length}):n("smartPlugs.showingEntities",{count:Bn.length})})]})})(),v&&Pn&&Pn.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 St=Pn.filter(qt=>qt.unit_of_measurement==="W"||qt.unit_of_measurement==="kW"||qt.unit_of_measurement==="mW"),Bn=Ve?St.filter(qt=>qt.entity_id.toLowerCase().includes(Ve.toLowerCase())||qt.friendly_name.toLowerCase().includes(Ve.toLowerCase())):St,mr=Pn.find(qt=>qt.entity_id===Te);return a.jsxs("div",{ref:Be,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:de?Ve:mr?`${mr.friendly_name} (${mr.state} ${mr.unit_of_measurement})`:"",onChange:qt=>{je(qt.target.value),de||xe(!0)},onFocus:()=>{xe(!0),je("")},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"}),Te&&!de&&a.jsx("button",{type:"button",onClick:()=>{ve(""),je("")},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"})})]}),de&&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:()=>{ve(""),xe(!1),je("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{ve(qt.entity_id),xe(!1),je("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Te?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Bn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const St=Pn.filter(qt=>qt.unit_of_measurement==="kWh"||qt.unit_of_measurement==="Wh"||qt.unit_of_measurement==="MWh"),Bn=Ze?St.filter(qt=>qt.entity_id.toLowerCase().includes(Ze.toLowerCase())||qt.friendly_name.toLowerCase().includes(Ze.toLowerCase())):St,mr=Pn.find(qt=>qt.entity_id===Ae);return a.jsxs("div",{ref:Ut,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?Ze:mr?`${mr.friendly_name} (${mr.state} ${mr.unit_of_measurement})`:"",onChange:qt=>{pt(qt.target.value),xt||yt(!0)},onFocus:()=>{yt(!0),pt("")},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&&!xt&&a.jsx("button",{type:"button",onClick:()=>{Re(""),pt("")},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:()=>{Re(""),yt(!1),pt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{Re(qt.entity_id),yt(!1),pt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Bn.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:n("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const St=Pn.filter(qt=>qt.unit_of_measurement==="kWh"||qt.unit_of_measurement==="Wh"||qt.unit_of_measurement==="MWh"),Bn=Kt?St.filter(qt=>qt.entity_id.toLowerCase().includes(Kt.toLowerCase())||qt.friendly_name.toLowerCase().includes(Kt.toLowerCase())):St,mr=Pn.find(qt=>qt.entity_id===Me);return a.jsxs("div",{ref:an,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:Vt?Kt:mr?`${mr.friendly_name} (${mr.state} ${mr.unit_of_measurement})`:"",onChange:qt=>{tn(qt.target.value),Vt||Yt(!0)},onFocus:()=>{Yt(!0),tn("")},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"}),Me&&!Vt&&a.jsx("button",{type:"button",onClick:()=>{Le(""),tn("")},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"})})]}),Vt&&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:()=>{Le(""),Yt(!1),tn("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:n("smartPlugs.none")}),Bn.map(qt=>a.jsxs("button",{type:"button",onClick:()=>{Le(qt.entity_id),Yt(!1),tn("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${qt.entity_id===Me?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:qt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[qt.entity_id," • ",qt.state," ",qt.unit_of_measurement]})]},qt.entity_id)),Bn.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:[!Sn?.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")]}),Sn?.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:St=>_(St.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:C,onChange:St=>P(St.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:St=>A(St.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:St=>F(St.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:k,onChange:St=>D(St.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:H,onChange:St=>z(St.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:Y,onChange:St=>L(St.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:te,onChange:St=>ae(St.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:J,onChange:St=>le(St.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:Q,onChange:St=>E(St.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:se,onChange:St=>{oe(St.target.value),dt(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:W,onChange:St=>ne(St.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:fe,onChange:St=>{be(St.target.value),dt(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:Pe,onChange:St=>q(St.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:St=>O(St.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:K,onChange:St=>U(St.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:me,onChange:St=>I(St.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:St=>X(St.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:St=>ee(St.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:St=>ge(St.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:St=>ce(St.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:B,onChange:St=>R(St.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:re,onChange:St=>ke(St.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:St=>ye(St.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")})]}),(se.trim()||fe.trim())&&a.jsx("div",{className:"flex gap-2",children:a.jsxs(De,{type:"button",variant:"secondary",onClick:async()=>{dt(null);try{const St=se.trim()||fe.trim(),Bn=await ue.testRESTConnection(St,Q,j.trim()||null);dt({success:Bn.success}),Bn.success||Ft(Bn.error||n("smartPlugs.addSmartPlug.connectionFailed"))}catch{dt({success:!1}),Ft(n("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[a.jsx(rp,{className:"w-4 h-4"}),n("smartPlugs.testConnection")]})}),at&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${at.success?"text-green-400":"text-red-400"}`,children:[at.success?a.jsx(vr,{className:"w-4 h-4"}):a.jsx($d,{className:"w-4 h-4"}),at.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:St=>{u(St.target.value),dt(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(De,{type:"button",variant:"secondary",onClick:()=>br.mutate(),disabled:!d.trim()||br.isPending,children:[br.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(rp,{className:"w-4 h-4"}),n("smartPlugs.test")]})]})]}),s==="tasmota"&&at&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${at.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:at.success?a.jsxs(a.Fragment,{children:[a.jsx(vr,{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:[at.device_name&&n("smartPlugs.deviceLabel",{name:at.device_name}),n("smartPlugs.stateLabel",{state:at.state})]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx($d,{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:St=>c(St.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:St=>p(St.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:St=>x(St.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:Nn??"",onChange:St=>We(St.target.value?Number(St.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")}),Rm?.map(St=>a.jsx("option",{value:St.id,children:St.name},St.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(Zh,{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:St=>lt(St.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:gt,onChange:St=>rt(St.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:Ie,onChange:St=>ot(St.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(Qn,{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:Ce,onChange:St=>Ge(St.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"})]})]}),Ce&&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:et,onChange:St=>Ke(St.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:Xe,onChange:St=>Ue(St.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(Yw,{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:Je,onChange:St=>At(St.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(yl,{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:St=>$e(St.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(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("smartPlugs.cancel")}),a.jsxs(De,{type:"submit",disabled:_l,className:"flex-1",children:[_l?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(ws,{className:"w-4 h-4"}),n(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function On({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 Ztt({provider:t,onEdit:e}){const{t:n}=Dt(),r=rn(),[i,s]=w.useState(!1),[o,l]=w.useState(!1),[c,d]=w.useState(null),{data:u}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=it({mutationFn:b=>ue.updateNotificationProvider(t.id,b),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=it({mutationFn:()=>ue.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),x=it({mutationFn:()=>ue.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(Tt,{className:"relative",children:a.jsxs(jt,{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(Zh,{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:cg(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Jn(t.last_error_at)?.getTime()||0)>(Jn(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:n("notifications.error")}),a.jsx(On,{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(SN,{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(ea,{className:"w-3 h-3"}),n("notifications.digest",{time:t.daily_digest_time})]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(De,{size:"sm",variant:"secondary",disabled:x.isPending,onClick:()=>{d(null),x.mutate()},className:"w-full",children:[x.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(tS,{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(vr,{className:"w-4 h-4"}):a.jsx(ja,{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(qd,{className:"w-4 h-4"}),n("notifications.eventSettings")]}),o?a.jsx(cc,{className:"w-4 h-4"}):a.jsx(In,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(On,{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(SN,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.quietHours")})]}),a.jsx(On,{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(Qn,{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(ea,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:n("notifications.dailyDigest")})]}),a.jsx(On,{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(Qn,{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(De,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(Yu,{className:"w-4 h-4"}),n("notifications.edit")]}),a.jsx(De,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),i&&a.jsx(yn,{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 Jtt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function ent({provider:t,onClose:e}){const{t:n}=Dt(),r=rn(),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,x]=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),[C,P]=w.useState(t?.daily_digest_time||"08:00"),[N,A]=w.useState(t?.on_print_start??!1),[T,F]=w.useState(t?.on_print_complete??!0),[k,D]=w.useState(t?.on_print_failed??!0),[H,z]=w.useState(t?.on_print_stopped??!0),[Y,L]=w.useState(t?.on_print_progress??!1),[te,ae]=w.useState(t?.on_printer_offline??!1),[J,le]=w.useState(t?.on_printer_error??!1),[se,oe]=w.useState(t?.on_filament_low??!1),[W,ne]=w.useState(t?.on_maintenance_due??!1),[fe,be]=w.useState(t?.on_bed_cooled??!1),[Pe,q]=w.useState(t?.on_first_layer_complete??!1),[Q,E]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([ce,B])=>[ce,String(B)])):{}),[j,O]=w.useState(null),[K,U]=w.useState(null),{data:me}=Ye({queryKey:["printers"],queryFn:ue.getPrinters});w.useEffect(()=>{const ce=B=>{B.key==="Escape"&&e()};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[e]);const I=it({mutationFn:()=>ue.testNotificationConfig({provider_type:l,config:Q}),onSuccess:ce=>{O(ce),U(null)},onError:ce=>{O({success:!1,message:ce.message})}}),G=it({mutationFn:ce=>ue.createNotificationProvider(ce),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:ce=>{U(ce.message)}}),X=it({mutationFn:ce=>ue.updateNotificationProvider(t.id,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:ce=>{U(ce.message)}}),V=ce=>{if(ce.preventDefault(),U(null),!s.trim()){U(n("notifications.nameRequired"));return}const B=ge(l);for(const re of B)if(!Q[re.key]?.trim()){U(n("notifications.fieldRequired",{field:re.label}));return}const R={name:s.trim(),provider_type:l,config:Q,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?C:null,on_print_start:N,on_print_complete:T,on_print_failed:k,on_print_stopped:H,on_print_progress:Y,on_printer_offline:te,on_printer_error:J,on_filament_low:se,on_maintenance_due:W,on_bed_cooled:fe,on_first_layer_complete:Pe};i?X.mutate(R):G.mutate(R)},ee=G.isPending||X.isPending,ie=ce=>{switch(ce){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:B=>B.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:B=>B.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},ge=ce=>ie(ce).filter(B=>B.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:ce=>ce.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:[K&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:K}),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:ce=>o(ce.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:ce=>{c(ce.target.value),E({}),O(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:Jtt.map(ce=>a.jsx("option",{value:ce,children:n(`notifications.providerTypes.${ce}`,ce)},ce))}),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(ce=>!("showIf"in ce)||ce.showIf?.(Q)!==!1).map(ce=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[ce.label," ",ce.required&&"*"]}),ce.type==="select"&&"options"in ce&&ce.options?a.jsx("select",{value:Q[ce.key]||ce.options[0]?.value||"",onChange:B=>{E({...Q,[ce.key]:B.target.value}),O(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:ce.options.map(B=>a.jsx("option",{value:B.value,children:B.label},B.value))}):a.jsx("input",{type:ce.type,value:Q[ce.key]||"",onChange:B=>{E({...Q,[ce.key]:B.target.value}),O(null)},placeholder:ce.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"})]},ce.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(De,{type:"button",variant:"secondary",onClick:()=>{O(null),I.mutate()},disabled:I.isPending||ge(l).length>0&&!Q[ge(l)[0]?.key],className:"flex-1",children:[I.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(tS,{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(vr,{className:"w-5 h-5"}),a.jsx("span",{children:j.message})]}):a.jsxs(a.Fragment,{children:[a.jsx(ja,{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:ce=>u(ce.target.value?Number(ce.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")}),me?.map(ce=>a.jsx("option",{value:ce.id,children:ce.name},ce.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(On,{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:ce=>x(ce.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:ce=>b(ce.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(On,{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:C,onChange:ce=>P(ce.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(On,{checked:N,onChange:A})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.complete")}),a.jsx(On,{checked:T,onChange:F})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.failed")}),a.jsx(On,{checked:k,onChange:D})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.stopped")}),a.jsx(On,{checked:H,onChange:z})]}),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(On,{checked:Y,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(On,{checked:fe,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(On,{checked:Pe,onChange:q})]})]})]}),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(On,{checked:te,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(On,{checked:J,onChange:le})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.lowFilament")}),a.jsx(On,{checked:se,onChange:oe})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:n("notifications.maintenance")}),a.jsx(On,{checked:W,onChange:ne})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("notifications.cancel")}),a.jsxs(De,{type:"submit",disabled:ee,className:"flex-1",children:[ee?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(ws,{className:"w-4 h-4"}),n(i?"notifications.save":"notifications.add")]})]})]})]})})}function tnt({template:t,onClose:e}){const{t:n}=Dt(),r=rn(),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}=Ye({queryKey:["template-variables"],queryFn:ue.getTemplateVariables}),x=f?.find(A=>A.event_type===t.event_type),{data:v,isLoading:b}=Ye({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>ue.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});w.useEffect(()=>{const A=T=>{T.key==="Escape"&&e()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e]);const g=it({mutationFn:A=>ue.updateNotificationTemplate(t.id,A),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:A=>{u(A.message)}}),_=it({mutationFn:()=>ue.resetNotificationTemplate(t.id),onSuccess:A=>{o(A.title_template),c(A.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:A=>{u(A.message)}}),C=A=>{if(A.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=A=>{const T=i.current;if(!T)return;const F=T.selectionStart,k=T.selectionEnd,D=l,H=D.substring(0,F),z=D.substring(k),Y=H+`{${A}}`+z;c(Y),setTimeout(()=>{T.focus();const L=F+A.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:C,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:A=>o(A.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:A=>c(A.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")})]}),x&&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:x.variables.map(A=>a.jsxs("button",{type:"button",onClick:()=>P(A),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(or,{className:"w-3 h-3"}),A]},A))}),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(yl,{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(ft,{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(De,{type:"button",variant:"ghost",onClick:()=>_.mutate(),disabled:_.isPending,className:"text-orange-400 hover:text-orange-300",children:[_.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(co,{className:"w-4 h-4 mr-2"}),n("notifications.resetToDefault")]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,children:n("notifications.cancel")}),a.jsxs(De,{onClick:C,disabled:g.isPending||!N,children:[g.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(ws,{className:"w-4 h-4 mr-2"}),n("notifications.save")]})]})]})]})})}const nnt={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 rnt({onClose:t}){const{t:e}=Dt(),n=rn(),{showToast:r}=hn(),[i,s]=w.useState(7),[o,l]=w.useState(null),[c,d]=w.useState(!1),{data:u}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:x,isRefetching:v}=Ye({queryKey:["notification-logs",i,c],queryFn:()=>ue.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=Ye({queryKey:["notification-log-stats",i],queryFn:()=>ue.getNotificationLogStats(i)}),g=it({mutationFn:()=>ue.clearNotificationLogs(30),onSuccess:C=>{r(C.message,"success"),n.invalidateQueries({queryKey:["notification-logs"]}),n.invalidateQueries({queryKey:["notification-log-stats"]})},onError:C=>{r(`Failed to clear logs: ${C.message}`,"error")}}),_=C=>{const P=Jn(C);if(!P)return"";const A=new Date().getTime()-P.getTime();return A<6e4?e("notifications.justNow"):A<36e5?`${Math.floor(A/6e4)}m ago`:A<864e5?`${Math.floor(A/36e5)}h ago`:P.toLocaleDateString()+" "+sZ(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(tw,{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(vr,{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(ja,{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:C=>s(Number(C.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:C=>d(C.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(De,{size:"sm",variant:"secondary",onClick:()=>x(),disabled:v,children:[v?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),e("notifications.refresh")]}),a.jsxs(De,{size:"sm",variant:"secondary",onClick:()=>g.mutate(),disabled:g.isPending,className:"text-red-400 hover:text-red-300",children:[g.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{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(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?a.jsx("div",{className:"space-y-2",children:p.map(C=>a.jsx(ant,{log:C,isExpanded:o===C.id,onToggle:()=>l(o===C.id?null:C.id),formatDate:_,formatFullDate:P=>dg(P,m)},C.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(tw,{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 ant({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){const{t:s}=Dt();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(vr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx(ja,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${nnt[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(cc,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(In,{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 int({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Dt();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(Tt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:[a.jsx(xn,{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(Gu,{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(De,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Bt,{className:"w-5 h-5"})})]})}),a.jsxs(jt,{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(De,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(De,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(or,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function snt(){const{t}=Dt(),e=rn(),{showToast:n}=hn(),[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,x]=w.useState("all"),[v,b]=w.useState(!1),[g,_]=w.useState(!1),[C,P]=w.useState(!1),{data:N,isLoading:A}=Ye({queryKey:["spoolman-settings"],queryFn:ue.getSpoolmanSettings}),{data:T,isLoading:F,refetch:k}=Ye({queryKey:["spoolman-status"],queryFn:ue.getSpoolmanStatus,refetchInterval:3e4}),{data:D}=Ye({queryKey:["printers"],queryFn:ue.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 ne=setTimeout(()=>{H.mutate()},500);return()=>clearTimeout(ne)}},[r,s,l,d,m,v]);const H=it({mutationFn:()=>ue.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"))}}),z=it({mutationFn:ue.connectSpoolman,onSuccess:()=>{k()}}),Y=it({mutationFn:ue.disconnectSpoolman,onSuccess:()=>{k()}}),L=it({mutationFn:ue.syncAllPrintersAms,onSuccess:W=>{W.success}}),te=it({mutationFn:W=>ue.syncPrinterAms(W),onSuccess:W=>{W.success}}),ae=()=>{f==="all"?L.mutate():te.mutate(f)},J=it({mutationFn:ue.syncWeightsFromAms,onSuccess:W=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:W.synced,skipped:W.skipped}),"success"),P(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),P(!1)}}),le=L.isPending||te.isPending,se=f==="all"?L.data:te.data,oe=f==="all"?L.isSuccess:te.isSuccess;return A?a.jsxs(Tt,{id:"card-spoolman",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Jl,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(jt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(Tt,{id:"card-spoolman",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Jl,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),H.isPending&&a.jsx(ft,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(jt,{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(Ra,{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(zr,{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(da,{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(zr,{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(vs,{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(De,{variant:"secondary",size:"sm",onClick:()=>P(!0),disabled:J.isPending,children:[J.isPending?a.jsx(ft,{className:"w-4 h-4 mr-2 animate-spin"}):a.jsx(cr,{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(vs,{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:W=>o(W.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:W=>c(W.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:W=>u(W.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:W=>p(W.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"),":"]}),F?a.jsx(ft,{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(zr,{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(De,{variant:"secondary",size:"sm",onClick:()=>Y.mutate(),disabled:Y.isPending,children:[Y.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(Jge,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(De,{size:"sm",onClick:()=>z.mutate(),disabled:z.isPending||!s,children:[z.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(im,{className:"w-4 h-4"}),t("settings.connect")]})})]}),z.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:z.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:W=>x(W.target.value==="all"?"all":Number(W.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")}),D?.map(W=>a.jsx("option",{value:W.id,children:W.name},W.id))]}),a.jsx(In,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:ae,disabled:le,children:[le?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),oe&&se&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${se.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:se.success?`Synced ${se.synced_count} spool${se.synced_count!==1?"s":""} successfully`:`Synced ${se.synced_count} spool${se.synced_count!==1?"s":""} with ${se.errors.length} error${se.errors.length!==1?"s":""}`}),se.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(Dn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[se.skipped_count," spool",se.skipped_count!==1?"s":""," skipped"]})]}),se.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?se.skipped:se.skipped.slice(0,5)).map((W,ne)=>a.jsxs("li",{className:"flex items-center gap-2",children:[W.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${W.color}`}}),a.jsx("span",{children:W.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",W.reason]})]},ne)),!g&&se.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",se.skipped_count-5," more"]})]})]}),se.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:se.errors.map((W,ne)=>a.jsx("li",{children:W},ne))})]})]})]})]})]}),C&&a.jsx(yn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:J.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>J.mutate(),onCancel:()=>P(!1)})]})}function ont(){const{t}=Dt(),{showToast:e}=hn(),[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,x]=w.useState(""),[v,b]=w.useState(""),[g,_]=w.useState(!1),[C,P]=w.useState(new Set),[N,A]=w.useState(!1),[T,F]=w.useState(null),[k,D]=w.useState(!1),H=w.useCallback(async()=>{try{const be=await ue.getSpoolCatalog();r(be)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{H()},[H]);const z=n.filter(be=>be.name.toLowerCase().includes(o.toLowerCase())),Y=async()=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const be=await ue.addCatalogEntry({name:f.trim(),weight:parseInt(v)});r(Pe=>[...Pe,be].sort((q,Q)=>q.name.localeCompare(Q.name))),u(!1),x(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},L=be=>{p(be.id),x(be.name),b(be.weight.toString())},te=()=>{p(null),x(""),b("")},ae=async be=>{if(!f.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const Pe=await ue.updateCatalogEntry(be,{name:f.trim(),weight:parseInt(v)});r(q=>q.map(Q=>Q.id===be?Pe:Q).sort((Q,E)=>Q.name.localeCompare(E.name))),p(null),x(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},J=async()=>{if(T)try{await ue.deleteCatalogEntry(T.id),r(be=>be.filter(Pe=>Pe.id!==T.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{F(null)}},le=async()=>{D(!1),s(!0);try{await ue.resetSpoolCatalog(),await H(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},se=be=>{P(Pe=>{const q=new Set(Pe);return q.has(be)?q.delete(be):q.add(be),q})},oe=()=>{C.size===z.length?P(new Set):P(new Set(z.map(be=>be.id)))},W=async()=>{if(A(!1),C.size!==0)try{const be=await ue.bulkDeleteCatalogEntries([...C]);r(Pe=>Pe.filter(q=>!C.has(q.id))),P(new Set),e(t("settings.catalog.bulkDeleted",{count:be.deleted}),"success")}catch{e(t("settings.catalog.bulkDeleteFailed"),"error")}},ne=()=>{const be=n.map(({name:E,weight:j})=>({name:E,weight:j})),Pe=new Blob([JSON.stringify(be,null,2)],{type:"application/json"}),q=URL.createObjectURL(Pe),Q=document.createElement("a");Q.href=q,Q.download="spool-catalog.json",document.body.appendChild(Q),Q.click(),document.body.removeChild(Q),URL.revokeObjectURL(q),e(t("settings.catalog.exported",{count:n.length}),"success")},fe=async be=>{const Pe=be.target.files?.[0];if(Pe){try{const q=await Pe.text(),Q=JSON.parse(q);if(!Array.isArray(Q))throw new Error("Invalid format");let E=0,j=0;for(const O of Q){if(!O.name||typeof O.weight!="number"){j++;continue}if(n.some(U=>U.name.toLowerCase()===O.name.toLowerCase())){j++;continue}try{const U=await ue.addCatalogEntry({name:O.name,weight:O.weight});r(me=>[...me,U].sort((I,G)=>I.name.localeCompare(G.name))),E++}catch{j++}}e(t("settings.catalog.imported",{added:E,skipped:j}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(Tt,{id:"card-spool-catalog",children:[a.jsxs(xn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Jl,{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:ne,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(ga,{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(La,{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:fe}),a.jsxs("button",{onClick:()=>D(!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(co,{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(or,{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.catalog.selectedCount",{count:C.size})}),a.jsxs("button",{onClick:()=>A(!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(en,{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(jt,{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=>x(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:Y,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(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(zr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{u(!1),x(""),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(ft,{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:z.length>0&&C.size===z.length,onChange:oe,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:z.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")})}):z.map(be=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${C.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:C.has(be.id),onChange:()=>se(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:Pe=>x(Pe.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:Pe=>b(Pe.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(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(zr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:te,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(be.id),onChange:()=>se(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(oi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>F(be),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(en,{className:"w-4 h-4"})})]})})]})},be.id))})]})})]}),T&&a.jsx(yn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:T.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:J,onCancel:()=>F(null)}),N&&a.jsx(yn,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:C.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:W,onCancel:()=>A(!1)}),k&&a.jsx(yn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:le,onCancel:()=>D(!1)})]})}function lnt(){const{t}=Dt(),{showToast:e}=hn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),[c,d]=w.useState(""),u=w.useRef(null),[m,p]=w.useState(!1),[f,x]=w.useState(null),[v,b]=w.useState(""),[g,_]=w.useState(""),[C,P]=w.useState("#FFFFFF"),[N,A]=w.useState(""),[T,F]=w.useState(!1),[k,D]=w.useState(new Set),[H,z]=w.useState(!1),[Y,L]=w.useState(!1),[te,ae]=w.useState(null),[J,le]=w.useState(null),[se,oe]=w.useState(!1),W=w.useCallback(async()=>{try{const V=await ue.getColorCatalog();r(V)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{W()},[W]);const ne=[...new Set(n.map(V=>V.manufacturer))].sort(),fe=n.filter(V=>{const ee=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 ee&&ie}),be=()=>{b(""),_(""),P("#FFFFFF"),A("")},Pe=async()=>{if(!v.trim()||!g.trim()||!C){e(t("settings.colorCatalog.fieldsRequired"),"error");return}F(!0);try{const V=await ue.addColorEntry({manufacturer:v.trim(),color_name:g.trim(),hex_color:C,material:N.trim()||null});r(ee=>[...ee,V].sort((ie,ge)=>ie.manufacturer.localeCompare(ge.manufacturer)||(ie.material||"").localeCompare(ge.material||"")||ie.color_name.localeCompare(ge.color_name))),p(!1),be(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{F(!1)}},q=V=>{x(V.id),b(V.manufacturer),_(V.color_name),P(V.hex_color),A(V.material||"")},Q=()=>{x(null),be()},E=async V=>{if(!v.trim()||!g.trim()||!C){e(t("settings.colorCatalog.fieldsRequired"),"error");return}F(!0);try{const ee=await ue.updateColorEntry(V,{manufacturer:v.trim(),color_name:g.trim(),hex_color:C,material:N.trim()||null});r(ie=>ie.map(ge=>ge.id===V?ee:ge).sort((ge,pe)=>ge.manufacturer.localeCompare(pe.manufacturer)||(ge.material||"").localeCompare(pe.material||"")||ge.color_name.localeCompare(pe.color_name))),x(null),be(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{F(!1)}},j=async()=>{if(J)try{await ue.deleteColorEntry(J.id),r(V=>V.filter(ee=>ee.id!==J.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{le(null)}},O=async()=>{oe(!1),s(!0);try{await ue.resetColorCatalog(),await W(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},K=async()=>{L(!0),ae(null);try{const V={},ee=ym();ee&&(V.Authorization=`Bearer ${ee}`);const ie=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:V});if(!ie.ok)throw new Error("Failed to start sync");const ge=ie.body?.getReader();if(!ge)throw new Error("No response body");const pe=new TextDecoder;let ce="";for(;;){const{done:B,value:R}=await ge.read();if(B)break;ce+=pe.decode(R,{stream:!0});const re=ce.split(` `);ce=re.pop()||"";for(const ke of re)if(ke.startsWith("data: "))try{const Se=JSON.parse(ke.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 W()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{L(!1),ae(null)}},U=V=>{D(ee=>{const ie=new Set(ee);return ie.has(V)?ie.delete(V):ie.add(V),ie})},me=()=>{k.size===fe.length?D(new Set):D(new Set(fe.map(V=>V.id)))},I=async()=>{if(z(!1),k.size!==0)try{const V=await ue.bulkDeleteColorEntries([...k]);r(ee=>ee.filter(ie=>!k.has(ie.id))),D(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:ce,hex_color:B,material:R})=>({manufacturer:pe,color_name:ce,hex_color:B,material:R})),ee=new Blob([JSON.stringify(V,null,2)],{type:"application/json"}),ie=URL.createObjectURL(ee),ge=document.createElement("a");ge.href=ie,ge.download="color-catalog.json",document.body.appendChild(ge),ge.click(),document.body.removeChild(ge),URL.revokeObjectURL(ie),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},X=async V=>{const ee=V.target.files?.[0];if(ee){try{const ie=await ee.text(),ge=JSON.parse(ie);if(!Array.isArray(ge))throw new Error("Invalid format");let pe=0,ce=0;for(const B of ge){if(!B.manufacturer||!B.color_name||!B.hex_color){ce++;continue}if(n.some(re=>re.manufacturer.toLowerCase()===B.manufacturer.toLowerCase()&&re.color_name.toLowerCase()===B.color_name.toLowerCase()&&(re.material||"").toLowerCase()===(B.material||"").toLowerCase())){ce++;continue}try{const re=await ue.addColorEntry({manufacturer:B.manufacturer,color_name:B.color_name,hex_color:B.hex_color,material:B.material||null});r(ke=>[...ke,re].sort((Se,ye)=>Se.manufacturer.localeCompare(ye.manufacturer)||(Se.material||"").localeCompare(ye.material||"")||Se.color_name.localeCompare(ye.color_name))),pe++}catch{ce++}}e(t("settings.colorCatalog.imported",{added:pe,skipped:ce}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}u.current&&(u.current.value="")}};return a.jsxs(Tt,{id:"card-color-catalog",children:[a.jsxs(xn,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Zw,{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(ga,{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(La,{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:K,disabled:Y,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:[Y?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(wy,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:Y?te?`${Math.min(te.fetched,te.total)} / ${te.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),a.jsxs("button",{onClick:()=>oe(!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(co,{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(or,{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.colorCatalog.selectedCount",{count:k.size})}),a.jsxs("button",{onClick:()=>z(!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(en,{className:"w-4 h-4"}),t("settings.colorCatalog.deleteSelected")]}),a.jsx("button",{onClick:()=>D(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),a.jsxs(jt,{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")}),ne.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:C,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:C,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=>A(V.target.value)}),a.jsxs("button",{onClick:Pe,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(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(zr,{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:fe.length,total:n.length})}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(ft,{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:fe.length>0&&k.size===fe.length,onChange:me,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:fe.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")})}):fe.map(V=>a.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${k.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:k.has(V.id),onChange:()=>U(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:C,onChange:ee=>P(ee.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:ee=>b(ee.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:ee=>A(ee.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:ee=>_(ee.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:C,onChange:ee=>P(ee.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:()=>E(V.id),disabled:T,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:T?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(zr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:Q,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(V.id),onChange:()=>U(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:()=>q(V),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(oi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>le(V),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(en,{className:"w-4 h-4"})})]})})]})},V.id))})]})})]}),J&&a.jsx(yn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${J.manufacturer} - ${J.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:j,onCancel:()=>le(null)}),H&&a.jsx(yn,{title:t("settings.colorCatalog.deleteSelected"),message:t("settings.colorCatalog.bulkDeleteConfirm",{count:k.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:I,onCancel:()=>z(!1)}),se&&a.jsx(yn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:O,onCancel:()=>oe(!1)})]})}function cnt({link:t,onClose:e}){const{t:n}=Dt(),r=rn(),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),[x,v]=w.useState(!!t?.custom_icon),[b,g]=w.useState(t?.custom_icon?ue.getExternalLinkIconUrl(t.id):null),[_,C]=w.useState(null),[P,N]=w.useState(null);w.useEffect(()=>{const Y=L=>{L.key==="Escape"&&e()};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[e]);const A=it({mutationFn:async Y=>{const L=await ue.createExternalLink(Y);return _?await ue.uploadExternalLinkIcon(L.id,_):L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:Y=>{N(Y.message)}}),T=it({mutationFn:async Y=>{let L=await ue.updateExternalLink(t.id,Y);return _?L=await ue.uploadExternalLinkIcon(t.id,_):!x&&t?.custom_icon&&(L=await ue.deleteExternalLinkIcon(t.id)),L},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:Y=>{N(Y.message)}}),F=Y=>{const L=Y.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}C(L),v(!0);const ae=new FileReader;ae.onload=J=>{g(J.target?.result)},ae.readAsDataURL(L)}},k=()=>{C(null),g(null),v(!1),s.current&&(s.current.value="")},D=Y=>{if(Y.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):A.mutate(L)},H=A.isPending||T.isPending,z=VP(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:Y=>Y.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:x&&b?a.jsx("img",{src:b,alt:"",className:"w-5 h-5 rounded"}):a.jsx(z,{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:D,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:Y=>l(Y.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:Y=>d(Y.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:F}),x&&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:k,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:a.jsx(en,{className:"w-4 h-4"})})]}):a.jsxs(De,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[a.jsx(La,{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."})]}),!x&&a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),a.jsx(wye,{value:u,onChange:m})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(De,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(De,{type:"submit",disabled:H,className:"flex-1",children:[H?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(ws,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function dnt(){const{t}=Dt(),e=rn(),[n,r]=w.useState(!1),[i,s]=w.useState(null),[o,l]=w.useState(null),[c,d]=w.useState(null),{data:u,isLoading:m}=Ye({queryKey:["external-links"],queryFn:ue.getExternalLinks}),p=it({mutationFn:C=>ue.deleteExternalLink(C),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),f=it({mutationFn:C=>ue.reorderExternalLinks(C),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),x=(C,P)=>{d(P),C.dataTransfer.effectAllowed="move"},v=C=>{C.preventDefault(),C.dataTransfer.dropEffect="move"},b=(C,P)=>{if(C.preventDefault(),c===null||c===P||!u)return;const N=u.map(k=>k.id),A=N.indexOf(c),T=N.indexOf(P);if(A===-1||T===-1)return;const F=[...N];F.splice(A,1),F.splice(T,0,c),f.mutate(F),d(null)},g=C=>{l(C)},_=()=>{o&&(p.mutate(o.id),l(null))};return a.jsxs(a.Fragment,{children:[a.jsxs(Tt,{id:"card-sidebar-links",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(im,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),a.jsxs(De,{size:"sm",onClick:()=>r(!0),children:[a.jsx(or,{className:"w-4 h-4"}),"Add Link"]})]})}),a.jsxs(jt,{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(ft,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?a.jsx("div",{className:"space-y-2",children:u.map(C=>{const P=VP(C.icon);return a.jsxs("div",{draggable:!0,onDragStart:N=>x(N,C.id),onDragOver:v,onDrop:N=>b(N,C.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===C.id?"opacity-50":""}`,children:[a.jsx(np,{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:C.name}),a.jsx(da,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),a.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:C.url})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{onClick:()=>s(C),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(oi,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>g(C),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(en,{className:"w-4 h-4"})})]})]},C.id)})}):a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(im,{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(cnt,{link:i,onClose:()=>{r(!1),s(null)}}),o&&a.jsx(yn,{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 v3={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function unt({printer:t,models:e}){const{t:n}=Dt(),r=rn(),{showToast:i}=hn(),[s,o]=w.useState(!0),[l,c]=w.useState(t.enabled),[d,u]=w.useState(t.name),[m,p]=w.useState(""),[f,x]=w.useState(t.mode==="queue"?"review":t.mode),[v,b]=w.useState(t.target_printer_id),[g,_]=w.useState(t.bind_ip||""),[C,P]=w.useState(t.remote_interface_ip||""),[N,A]=w.useState(t.model||""),[T,F]=w.useState(t.auto_dispatch??!0),[k,D]=w.useState(!1),[H,z]=w.useState(null),[Y,L]=w.useState(!1);w.useEffect(()=>{H||(c(t.enabled),x(t.mode==="queue"?"review":t.mode),u(t.name),b(t.target_printer_id),_(t.bind_ip||""),P(t.remote_interface_ip||""),A(t.model||""),F(t.auto_dispatch??!0))},[t,H]);const{data:te}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),{data:ae}=Ye({queryKey:["network-interfaces"],queryFn:()=>ue.getNetworkInterfaces().then(j=>j.interfaces)}),J=it({mutationFn:j=>NN.update(t.id,j),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(n("virtualPrinter.toast.updated")),z(null)},onError:j=>{i(j.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),x(t.mode==="queue"?"review":t.mode),b(t.target_printer_id),_(t.bind_ip||""),z(null)}}),le=it({mutationFn:()=>NN.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)}}),se=j=>{j.stopPropagation();const O=!l;if(O){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(O),z("toggle"),J.mutate({enabled:O})},oe=()=>{d.trim()&&(z("name"),J.mutate({name:d.trim()}))},W=()=>{if(!m){i(n("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(m.length!==8){i(n("virtualPrinter.toast.accessCodeLength"),"error");return}z("accessCode"),J.mutate({access_code:m}),p("")},ne=j=>{x(j),z("mode"),J.mutate({mode:j})},fe=j=>{A(j),z("model"),J.mutate({model:j})},be=j=>{b(j),z("targetPrinter"),J.mutate({target_printer_id:j})},Pe=j=>{P(j),z("remoteInterface"),J.mutate({remote_interface_ip:j})},q=t.status?.running||!1,Q=n(`virtualPrinter.mode.${v3[f]||"archive"}`),E=te?.find(j=>j.id===v)?.name;return a.jsxs(a.Fragment,{children:[a.jsxs(Tt,{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(In,{className:"w-4 h-4"}):a.jsx(Za,{className:"w-4 h-4"})}),a.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${q?"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:Q}),t.model_name&&a.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),E&&a.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[f==="proxy"&&a.jsx(Z3,{className:"w-3 h-3 inline mr-1"}),E]}),g&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:g}),C&&a.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:C}),a.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:j=>j.stopPropagation(),children:a.jsx("button",{onClick:se,disabled:H==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${H==="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(jt,{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:oe,onKeyDown:j=>j.key==="Enter"&&oe(),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(en,{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:()=>ne(j),disabled:H==="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(Z3,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${v3[j]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${v3[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;F(j),z("autoDispatch"),J.mutate({auto_dispatch:j})},disabled:H==="autoDispatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${T?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${H==="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=>fe(j.target.value),disabled:H==="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,O])=>a.jsxs("option",{value:j,children:[O," (",j,")"]},j))}),a.jsx(In,{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(vs,{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(zr,{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(Dn,{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:k?"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:()=>D(!k),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:k?a.jsx(Eg,{className:"w-4 h-4"}):a.jsx(yl,{className:"w-4 h-4"})})]}),a.jsx(De,{onClick:W,disabled:!m||H==="accessCode",variant:"primary",children:H==="accessCode"?a.jsx(ft,{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 O=parseInt(j.target.value,10);isNaN(O)||be(O)},disabled:H==="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")}),te?.map(j=>a.jsxs("option",{value:j.id,children:[j.name," (",j.ip_address,")"]},j.id))]}),a.jsx(In,{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),z("bindIp"),J.mutate({bind_ip:j.target.value})},disabled:H==="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(In,{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")}),C?a.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:a.jsx(zr,{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(vs,{className:"w-3 h-3"})})]}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:C,onChange:j=>Pe(j.target.value),disabled:H==="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(In,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),Y&&a.jsx(yn,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:le.isPending,onConfirm:()=>le.mutate(),onCancel:()=>L(!1)})]})}const bY={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function mnt({onClose:t}){const{t:e}=Dt(),n=rn(),{showToast:r}=hn(),[i,s]=w.useState(""),[o,l]=w.useState("immediate"),[c,d]=w.useState(null),{data:u}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),m=it({mutationFn:()=>NN.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(Tt,{className:"w-full max-w-md",onClick:p=>p.stopPropagation(),children:a.jsxs(jt,{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(Z3,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${bY[p]}`)]}),a.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${bY[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(In,{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(De,{variant:"secondary",onClick:t,className:"flex-1",disabled:m.isPending,children:e("common.cancel")}),a.jsx(De,{variant:"primary",onClick:()=>m.mutate(),className:"flex-1",disabled:m.isPending,children:m.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function hnt(){const{t}=Dt(),[e,n]=w.useState(!1),{data:r,isLoading:i}=Ye({queryKey:["virtual-printers"],queryFn:NN.list,refetchInterval:1e4});if(i)return a.jsx(Tt,{children:a.jsx(jt,{className:"py-8 flex justify-center",children:a.jsx(ft,{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(Tt,{className:"border-l-4 border-l-yellow-500",children:a.jsx(jt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(Dn,{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(da,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),a.jsx(Tt,{className:"lg:col-span-3",children:a.jsx(jt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2",children:[a.jsx(vs,{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(Mr,{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(De,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(or,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),s.length===0?a.jsx(Tt,{children:a.jsxs(jt,{className:"py-8 text-center",children:[a.jsx(Mr,{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(De,{variant:"primary",onClick:()=>n(!0),children:[a.jsx(or,{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(unt,{printer:l,models:o},l.id))}),e&&a.jsx(mnt,{onClose:()=>n(!1)})]})}function xY(t){if(t<60)return`${t}s`;const e=Math.floor(t/60);if(e<60)return`${e}m`;const n=Math.floor(e/60),r=e%60;if(n<24)return r?`${n}h ${r}m`:`${n}h`;const i=Math.floor(n/24),s=n%24;return s?`${i}d ${s}h`:`${i}d`}function yY(t){return t==null?"—":t>=1024?`${(t/1024).toFixed(1)} GB`:`${Math.round(t)} MB`}function pnt({device:t,onUnregister:e,isDeleting:n}){const{t:r}=Dt(),{showToast:i}=hn(),s=t.system_stats,o=s?.memory,l=s?.disk,c=t.online,[d,u]=w.useState(null),[m,p]=w.useState(null),f=async g=>{p(g);try{g==="update"?await $r.triggerUpdate(t.device_id):await $r.systemCommand(t.device_id,g),i(r("settings.spoolbuddy.commandQueued"),"success")}catch(_){const C=_ instanceof Error?_.message:r("settings.spoolbuddy.commandError");i(C,"error")}finally{p(null),u(null)}},x=[{key:"update",label:r("settings.spoolbuddy.update"),icon:ga},{key:"restart_browser",label:r("settings.spoolbuddy.restartBrowser"),icon:jO},{key:"restart_daemon",label:r("settings.spoolbuddy.restartDaemon"),icon:cr},{key:"reboot",label:r("settings.spoolbuddy.reboot"),icon:nw},{key:"shutdown",label:r("settings.spoolbuddy.shutdown"),icon:Jd,variant:"danger"}],v={update:r("settings.spoolbuddy.updateConfirmTitle"),restart_browser:r("settings.spoolbuddy.restartBrowserConfirmTitle"),restart_daemon:r("settings.spoolbuddy.restartDaemonConfirmTitle"),reboot:r("settings.spoolbuddy.rebootConfirmTitle"),shutdown:r("settings.spoolbuddy.shutdownConfirmTitle")},b={update:r("settings.spoolbuddy.updateConfirmBody",{hostname:t.hostname}),restart_browser:r("settings.spoolbuddy.restartBrowserConfirmBody",{hostname:t.hostname}),restart_daemon:r("settings.spoolbuddy.restartDaemonConfirmBody",{hostname:t.hostname}),reboot:r("settings.spoolbuddy.rebootConfirmBody",{hostname:t.hostname}),shutdown:r("settings.spoolbuddy.shutdownConfirmBody",{hostname:t.hostname})};return a.jsxs(Tt,{children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[a.jsxs("div",{className:"min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("h3",{className:"text-base font-semibold text-white truncate",children:t.hostname}),a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${c?"bg-green-500/15 text-green-400 border border-green-500/40":"bg-gray-500/15 text-gray-400 border border-gray-500/40"}`,children:[c?a.jsx(rp,{className:"w-3 h-3"}):a.jsx($d,{className:"w-3 h-3"}),r(c?"settings.spoolbuddy.online":"settings.spoolbuddy.offline")]})]}),a.jsx("p",{className:"text-xs text-bambu-gray font-mono mt-1 truncate",children:t.device_id})]}),a.jsxs(De,{variant:"danger",size:"sm",onClick:()=>e(t),disabled:n,"aria-label":r("settings.spoolbuddy.unregister"),children:[a.jsx(en,{className:"w-3.5 h-3.5"}),a.jsx("span",{className:"hidden sm:inline",children:r("settings.spoolbuddy.unregister")})]})]})}),a.jsxs(jt,{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.ipAddress")}),a.jsx("div",{className:"text-white font-mono",children:t.ip_address})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.firmware")}),a.jsx("div",{className:"text-white",children:t.firmware_version??"—"})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"text-bambu-gray flex items-center gap-1",children:[a.jsx(Qn,{className:"w-3 h-3"}),r("settings.spoolbuddy.lastSeen")]}),a.jsx("div",{className:"text-white",children:t.last_seen?ap(t.last_seen):r("settings.spoolbuddy.never")})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.daemonUptime")}),a.jsx("div",{className:"text-white",children:xY(t.uptime_s)})]})]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:x.map(({key:g,label:_,icon:C,variant:P})=>a.jsxs(De,{variant:P??"secondary",size:"sm",onClick:()=>u(g),disabled:!c||m!==null,"aria-label":_,children:[m===g?a.jsx(ft,{className:"w-3.5 h-3.5 animate-spin"}):a.jsx(C,{className:"w-3.5 h-3.5"}),a.jsx("span",{children:_})]},g))}),a.jsxs("div",{className:"flex items-center gap-3 text-xs flex-wrap",children:[a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.nfc_ok?a.jsx(dl,{className:"w-3.5 h-3.5 text-green-400"}):a.jsx(ja,{className:"w-3.5 h-3.5 text-red-400"}),r("settings.spoolbuddy.nfc"),t.nfc_reader_type&&a.jsxs("span",{className:"text-bambu-gray/70",children:["(",t.nfc_reader_type,")"]})]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.scale_ok?a.jsx(dl,{className:"w-3.5 h-3.5 text-green-400"}):a.jsx(ja,{className:"w-3.5 h-3.5 text-red-400"}),r("settings.spoolbuddy.scale")]})]}),s&&a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 text-xs",children:[s.cpu_temp_c!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(rS,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.cpuTemp")}),a.jsxs("div",{className:"text-white",children:[s.cpu_temp_c.toFixed(1),"°C"]})]})]}),o&&o.percent!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(o0,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.memory")}),a.jsxs("div",{className:"text-white",children:[o.percent.toFixed(0),"% (",yY(o.used_mb)," / ",yY(o.total_mb),")"]})]})]}),l&&l.percent!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Dg,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.disk")}),a.jsxs("div",{className:"text-white",children:[l.percent.toFixed(0),"% (",l.used_gb?.toFixed(1)," / ",l.total_gb?.toFixed(1)," GB)"]})]})]}),s.system_uptime_s!==void 0&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Qn,{className:"w-3.5 h-3.5 text-bambu-gray"}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.systemUptime")}),a.jsx("div",{className:"text-white",children:xY(s.system_uptime_s)})]})]})]}),s.os&&a.jsx("div",{className:"mt-3 text-xs text-bambu-gray font-mono truncate",children:[s.os.os,s.os.kernel,s.os.arch,s.os.python&&`Python ${s.os.python}`].filter(Boolean).join(" · ")})]})]}),d&&a.jsx(yn,{variant:d==="shutdown"||d==="reboot"?"danger":"default",title:v[d],message:b[d],confirmText:r("settings.spoolbuddy.commandConfirm"),isLoading:m!==null,onConfirm:()=>f(d),onCancel:()=>u(null)})]})}function fnt(){const{t}=Dt(),e=rn(),{showToast:n}=hn(),[r,i]=w.useState(null),{data:s=[],isLoading:o}=Ye({queryKey:["spoolbuddy-devices"],queryFn:()=>$r.getDevices(),refetchInterval:15e3}),l=it({mutationFn:d=>$r.deleteDevice(d),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolbuddy-devices"]}),n(t("settings.spoolbuddy.unregisterSuccess"),"success"),i(null)},onError:d=>{n(d.message||t("settings.spoolbuddy.unregisterError"),"error")}});if(o)return a.jsx(Tt,{children:a.jsx(jt,{className:"py-8 flex justify-center",children:a.jsx(ft,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const c=s.length>1;return a.jsxs("div",{className:"space-y-4",children:[a.jsx(Tt,{children:a.jsx(jt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[a.jsx(vs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.infoTitle")}),a.jsx("p",{children:t("settings.spoolbuddy.infoBody")})]})]})})}),c&&a.jsx(Tt,{className:"border-l-4 border-l-yellow-500",children:a.jsx(jt,{className:"py-3 px-4",children:a.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[a.jsx(Dn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-bambu-gray",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.duplicatesTitle",{count:s.length})}),a.jsx("p",{children:t("settings.spoolbuddy.duplicatesBody")})]})]})})}),s.length===0?a.jsx(Tt,{children:a.jsx(jt,{className:"py-8 text-center text-bambu-gray text-sm",children:t("settings.spoolbuddy.empty")})}):a.jsx("div",{className:"space-y-3",children:s.map(d=>a.jsx(pnt,{device:d,onUnregister:i,isDeleting:l.isPending&&l.variables===d.device_id},d.id))}),r&&a.jsx(yn,{variant:"danger",title:t("settings.spoolbuddy.confirmTitle"),message:t("settings.spoolbuddy.confirmBody",{hostname:r.hostname,deviceId:r.device_id}),confirmText:t("settings.spoolbuddy.unregister"),isLoading:l.isPending,onConfirm:()=>l.mutate(r.device_id),onCancel:()=>i(null)})]})}function w3(t){if(!t)return"-";const e=Jn(t);return e?e.toLocaleString():"-"}function S3({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(vr,{className:"w-3 h-3"}),failed:a.jsx(ja,{className:"w-3 h-3"}),skipped:a.jsx($P,{className:"w-3 h-3"}),running:a.jsx(ft,{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 gnt(){const t=rn(),{showToast:e}=hn(),{t:n}=Dt(),[r,i]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[d,u]=w.useState(!1),[m,p]=w.useState("daily"),[f,x]=w.useState(!0),[v,b]=w.useState(!0),[g,_]=w.useState(!1),[C,P]=w.useState(!1),[N,A]=w.useState(!1),[T,F]=w.useState(!0),[k,D]=w.useState(!1),[H,z]=w.useState(!1),[Y,L]=w.useState(""),[te,ae]=w.useState(!1),[J,le]=w.useState(null),[se,oe]=w.useState(null),W=w.useRef(null),[ne,fe]=w.useState(null),[be,Pe]=w.useState(null),[q,Q]=w.useState(""),{data:E,refetch:j}=Ye({queryKey:["local-backup-status"],queryFn:ue.getLocalBackupStatus,refetchInterval:he=>he.state.data?.is_running?1e3:1e4}),{data:O,refetch:K}=Ye({queryKey:["local-backup-files"],queryFn:ue.getLocalBackups,refetchInterval:3e4});w.useEffect(()=>{E?.path!==void 0&&Q(E.path)},[E?.path]);const U=it({mutationFn:ue.triggerLocalBackup,onSuccess:he=>{he.success?e(n("backup.scheduledBackupComplete")):e(he.message,"error"),j(),K()},onError:()=>e(n("backup.scheduledBackupFailed"),"error")}),me=it({mutationFn:he=>ue.deleteLocalBackup(he),onSuccess:()=>{K(),fe(null)}}),I=it({mutationFn:async he=>(Pe(null),z(!0),oe(null),L(n("backup.restoring")),ue.restoreLocalBackup(he)),onSuccess:he=>{z(!1),L(""),he.success?(oe({success:!0,message:he.message}),e(n("backup.backupRestoredRestart"),"success")):(oe({success:!1,message:he.message}),e(he.message,"error"))},onError:he=>{z(!1),L("");const Fe=he instanceof Error?he.message:n("backup.failedToRestore");oe({success:!1,message:Fe}),e(Fe,"error")}});w.useEffect(()=>{if(k||H){const Fe=we=>(we.preventDefault(),we.returnValue="A backup operation is in progress. Are you sure you want to leave?",we.returnValue);return window.addEventListener("beforeunload",Fe),()=>window.removeEventListener("beforeunload",Fe)}},[k,H]);const[G,X]=w.useState(!1),[V,ee]=w.useState(null),ie=w.useRef(null),ge=w.useRef(!1),{data:pe,isLoading:ce}=Ye({queryKey:["github-backup-config"],queryFn:ue.getGitHubBackupConfig}),{data:B}=Ye({queryKey:["github-backup-status"],queryFn:ue.getGitHubBackupStatus,refetchInterval:he=>he.state.data?.is_running?500:1e4}),{data:R}=Ye({queryKey:["github-backup-logs"],queryFn:()=>ue.getGitHubBackupLogs(20)}),{data:re}=Ye({queryKey:["cloud-status"],queryFn:ue.getCloudStatus}),{data:ke}=Ye({queryKey:["printers"],queryFn:ue.getPrinters}),Se=Pp({queries:(ke??[]).map(he=>({queryKey:["printerStatus",he.id],queryFn:()=>ue.getPrinterStatus(he.id),staleTime:1e4,refetchInterval:3e4}))}),ye=(ke??[]).map((he,Fe)=>({printer:he,connected:Se[Fe]?.data?.connected??!1})),Te=ye.length,ve=ye.filter(he=>he.connected).length,Ae=Te>0&&ve===0,Re=ve>0&&ve{pe&&(i(pe.repository_url),c(pe.branch),u(pe.schedule_enabled),p(pe.schedule_type),x(pe.backup_kprofiles),b(pe.backup_cloud_profiles),_(pe.backup_settings),P(pe.backup_spools),A(pe.backup_archives),F(pe.enabled),o(""),setTimeout(()=>{ge.current=!0},100))},[pe]);const Me=w.useCallback(async(he=!1)=>{if(pe?.has_token)try{he&&s?(await ue.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:C,backup_archives:N,enabled:T}),o(""),e(n("backup.tokenUpdated"))):(await ue.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:d,schedule_type:m,backup_kprofiles:f,backup_cloud_profiles:v,backup_settings:g,backup_spools:C,backup_archives:N,enabled:T}),e(n("backup.settingsSaved"))),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(Fe){e(n("backup.failedToSave",{message:Fe.message}),"error")}},[pe?.has_token,r,s,l,d,m,f,v,g,C,N,T,t,e,n]);w.useEffect(()=>{if(!(!ge.current||!pe?.has_token))return ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{Me(!1)},500),()=>{ie.current&&clearTimeout(ie.current)}},[r,l,d,m,f,v,g,C,N,T,Me,pe?.has_token]),w.useEffect(()=>{if(!(!ge.current||!pe?.has_token||!s))return ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{Me(!0)},1e3),()=>{ie.current&&clearTimeout(ie.current)}},[s,Me,pe?.has_token]);const Le=it({mutationFn:he=>ue.saveGitHubBackupConfig(he),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e(n("backup.githubBackupEnabled")),o(""),ge.current=!0},onError:he=>{e(n("backup.failedToSave",{message:he.message}),"error")}}),Oe=it({mutationFn:ue.triggerGitHubBackup,onSuccess:he=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),he.success?he.files_changed>0?e(n("backup.backupCompleteFiles",{count:he.files_changed})):e(n("backup.backupSkippedNoChanges")):e(n("backup.backupFailed2",{message:he.message}),"error")},onError:he=>{e(n("backup.backupFailed2",{message:he.message}),"error")}}),qe=it({mutationFn:()=>ue.clearGitHubBackupLogs(0),onSuccess:he=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(n("backup.clearedLogs",{count:he.deleted}))},onError:he=>{e(n("backup.failedToClearLogs",{message:he.message}),"error")}}),Qe=async()=>{X(!0),ee(null);try{let he;if(s){if(!r){e(n("backup.enterRepoUrl"),"error"),X(!1);return}he=await ue.testGitHubConnection(r,s)}else if(pe?.has_token)he=await ue.testGitHubStoredConnection();else{e(n("backup.enterRepoAndToken"),"error"),X(!1);return}ee({success:he.success,message:he.message})}catch(he){ee({success:!1,message:he.message})}finally{X(!1)}},tt=()=>{if(!r){e(n("backup.repoRequired"),"error");return}if(!s){e(n("backup.tokenRequired"),"error");return}Le.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:C,backup_archives:N,enabled:T})};return ce?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(ft,{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(Tt,{id:"card-backup-github",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(eF,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.githubBackup")})]}),pe&&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(On,{checked:T,onChange:F})]})]})}),a.jsxs(jt,{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:he=>{i(he.target.value),ee(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")," ",pe?.has_token&&a.jsx("span",{className:"text-green-400",children:n("backup.tokenSaved")})]}),a.jsx("input",{type:"password",value:s,onChange:he=>{o(he.target.value),ee(null)},placeholder:pe?.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:he=>c(he.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:he=>{he.target.value==="disabled"?u(!1):(u(!0),p(he.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 ${Ae?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[a.jsx("input",{type:"checkbox",checked:f,onChange:he=>x(he.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:Ae}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${Ae?"text-bambu-gray":"text-white"}`,children:n("backup.kProfiles")}),Ae&&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(Dn,{className:"w-3 h-3"}),n("backup.noPrintersConnected")]}),Re&&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(Dn,{className:"w-3 h-3"}),n("backup.printersConnected",{connected:ve,total:Te})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:n("backup.kProfilesDescription")})]})]}),a.jsxs("label",{className:`flex items-start gap-2 ${re?.is_authenticated?"cursor-pointer":"cursor-not-allowed opacity-60"}`,children:[a.jsx("input",{type:"checkbox",checked:v,onChange:he=>b(he.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:!re?.is_authenticated}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${re?.is_authenticated?"text-white":"text-bambu-gray"}`,children:n("backup.cloudProfiles")}),!re?.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(Dn,{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:he=>_(he.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:C,onChange:he=>P(he.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:he=>A(he.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:[B?.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:B.last_backup_at?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[n("backup.lastBackupAt")," ",ap(B.last_backup_at,"system",n)]}),a.jsx(S3,{status:B.last_backup_status})]}):a.jsx("span",{children:n("backup.noBackupsYet")})}),B.next_scheduled_run&&a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx(Qn,{className:"w-3 h-3 inline mr-1"}),n("backup.next")," ",ap(B.next_scheduled_run,"system",n)]})]}),V&&a.jsxs("div",{className:`text-sm flex items-center gap-1 ${V.success?"text-green-400":"text-red-400"}`,children:[V.success?a.jsx(vr,{className:"w-4 h-4"}):a.jsx(ja,{className:"w-4 h-4"}),V.message]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:B?.configured?a.jsx(a.Fragment,{children:Oe.isPending||B.is_running?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{className:"text-sm",children:B.progress||n("backup.startingBackup")})]}):a.jsxs(a.Fragment,{children:[a.jsxs(De,{variant:"primary",size:"sm",onClick:()=>Oe.mutate(),disabled:!pe?.enabled,children:[a.jsx(Ji,{className:"w-4 h-4"}),n("backup.backupNow")]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:Qe,disabled:G,children:[G?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),n("backup.test")]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs(De,{variant:"primary",size:"sm",onClick:tt,disabled:Le.isPending||!r||!s,children:[Le.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(vr,{className:"w-4 h-4"}),n("backup.enableBackup")]}),a.jsxs(De,{variant:"secondary",size:"sm",onClick:Qe,disabled:G||!r||!s,children:[G?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(cr,{className:"w-4 h-4"}),n("backup.testConnection")]})]})})]})]})]}),R&&R.length>0&&a.jsxs(Tt,{id:"card-backup-history",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tw,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.history")})]}),a.jsxs(De,{variant:"ghost",size:"sm",onClick:()=>qe.mutate(),disabled:qe.isPending,children:[a.jsx(en,{className:"w-4 h-4"}),n("backup.clear")]})]})}),a.jsx(jt,{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:R.slice(0,10).map(he=>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:w3(he.started_at)}),a.jsx("td",{className:"py-2 px-2",children:a.jsx(S3,{status:he.status})}),a.jsx("td",{className:"py-2 px-2",children:he.commit_sha?a.jsxs("a",{href:`${pe?.repository_url}/commit/${he.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[he.commit_sha.substring(0,7),a.jsx(da,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-bambu-gray",children:"-"})})]},he.id))})]})})})]})]}),a.jsxs("div",{className:"space-y-6",children:[a.jsxs(Tt,{id:"card-backup-local",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Jl,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.localBackup")})]})}),a.jsxs(jt,{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(De,{variant:"secondary",size:"sm",disabled:k||H,onClick:async()=>{D(!0),L(n("backup.preparingBackup"));try{L(n("backup.creatingArchive"));const{blob:he,filename:Fe}=await ue.exportBackup();L(n("backup.downloadingFile"));const we=URL.createObjectURL(he),Ve=document.createElement("a");Ve.href=we,Ve.download=Fe,Ve.click(),URL.revokeObjectURL(we),e(n("backup.backupDownloaded"))}catch(he){e(n("backup.failedToCreateBackup",{message:he instanceof Error?he.message:"Unknown error"}),"error")}finally{D(!1),L("")}},children:[a.jsx(ga,{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:W,type:"file",accept:".zip",className:"hidden",onChange:he=>{const Fe=he.target.files?.[0];Fe&&(le(Fe),ae(!0)),he.target.value=""}}),a.jsxs(De,{variant:"secondary",size:"sm",disabled:H||k,onClick:()=>W.current?.click(),children:[a.jsx(La,{className:"w-4 h-4"}),n("backup.restore")]})]}),se&&a.jsx("div",{className:`p-3 rounded-lg ${se.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:[se.success?a.jsx(vr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):a.jsx(ja,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:se.success?"text-green-200":"text-red-200",children:[se.message,se.success&&a.jsx("div",{className:"mt-2",children:a.jsxs(De,{size:"sm",onClick:()=>window.location.reload(),children:[a.jsx(co,{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(Dn,{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")})]})]})})]})]}),a.jsxs(Tt,{id:"card-backup-scheduled",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(mge,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:n("backup.scheduledBackup")})]}),a.jsx(On,{checked:E?.enabled??!1,onChange:async he=>{try{await ue.updateSettings({local_backup_enabled:he}),e(n("backup.settingsSaved"))}catch(Fe){e(n("backup.failedToSave",{message:Fe instanceof Error?Fe.message:"Unknown error"}),"error")}j()}})]})}),a.jsxs(jt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.scheduledBackupDescription")}),E?.enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.frequency")}),a.jsxs("select",{value:E?.schedule??"daily",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",onChange:async he=>{try{await ue.updateSettings({local_backup_schedule:he.target.value}),e(n("backup.settingsSaved"))}catch(Fe){e(n("backup.failedToSave",{message:Fe instanceof Error?Fe.message:"Unknown error"}),"error")}j()},children:[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")})]})]}),(E?.schedule??"daily")!=="hourly"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.backupTime")}),a.jsx("input",{type:"time",value:E?.time??"03:00",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 [color-scheme:dark]",onChange:async he=>{try{await ue.updateSettings({local_backup_time:he.target.value}),e(n("backup.settingsSaved"))}catch(Fe){e(n("backup.failedToSave",{message:Fe instanceof Error?Fe.message:"Unknown error"}),"error")}j()}}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.utc")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.retention")}),a.jsx("input",{type:"number",min:1,max:100,value:E?.retention??5,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",onChange:async he=>{const Fe=Math.max(1,Math.min(100,parseInt(he.target.value)||5));try{await ue.updateSettings({local_backup_retention:Fe}),e(n("backup.settingsSaved"))}catch(we){e(n("backup.failedToSave",{message:we instanceof Error?we.message:"Unknown error"}),"error")}j()}}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.retentionDescription")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("backup.outputPath")}),a.jsx("input",{type:"text",value:q,onChange:he=>Q(he.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",onBlur:async()=>{try{await ue.updateSettings({local_backup_path:q}),e(n("backup.settingsSaved"))}catch(he){e(n("backup.failedToSave",{message:he instanceof Error?he.message:"Unknown error"}),"error")}j(),K()},onKeyDown:he=>{he.key==="Enter"&&he.target.blur()}}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:q?n("backup.outputPathDescription"):a.jsxs(a.Fragment,{children:[n("backup.defaultPathLabel")," ",a.jsx("code",{className:"text-bambu-gray",children:E?.default_path||"..."})]})})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"text-sm",children:[E?.last_backup_at&&a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsxs("span",{children:[n("backup.lastBackup"),":"]}),a.jsx(S3,{status:E.last_status}),a.jsx("span",{children:ap(E.last_backup_at)})]}),E?.next_run&&a.jsxs("div",{className:"text-bambu-gray mt-1",children:[a.jsxs("span",{children:[n("backup.nextBackup"),": "]}),a.jsx("span",{children:w3(E.next_run)})]})]}),a.jsxs(De,{variant:"secondary",size:"sm",disabled:E?.is_running||U.isPending,onClick:()=>U.mutate(),children:[E?.is_running||U.isPending?a.jsx(ft,{className:"w-4 h-4 animate-spin"}):a.jsx(Ji,{className:"w-4 h-4"}),E?.is_running?n("backup.backupRunning"):n("backup.runNow")]})]}),O&&O.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:n("backup.backupFiles")}),a.jsx("div",{className:"space-y-1",children:O.map(he=>a.jsxs("div",{className:"flex items-center justify-between py-1.5 px-2 rounded hover:bg-bambu-dark-tertiary/50 text-sm",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("span",{className:"text-white truncate block",children:he.filename}),a.jsxs("span",{className:"text-bambu-gray text-xs",children:[(he.size/1024/1024).toFixed(1)," MB · ",w3(he.created_at)]})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{className:"text-bambu-gray hover:text-bambu-green p-1",title:n("backup.download"),onClick:async()=>{try{const{blob:Fe,filename:we}=await ue.downloadLocalBackup(he.filename),Ve=URL.createObjectURL(Fe),je=document.createElement("a");je.href=Ve,je.download=we,je.click(),URL.revokeObjectURL(Ve)}catch{e(n("backup.scheduledBackupFailed"),"error")}},children:a.jsx(ga,{className:"w-3.5 h-3.5"})}),a.jsx("button",{className:"text-bambu-gray hover:text-yellow-400 p-1",title:n("backup.restore"),onClick:()=>Pe(he.filename),children:a.jsx(co,{className:"w-3.5 h-3.5"})}),a.jsx("button",{className:"text-bambu-gray hover:text-red-400 p-1",onClick:()=>fe(he.filename),title:n("backup.deleteBackup"),children:a.jsx(en,{className:"w-3.5 h-3.5"})})]})]},he.filename))})]}),O&&O.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray text-center py-3 border-t border-bambu-dark-tertiary",children:n("backup.noScheduledBackups")})]})]})]})]}),ne&&a.jsx(yn,{title:n("backup.deleteBackup"),message:n("backup.deleteBackupConfirm"),confirmText:n("backup.deleteBackup"),variant:"danger",onConfirm:()=>me.mutate(ne),onCancel:()=>fe(null)}),be&&a.jsx(yn,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:be}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:()=>I.mutate(be),onCancel:()=>Pe(null)}),te&&J&&a.jsx(yn,{title:n("backup.restoreConfirmTitle"),message:n("backup.restoreConfirmMessage",{filename:J.name}),confirmText:n("backup.restoreConfirmButton"),variant:"danger",onConfirm:async()=>{ae(!1),z(!0),oe(null);try{L(n("backup.uploadingFile"));const he=await ue.importBackup(J);oe(he),he.success?e(n("backup.backupRestoredRestart"),"success"):e(he.message,"error")}catch(he){const Fe=he instanceof Error?he.message:n("backup.failedToRestore");oe({success:!1,message:Fe}),e(Fe,"error")}finally{z(!1),L(""),le(null)}},onCancel:()=>{ae(!1),le(null)}}),(k||H)&&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(k?"backup.creatingBackup":"backup.restoringBackup")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:Y||n(k?"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(Dn,{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")})]})})]})})]})}function bnt(){const{t}=Dt(),e=rn(),{showToast:n}=hn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("medium"),[d,u]=w.useState("notify"),[m,p]=w.useState(10),[f,x]=w.useState(null),[v,b]=w.useState(null),[g,_]=w.useState(!1),{data:C}=Ye({queryKey:["settings"],queryFn:ue.getSettings}),{data:P,refetch:N}=Ye({queryKey:["obico-status"],queryFn:ue.getObicoStatus,refetchInterval:1e4}),{data:A}=Ye({queryKey:["printers"],queryFn:ue.getPrinters});w.useEffect(()=>{if(C){i(C.obico_enabled??!1),o(C.obico_ml_url??""),c(C.obico_sensitivity??"medium"),u(C.obico_action??"notify"),p(C.obico_poll_interval??10);try{const D=C.obico_enabled_printers?JSON.parse(C.obico_enabled_printers):null;x(Array.isArray(D)?D:null)}catch{x(null)}_(!0)}},[C]);const T=it({mutationFn:()=>ue.updateSettings({obico_enabled:r,obico_ml_url:s,obico_sensitivity:l,obico_action:d,obico_poll_interval:m,obico_enabled_printers:f===null?"":JSON.stringify(f)}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]}),e.invalidateQueries({queryKey:["obico-status"]}),n(t("settings.toast.settingsSaved"))}});w.useEffect(()=>{if(!g||!C||!(C.obico_enabled!==r||C.obico_ml_url!==s||C.obico_sensitivity!==l||C.obico_action!==d||C.obico_poll_interval!==m||C.obico_enabled_printers!==(f===null?"":JSON.stringify(f))))return;const H=setTimeout(()=>T.mutate(),500);return()=>clearTimeout(H)},[r,s,l,d,m,f,g]);const F=async()=>{b(null);try{const D=await ue.testObicoConnection(s);D.ok?b({ok:!0,message:t("failureDetection.testSuccess")}):b({ok:!1,message:D.error||`HTTP ${D.status_code??"?"} — ${D.body??t("failureDetection.testFailed")}`})}catch(D){b({ok:!1,message:D instanceof Error?D.message:String(D)})}},k=(D,H)=>{if(f===null){const z=A?.map(L=>L.id)??[],Y=H?z:z.filter(L=>L!==D);x(Y);return}x(H?[...f,D]:f.filter(z=>z!==D))};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[a.jsxs(Tt,{id:"card-fd-ml",children:[a.jsxs(xn,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(HQ,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.title")})]}),a.jsx(On,{checked:r,onChange:i})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:t("failureDetection.description")})]}),a.jsxs(jt,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.mlUrl")}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:s,onChange:D=>o(D.target.value),placeholder:"http://192.168.1.10:3333",className:"flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",disabled:!r}),a.jsx(De,{onClick:F,disabled:!s||T.isPending,variant:"secondary",children:t("failureDetection.test")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.mlUrlHint")}),v&&a.jsxs("div",{className:`flex items-start gap-2 mt-2 text-sm ${v.ok?"text-green-400":"text-red-400"}`,children:[v.ok?a.jsx(zr,{className:"w-4 h-4 mt-0.5"}):a.jsx(Bt,{className:"w-4 h-4 mt-0.5"}),a.jsx("span",{children:v.message})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.sensitivity")}),a.jsxs("select",{value:l,onChange:D=>c(D.target.value),disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[a.jsx("option",{value:"low",children:t("failureDetection.sensitivityLow")}),a.jsx("option",{value:"medium",children:t("failureDetection.sensitivityMedium")}),a.jsx("option",{value:"high",children:t("failureDetection.sensitivityHigh")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.sensitivityHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.action")}),a.jsxs("select",{value:d,onChange:D=>u(D.target.value),disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[a.jsx("option",{value:"notify",children:t("failureDetection.actionNotify")}),a.jsx("option",{value:"pause",children:t("failureDetection.actionPause")}),a.jsx("option",{value:"pause_and_off",children:t("failureDetection.actionPauseOff")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.pollInterval")}),a.jsx("input",{type:"number",value:m,onChange:D=>p(Math.max(5,Math.min(120,Number(D.target.value)||10))),min:5,max:120,disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.pollIntervalHint")})]}),P&&!P.external_url_configured&&r&&a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-900/30 border border-amber-700 rounded text-sm text-amber-200",children:[a.jsx(Dn,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),a.jsxs("div",{children:[a.jsx("div",{className:"font-medium",children:t("failureDetection.externalUrlMissing")}),a.jsx("div",{className:"text-xs mt-1",children:t("failureDetection.externalUrlHint")})]})]})]})]}),a.jsxs(Tt,{id:"card-fd-perprinter",children:[a.jsxs(xn,{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.perPrinterTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("failureDetection.perPrinterHint")})]}),a.jsxs(jt,{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[a.jsx("input",{type:"checkbox",checked:f===null,onChange:D=>x(D.target.checked?null:A?.map(H=>H.id)??[]),disabled:!r}),a.jsx("span",{className:"text-white",children:t("failureDetection.monitorAll")})]}),f!==null&&A&&a.jsx("div",{className:"pl-5 space-y-1 border-l border-gray-700",children:A.map(D=>a.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[a.jsx("input",{type:"checkbox",checked:f.includes(D.id),onChange:H=>k(D.id,H.target.checked),disabled:!r}),a.jsx("span",{className:"text-white",children:D.name})]},D.id))})]})]})]}),a.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[a.jsxs(Tt,{id:"card-fd-status",children:[a.jsx(xn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.statusTitle")})}),a.jsx(jt,{children:P?a.jsxs("div",{className:"space-y-3 text-sm",children:[a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.serviceRunning")}),a.jsx("span",{className:P.is_running?"text-green-400":"text-red-400",children:P.is_running?t("common.yes"):t("common.no")})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.thresholds")}),a.jsxs("span",{className:"text-white font-mono",children:[P.thresholds.low.toFixed(2)," / ",P.thresholds.high.toFixed(2)]})]}),P.last_error&&a.jsxs("div",{className:"flex items-start gap-2 text-red-400",children:[a.jsx(Bt,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),a.jsx("span",{className:"break-words",children:P.last_error})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray mb-1",children:t("failureDetection.activePrinters")}),Object.keys(P.per_printer).length===0?a.jsx("div",{className:"text-bambu-gray italic text-xs",children:t("failureDetection.noActivePrints")}):a.jsx("div",{className:"space-y-1",children:Object.entries(P.per_printer).map(([D,H])=>{const z=A?.find(L=>String(L.id)===D),Y=H.class==="failure"?"text-red-400":H.class==="warning"?"text-amber-400":"text-green-400";return a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-white",children:z?.name??`Printer ${D}`}),a.jsxs("span",{className:`font-mono ${Y}`,children:[H.class," (",H.score.toFixed(3),", ",H.frame_count,"f)"]})]},D)})})]})]}):a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{children:t("common.loading")})]})})]}),a.jsxs(Tt,{id:"card-fd-history",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.historyTitle")}),a.jsx("button",{onClick:()=>N(),className:"text-xs text-bambu-gray hover:text-white",children:t("common.refresh")})]})}),a.jsx(jt,{children:!P||P.history.length===0?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(vs,{className:"w-4 h-4"}),a.jsx("span",{children:t("failureDetection.noHistory")})]}):a.jsx("div",{className:"space-y-1 max-h-96 overflow-y-auto text-xs font-mono",children:P.history.map((D,H)=>{const z=A?.find(L=>L.id===D.printer_id),Y=D.class==="failure"?"text-red-400":D.class==="warning"?"text-amber-400":"text-bambu-gray";return a.jsxs("div",{className:"flex justify-between gap-2 py-1 border-b border-gray-800",children:[a.jsx("span",{className:"text-bambu-gray",children:new Date(D.timestamp).toLocaleTimeString()}),a.jsx("span",{className:"text-white truncate",children:z?.name??`#${D.printer_id}`}),a.jsxs("span",{className:Y,children:[D.class," ",D.score.toFixed(3)]})]},H)})})})]})]})]})}const xnt={starttls:587,ssl:465,none:25},ynt={587:"starttls",465:"ssl",25:"none"};function vnt(){const{t}=Dt(),{showToast:e}=hn(),n=rn(),[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}=Ye({queryKey:["smtpSettings"],queryFn:()=>ue.getSMTPSettings()}),{authEnabled:d}=_r(),{data:u}=Ye({queryKey:["advancedAuthStatus"],queryFn:()=>ue.getAdvancedAuthStatus()});w.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const m=T=>{i({...r,smtp_security:T,smtp_port:xnt[T]})},p=T=>{const F=ynt[T];i({...r,smtp_port:T,...F?{smtp_security:F}:{}})},f=T=>{i({...r,smtp_auth_enabled:T,...T?{}:{smtp_username:"",smtp_password:""}})},x=it({mutationFn:T=>ue.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=it({mutationFn:T=>ue.testSMTP(T),onSuccess:T=>{e(T.message,T.success?"success":"error")},onError:T=>{e(T.message,"error")}}),b=it({mutationFn:T=>T?ue.enableAdvancedAuth():ue.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}x.mutate(r)},_=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}v.mutate({test_recipient:s})},C=()=>{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(ft,{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",A="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(Tt,{id:"card-email-advanced-auth",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gm,{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(De,{onClick:C,disabled:b.isPending,variant:P?"danger":"primary",children:P?a.jsxs(a.Fragment,{children:[a.jsx(N0,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(Pd,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),a.jsx(jt,{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(vr,{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(Dn,{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(Tt,{id:"card-smtp-config",children:[a.jsx(xn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),a.jsx(jt,{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:A})]}),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:A})]})]}),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(De,{onClick:g,disabled:x.isPending,className:"flex-1",children:x.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),a.jsx("div",{children:a.jsxs(Tt,{id:"card-email-test",children:[a.jsx(xn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),a.jsx(jt,{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(De,{onClick:_,disabled:v.isPending,variant:"secondary",children:v.isPending?a.jsxs(a.Fragment,{children:[a.jsx(ft,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):a.jsxs(a.Fragment,{children:[a.jsx(tS,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})]})}const wnt={starttls:"389",ldaps:"636"};function Snt(){const{t}=Dt(),{showToast:e}=hn(),n=rn(),{authEnabled:r}=_r(),[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}=Ye({queryKey:["settings"],queryFn:()=>ue.getSettings()}),{data:c}=Ye({queryKey:["ldapStatus"],queryFn:()=>ue.getLDAPStatus()}),{data:d=[]}=Ye({queryKey:["groups"],queryFn:()=>ue.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=it({mutationFn:g=>ue.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=it({mutationFn:g=>ue.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=it({mutationFn:()=>ue.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)},x=()=>{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(ft,{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(Tt,{id:"card-ldap-toggle",children:[a.jsx(xn,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Vu,{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(De,{onClick:x,disabled:m.isPending,variant:v?"danger":"primary",children:v?a.jsxs(a.Fragment,{children:[a.jsx(N0,{className:"w-4 h-4"}),t("common.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(Pd,{className:"w-4 h-4"}),t("common.enable")||"Enable"]})})]})}),a.jsx(jt,{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(vr,{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(Dn,{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(Tt,{id:"card-ldap-server",children:[a.jsx(xn,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.serverConfig")||"LDAP Server Configuration"})}),a.jsx(jt,{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: ${wnt[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(xz,{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" diff --git a/static/index.html b/static/index.html index 7d44e3def..d992edb08 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +