diff --git a/CHANGELOG.md b/CHANGELOG.md index 19bddcbc4..fac80d2af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.1b2] - Unreleased ### Fixed +- **PCTG Filament Misidentified as PC** ([#478](https://github.com/maziggy/bambuddy/issues/478)) — Selecting "Generic PCTG" as a filament profile defaulted to PC material. The spool form's material parser listed PC before PCTG and used substring matching (`indexOf`), so "PCTG" matched "PC" first. The AMS slot configuration and local profiles views were also missing PCTG from their known material types. Additionally, the temperature range logic used `includes('PC')` which matched PCTG and assigned PC temperatures (260-300°C) instead of PETG-range temperatures (220-260°C). Fixed by reordering PCTG before PC in the spool form parser, adding PCTG to all material type arrays, and adding an exact-match temperature case for PCTG. - **Phantom Prints From Lingering SD Card Files** ([#477](https://github.com/maziggy/bambuddy/issues/477)) — Prints could restart without user input hours after completing, because uploaded gcode files survived on the printer's SD card and were auto-started on firmware restart. Three bugs allowed files to linger. First, the post-print SD card cleanup retry loop always broke after the first attempt regardless of success, because `delete_file_async` catches errors internally and returns `False` instead of raising — the `except` retry branch never executed. Fixed by only breaking on successful delete and retrying with a 2-second delay on failure. Second, when `start_print()` failed after uploading a file (in both the background dispatcher and print scheduler), the uploaded file was never cleaned up since `on_print_complete` never fires for a print that never started. Now deletes the uploaded file on a best-effort basis when `start_print()` returns `False`. Third, cleanup failure logging was at `DEBUG` level, making failures invisible in normal operation — escalated to `WARNING`. - **Non-Actionable HMS Errors Triggering Notifications** ([#470](https://github.com/maziggy/bambuddy/issues/470)) — Infrastructure and auth-related HMS error codes (like `0500_0007` "MQTT command verification failed") were triggering printer error notifications even though they don't indicate actual print problems. For example, a device with incorrect bind settings sending unauthorized MQTT commands caused repeated false-alarm nozzle/extruder error notifications with camera snapshots of perfectly fine prints. Now suppresses notifications for known non-actionable error codes: `0500_0007` (MQTT auth failure), `0500_4001` (Bambu Cloud connection failure), and `0500_400E` (print cancelled by user). - **Support Bundle Leaking Personal Data** ([#473](https://github.com/maziggy/bambuddy/issues/473)) — The support bundle's log sanitizer only used regex patterns, which can't detect arbitrary user-chosen strings like printer names and usernames. Now queries the database for known sensitive values (printer names, serial numbers, auth usernames, Bambu Cloud email) and does exact-string replacement before the regex pass. Serial number regex no longer leaks the first 3 characters (was using a capture group for partial redaction). Tasmota smart plug credentials embedded in URLs (`http://user:pass@host`) were logged verbatim by httpx; now uses httpx's `auth` parameter for HTTP Basic auth so credentials never appear in the URL. Added `username` and `path` to the settings key filter to redact `smtp_username` and `slicer_binary_path` from the support info JSON. A URL credentials regex provides defense-in-depth for any remaining `user:pass@` patterns in logs. IP addresses are no longer redacted from the bundle as they are needed for connectivity debugging. Updated the frontend privacy disclaimer and wiki documentation to reflect the new behavior. diff --git a/backend/tests/unit/test_archive_filtering.py b/backend/tests/unit/test_archive_filtering.py index 6d558d23b..51abffae7 100644 --- a/backend/tests/unit/test_archive_filtering.py +++ b/backend/tests/unit/test_archive_filtering.py @@ -754,6 +754,8 @@ class TestAttachTimelapseBackgroundConversion: mock_create_task.assert_called_once() # Verify task name includes archive ID assert "timelapse-convert-1" in mock_create_task.call_args[1]["name"] + # Close the unawaited coroutine to prevent GC warning + mock_create_task.call_args[0][0].close() class TestDeleteTimelapse: diff --git a/frontend/src/components/ConfigureAmsSlotModal.tsx b/frontend/src/components/ConfigureAmsSlotModal.tsx index b57a352e8..b675c80cf 100644 --- a/frontend/src/components/ConfigureAmsSlotModal.tsx +++ b/frontend/src/components/ConfigureAmsSlotModal.tsx @@ -80,7 +80,7 @@ interface ConfigureAmsSlotModalProps { } // Known filament material types -const MATERIAL_TYPES = ['PLA', 'PETG', 'ABS', 'ASA', 'TPU', 'PC', 'PA', 'NYLON', 'PVA', 'HIPS', 'PP', 'PET']; +const MATERIAL_TYPES = ['PLA', 'PETG', 'PCTG', 'ABS', 'ASA', 'TPU', 'PC', 'PA', 'NYLON', 'PVA', 'HIPS', 'PP', 'PET']; // Extract filament type from preset name by finding known material type function parsePresetName(name: string): { material: string; brand: string; variant: string } { @@ -390,6 +390,9 @@ export function ConfigureAmsSlotModal({ } else if (material.includes('TPU')) { tempMin = 200; tempMax = 240; + } else if (material === 'PCTG') { + tempMin = 220; + tempMax = 260; } else if (material.includes('PC')) { tempMin = 260; tempMax = 300; diff --git a/frontend/src/components/LocalProfilesView.tsx b/frontend/src/components/LocalProfilesView.tsx index 86ff0757f..5e835ed35 100644 --- a/frontend/src/components/LocalProfilesView.tsx +++ b/frontend/src/components/LocalProfilesView.tsx @@ -22,7 +22,7 @@ import { useToast } from '../contexts/ToastContext'; import { useAuth } from '../contexts/AuthContext'; // Known material types for name-parsing fallback -const MATERIAL_TYPES = ['PLA', 'PETG', 'ABS', 'ASA', 'TPU', 'PC', 'PA', 'PVA', 'HIPS', 'PP', 'PET', 'NYLON']; +const MATERIAL_TYPES = ['PLA', 'PETG', 'PCTG', 'ABS', 'ASA', 'TPU', 'PC', 'PA', 'PVA', 'HIPS', 'PP', 'PET', 'NYLON']; const FILAMENT_TYPE_COLORS: Record = { PLA: 'E8E8E8', PETG: '4A90D9', ABS: 'E67E22', ASA: 'D35400', diff --git a/frontend/src/components/spool-form/utils.ts b/frontend/src/components/spool-form/utils.ts index fa5f7f83d..2b05224e3 100644 --- a/frontend/src/components/spool-form/utils.ts +++ b/frontend/src/components/spool-form/utils.ts @@ -36,7 +36,7 @@ export function parsePresetName(name: string): { brand: string; material: string const materials = [ 'PLA-CF', 'PETG-CF', 'ABS-GF', 'ASA-CF', 'PA-CF', 'PAHT-CF', 'PA6-CF', 'PA6-GF', 'PPA-CF', 'PPA-GF', 'PET-CF', 'PPS-CF', 'PC-CF', 'PC-ABS', 'ABS-GF', - 'PETG', 'PLA', 'ABS', 'ASA', 'PC', 'PA', 'TPU', 'PVA', 'HIPS', 'BVOH', 'PPS', 'PCTG', 'PEEK', 'PEI', + 'PCTG', 'PETG', 'PLA', 'ABS', 'ASA', 'PC', 'PA', 'TPU', 'PVA', 'HIPS', 'BVOH', 'PPS', 'PEEK', 'PEI', ]; // Find material in the name diff --git a/static/assets/index-DeeYbjZC.js b/static/assets/index-CsfKMedi.js similarity index 98% rename from static/assets/index-DeeYbjZC.js rename to static/assets/index-CsfKMedi.js index 9d3d97295..7e67486f0 100644 --- a/static/assets/index-DeeYbjZC.js +++ b/static/assets/index-CsfKMedi.js @@ -8482,7 +8482,7 @@ void main() { border-l-[5px] border-l-transparent border-r-[5px] border-r-transparent border-t-[5px] border-t-bambu-dark-tertiary - `})]})]})}function RHe({isOpen:t,onClose:e,tagUid:n,trayUuid:r,printerId:a,amsId:s,trayId:o}){const{t:l}=Ut(),c=tn(),{showToast:u}=cn(),[d,h]=w.useState(""),{data:f,isLoading:p}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!1),enabled:t}),x=w.useMemo(()=>f?f.filter(g=>{if(g.tag_uid||g.tray_uuid)return!1;if(!d)return!0;const y=d.toLowerCase();return g.material.toLowerCase().includes(y)||g.brand&&g.brand.toLowerCase().includes(y)||g.color_name&&g.color_name.toLowerCase().includes(y)}):[],[f,d]),v=ot({mutationFn:g=>ne.linkTagToSpool(g,{tag_uid:n||void 0,tray_uuid:r||void 0,tag_type:r?"bambulab":"generic",data_origin:"nfc_link"}),onSuccess:()=>{c.invalidateQueries({queryKey:["inventory-spools"]}),c.invalidateQueries({queryKey:["inventory-assignments"]}),u(l("inventory.tagLinked"),"success"),e()},onError:g=>{u(g.message||l("inventory.tagLinkFailed"),"error")}});return t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Bb,{className:"w-5 h-5 text-bambu-green"}),l("inventory.linkToSpool")]}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," · Printer #",a]})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 border-b border-white/10",children:[i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:d,onChange:g=>h(g.target.value),placeholder:l("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),(n||r)&&i.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:n||r,children:["Tag: ",n||r]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:p?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):x.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):x.map(g=>i.jsxs("button",{onClick:()=>v.mutate(g.id),disabled:v.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left",children:[i.jsx("span",{className:"w-6 h-6 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:g.rgba?`#${g.rgba.substring(0,6)}`:"#808080"}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"text-sm text-white font-medium truncate",children:[g.brand?`${g.brand} `:"",g.material,g.subtype?` ${g.subtype}`:""]}),i.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[g.color_name||"No color"," · #",g.id]})]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(g.label_weight-g.weight_used),"g"]})]},g.id))}),i.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:i.jsx(Ce,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function FHe({isOpen:t,onClose:e,printerId:n,amsId:r,trayId:a,trayInfo:s}){const{t:o}=Ut(),l=tn(),{showToast:c}=cn(),[u,d]=w.useState(null),[h,f]=w.useState(""),{data:p,isLoading:x}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(),enabled:t}),{data:v}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),enabled:t}),g=ot({mutationFn:M=>ne.assignSpool({spool_id:M,printer_id:n,ams_id:r,tray_id:a}),onSuccess:M=>{l.setQueryData(["spool-assignments"],C=>{const j=(C||[]).filter(P=>!(P.printer_id===n&&P.ams_id===r&&P.tray_id===a));return j.push(M),j}),l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.assignSuccess"),"success"),e()},onError:M=>{c(`${o("inventory.assignFailed")}: ${M.message}`,"error")}});if(!t)return null;const y=new Set((v||[]).filter(M=>!(M.printer_id===n&&M.ams_id===r&&M.tray_id===a)).map(M=>M.spool_id)),_=r===254||r===255,N=p?.filter(M=>!y.has(M.id)&&(_||!M.tag_uid&&!M.tray_uuid)),k=N?.filter(M=>{if(!h)return!0;const C=h.toLowerCase();return M.material.toLowerCase().includes(C)||(M.brand?.toLowerCase().includes(C)??!1)||(M.color_name?.toLowerCase().includes(C)??!1)||(M.subtype?.toLowerCase().includes(C)??!1)}),A=()=>{u&&g.mutate(u)};return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fi,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("inventory.assignSpool")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[s&&i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[o("inventory.selectSpool"),":"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${s.color}`}}),i.jsx("span",{className:"text-white font-medium",children:s.type||o("ams.emptySlot")}),i.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:h,onChange:M=>f(M.target.value),placeholder:o("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsx("div",{children:x?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):k&&k.length>0?i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-2",children:k.map(M=>i.jsx("button",{onClick:()=>d(M.id),className:`w-full p-3 rounded-lg border text-left transition-colors ${u===M.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center gap-2",children:[M.rgba&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:`#${M.rgba.substring(0,6)}`}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("p",{className:"text-white font-medium truncate",children:[M.brand?`${M.brand} `:"",M.material,M.subtype?` ${M.subtype}`:""]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[M.color_name||"",M.label_weight?` - ${M.label_weight}g`:"",M.label_weight?` (${Math.max(0,Math.round(M.label_weight-M.weight_used))}g ${o("ams.remainingUnit")})`:""]})]}),u===M.id&&i.jsx(ra,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]})},M.id))}):N&&N.length===0?i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noManualSpools")})}):i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noSpoolsMatch")})})})]}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:o("common.cancel")}),i.jsx(Ce,{onClick:A,disabled:!u||g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),o("inventory.assigning")]}):i.jsxs(i.Fragment,{children:[i.jsx(fi,{className:"w-4 h-4"}),o("inventory.assignSpool")]})})]}),g.isError&&i.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:g.error.message})]})]})}function LHe(t,e){if(t===255)return"External";let n,r=!1;t>=128&&t<=135?(n=t-128,r=!0):t>=0&&t<=3?(n=t,r=e===1):n=0,n=Math.max(0,Math.min(n,7));const a=String.fromCharCode(65+n);return r?`HT-${a}`:`AMS-${a}`}function x_(t){const e=t.includes("_")?t.split("_")[0]:t;return e.startsWith("GFS")?"GF"+e.slice(3):(e.startsWith("PFUS")||e.startsWith("PFSP"),e)}const OHe=["PLA","PETG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function G7(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const a of OHe){const s=new RegExp(`\\b${a}\\b`,"i");if(s.test(n)){const o=e.split(s),l=o[0]?.trim()||"",c=o[1]?.trim()||"";return{material:a,brand:l,variant:c}}}const r=e.split(/\s+/);return r.length>=2?{material:r[1],brand:r[0],variant:r.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function IHe(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const zHe={white:"FFFFFF",black:"000000",red:"FF0000",green:"00FF00",blue:"0000FF",yellow:"FFFF00",cyan:"00FFFF",magenta:"FF00FF",orange:"FFA500",purple:"800080",pink:"FFC0CB",brown:"8B4513",gray:"808080",grey:"808080","jade white":"FFFEF2",ivory:"FFFFF0",beige:"F5F5DC",cream:"FFFDD0",silver:"C0C0C0",gold:"FFD700",bronze:"CD7F32",copper:"B87333",navy:"000080",teal:"008080",olive:"808000",maroon:"800000",coral:"FF7F50",salmon:"FA8072",lime:"32CD32",mint:"98FF98","forest green":"228B22","sky blue":"87CEEB","royal blue":"4169E1",turquoise:"40E0D0",lavender:"E6E6FA",violet:"EE82EE",plum:"DDA0DD",tan:"D2B48C",chocolate:"D2691E",charcoal:"36454F",slate:"708090",transparent:"000000",natural:"F5F5DC",wood:"DEB887"},UHe=[{name:"White",hex:"FFFFFF"},{name:"Black",hex:"000000"},{name:"Red",hex:"FF0000"},{name:"Blue",hex:"0000FF"},{name:"Green",hex:"00AA00"},{name:"Yellow",hex:"FFFF00"},{name:"Orange",hex:"FFA500"},{name:"Gray",hex:"808080"}],BHe=[{name:"Cyan",hex:"00FFFF"},{name:"Magenta",hex:"FF00FF"},{name:"Purple",hex:"800080"},{name:"Pink",hex:"FFC0CB"},{name:"Brown",hex:"8B4513"},{name:"Beige",hex:"F5F5DC"},{name:"Navy",hex:"000080"},{name:"Teal",hex:"008080"},{name:"Lime",hex:"32CD32"},{name:"Gold",hex:"FFD700"},{name:"Silver",hex:"C0C0C0"},{name:"Maroon",hex:"800000"},{name:"Olive",hex:"808000"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Indigo",hex:"4B0082"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Slate",hex:"708090"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Cream",hex:"FFFDD0"}];function HHe(t){const e=t.toLowerCase().trim();return zHe[e]||null}function $He(t){const e=t.indexOf("@");if(e<0)return null;const r=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return r?r[1].trim():null}function VHe({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:a="0.4",printerModel:s,onSuccess:o}){const{t:l}=Ut(),[c,u]=w.useState(""),[d,h]=w.useState(null),[f,p]=w.useState(""),[x,v]=w.useState(""),[g,y]=w.useState(""),[_,N]=w.useState(!1),[k,A]=w.useState(!1),{data:M,isLoading:C,isError:j}=Je({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:t,retry:!1}),{data:P,isLoading:E}=Je({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets(),enabled:t}),{data:B,isLoading:O}=Je({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:U,isLoading:R}=Je({queryKey:["kprofiles",n,a],queryFn:()=>ne.getKProfiles(n,a),enabled:t&&!!n}),{data:V}=Je({queryKey:["colorCatalog"],queryFn:()=>ne.getColorCatalog(),enabled:t,staleTime:1/0}),G=ot({mutationFn:async()=>{if(!c)throw new Error("No filament preset selected");const te=c.startsWith("local_"),je=c.startsWith("builtin_"),ue=te?parseInt(c.replace("local_",""),10):null,oe=je?c.replace("builtin_",""):null,_e=te?P?.filament.find(fe=>fe.id===ue):null,se=je?B?.find(fe=>fe.filament_id===oe):null,Oe=!te&&!je?M?.filament.find(fe=>fe.setting_id===c):null;if(!te&&!je&&!Oe)throw new Error("Selected preset not found");if(te&&!_e)throw new Error("Selected local preset not found");if(je&&!se)throw new Error("Selected builtin preset not found");const q=te?_e.name:je?se.name:Oe.name,X=G7(q),de=d?.slot_id??-1,Z=f||r.trayColor?.slice(0,6)||"FFFFFF",ie=q.replace(/@.+$/,"").trim();let le,Fe;if(te){const fe=(_e?.filament_type||X.material||"").toUpperCase(),ze={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};le=ze[fe]||ze[fe.replace(/[-\s]?CF$/,"")]||ze[fe.replace(/\+$/,"")]||ze[fe.split(/[-\s]/)[0]]||"",Fe=""}else if(je)le=oe,Fe="";else if(le=x_(c),Fe=c,!c.startsWith("GFS"))try{const fe=await ne.getCloudSettingDetail(c);fe.filament_id?le=fe.filament_id:fe.base_id&&(le=x_(fe.base_id),console.log(`Derived tray_info_idx from base_id: ${fe.base_id} -> ${le}`))}catch(fe){console.warn("Failed to fetch preset detail for filament_id:",fe)}let pe=te&&_e?.nozzle_temp_min?_e.nozzle_temp_min:190,Q=te&&_e?.nozzle_temp_max?_e.nozzle_temp_max:230;if(!te||je||!_e?.nozzle_temp_min&&!_e?.nozzle_temp_max){const fe=(te&&_e?.filament_type||X.material).toUpperCase();fe.includes("PLA")?(pe=190,Q=230):fe.includes("PETG")?(pe=220,Q=260):fe.includes("ABS")||fe.includes("ASA")?(pe=240,Q=280):fe.includes("TPU")?(pe=200,Q=240):fe.includes("PC")?(pe=260,Q=300):(fe.includes("PA")||fe.includes("NYLON"))&&(pe=250,Q=290)}const L=d?.k_value?parseFloat(d.k_value):0,D=te?_e?.filament_type||X.material||"PLA":X.material||"PLA",H=await ne.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:le,tray_type:D,tray_sub_brands:ie,tray_color:Z+"FF",nozzle_temp_min:pe,nozzle_temp_max:Q,cali_idx:de,nozzle_diameter:a,setting_id:Fe,kprofile_filament_id:d?.filament_id,kprofile_setting_id:d?.setting_id||void 0,k_value:L}),he=te?`local_${ue}`:je?`builtin_${oe}`:c,be=te?"local":je?"builtin":"cloud";try{await ne.saveSlotPreset(n,r.amsId,r.trayId,he,ie,be)}catch(fe){console.warn("Failed to save slot preset mapping:",fe)}return H},onSuccess:()=>{N(!0),o?.(),setTimeout(()=>{N(!1),e()},1500)}}),z=ot({mutationFn:async()=>ne.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{N(!0),o?.(),setTimeout(()=>{N(!1),e()},1500)}}),K=w.useMemo(()=>{const te=g.toLowerCase(),je=[],ue=new Set,oe=r.savedPresetId,_e=r.trayInfoIdx;if(M?.filament)for(const se of M.filament){ue.add(se.setting_id);const Oe=oe===se.setting_id||_e&&(se.setting_id===_e||x_(se.setting_id)===_e);if(!(!Oe&&te&&!se.name.toLowerCase().includes(te))){if(!Oe&&s){const q=$He(se.name);if(q&&q.toUpperCase()!==s.toUpperCase())continue}je.push({id:se.setting_id,name:se.name,source:"cloud",isUser:IHe(se.setting_id)})}}if(P?.filament)for(const se of P.filament){const Oe=`local_${se.id}`,q=oe===Oe;if(!(!q&&te&&!se.name.toLowerCase().includes(te))){if(!q&&s&&se.compatible_printers){const X=se.compatible_printers.split(";").map(de=>{const Z=de.trim(),ie=Z.match(/^BBL\s+(.+)/i);return ie?ie[1].trim().toUpperCase():Z.toUpperCase()}).filter(Boolean);if(X.length>0&&!X.includes(s.toUpperCase()))continue}je.push({id:Oe,name:se.name,source:"local",isUser:!1})}}if(B)for(const se of B){if(ue.has(se.filament_id))continue;const Oe=se.filament_id.startsWith("GF")?"GFS"+se.filament_id.slice(2):se.filament_id;ue.has(Oe)||(!te||se.name.toLowerCase().includes(te))&&je.push({id:`builtin_${se.filament_id}`,name:se.name,source:"builtin",isUser:!1})}return je.sort((se,Oe)=>{const q={cloud:0,local:1,builtin:2};return se.source!==Oe.source?q[se.source]-q[Oe.source]:se.isUser&&!Oe.isUser?-1:!se.isUser&&Oe.isUser?1:se.name.localeCompare(Oe.name)})},[M?.filament,P?.filament,B,g,s,r.savedPresetId,r.trayInfoIdx]),Y=w.useMemo(()=>{if(!c)return null;let te=null;if(c.startsWith("local_")){const oe=parseInt(c.replace("local_",""),10);te=P?.filament.find(se=>se.id===oe)?.name||null}else if(c.startsWith("builtin_")){const oe=c.replace("builtin_","");te=B?.find(se=>se.filament_id===oe)?.name||null}else M?.filament&&(te=M.filament.find(_e=>_e.setting_id===c)?.name||null);if(!te)return null;let je=te.replace(/@.+$/,"").trim();je.startsWith("# ")&&(je=je.slice(2).trim());const ue=G7(je);return{fullName:je,material:ue.material,brand:ue.brand}},[c,M?.filament,P?.filament,B]),ae=Y?.fullName||"",$=w.useMemo(()=>{if(!V||!Y)return[];const{fullName:te,brand:je}=Y,ue=te.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return V.filter(oe=>{const _e=(oe.material||"").toUpperCase(),se=oe.manufacturer.toUpperCase();if(!(_e===ue.toUpperCase()||_e.includes(ue.toUpperCase())||ue.toUpperCase().includes(_e)))return!1;if(je){const q=je.toUpperCase();if(!se.includes(q)&&!q.includes(se))return!1}return!0})},[V,Y]),W=w.useMemo(()=>{if(!U?.profiles||!Y)return[];const{fullName:te,material:je,brand:ue}=Y,oe=te.toUpperCase(),_e=je.toUpperCase(),se=ue.toUpperCase();if(!_e||_e.length<2)return[];const Oe=U.profiles.filter(X=>{const de=X.name.toUpperCase();if(se)return!(!de.includes(se)||!de.includes(_e));if(de.includes(oe)||de.includes(_e))return!0;const ie={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[_e]||[];for(const le of ie)if(de.includes(le))return!0;return!1}),q=new Map;for(const X of Oe){const de=`${X.name}|${X.k_value}`,Z=q.get(de);Z?r.extruderId!==void 0&&X.extruder_id===r.extruderId&&Z.extruder_id!==r.extruderId&&q.set(de,X):q.set(de,X)}return Array.from(q.values())},[U?.profiles,Y,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&M?.filament){let te=M.filament.find(je=>je.setting_id===r.trayInfoIdx);te||(te=M.filament.find(je=>x_(je.setting_id)===r.trayInfoIdx)),te&&u(te.setting_id)}if(r.trayColor){const te=r.trayColor.slice(0,6);te&&p(te)}}else u(""),h(null),p(""),v(""),y(""),N(!1)},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,M?.filament]),w.useEffect(()=>{if(W.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const te=W.find(je=>je.slot_id===r.caliIdx);if(te){h(te);return}}h(W[0])}else h(null)},[c,W,r.caliIdx]);const ee=w.useCallback(te=>{te.key==="Escape"&&e()},[e]);if(w.useEffect(()=>{if(t)return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[t,ee]),!t)return null;const J=C&&!j||E||O||R,ye=c&&!G.isPending,me=f||r.trayColor?.slice(0,6)||"FFFFFF";return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ed,{className:"w-5 h-5 text-bambu-blue"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:l("configureAmsSlot.title")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4 max-h-[60vh] overflow-y-auto",children:[_&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:i.jsxs("div",{className:"text-center space-y-3",children:[i.jsx(ob,{className:"w-16 h-16 text-bambu-green mx-auto"}),i.jsx("p",{className:"text-lg font-semibold text-white",children:l("configureAmsSlot.slotConfigured")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:l("configureAmsSlot.settingsSentToPrinter")})]})}),i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:l("configureAmsSlot.configuringSlot")}),i.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white font-medium",children:l("configureAmsSlot.slotLabel",{ams:LHe(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&i.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),J?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[l("configureAmsSlot.filamentProfile")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:l("configureAmsSlot.searchPresets"),value:g,onChange:te=>y(te.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:K.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:M?.filament?.length===0&&!P?.filament?.length?l("configureAmsSlot.noPresetsAvailable"):l("configureAmsSlot.noMatchingPresets")}):K.map(te=>i.jsx("button",{ref:c===te.id?je=>{je?.scrollIntoView({block:"nearest"})}:void 0,onClick:()=>u(te.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${c===te.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-white text-sm truncate",children:te.name}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[te.source==="local"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:l("profiles.localProfiles.badge")}),te.source==="builtin"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:l("configureAmsSlot.builtin")}),te.isUser&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:l("configureAmsSlot.custom")})]})]})},te.id))})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[l("configureAmsSlot.kProfileLabel"),ae&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:l("configureAmsSlot.filteringFor",{material:ae})})]}),W.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:d?.name||"",onChange:te=>{const je=W.find(ue=>ue.name===te.target.value);h(je||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 appearance-none pr-10",children:[i.jsx("option",{value:"",children:l("configureAmsSlot.noKProfile")}),W.map(te=>i.jsxs("option",{value:te.name,children:[te.name," (K=",te.k_value,")"]},`${te.name}-${te.extruder_id}`))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):c?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:l("configureAmsSlot.noMatchingKProfiles")}):i.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:l("configureAmsSlot.selectFilamentFirst")}),d&&i.jsx("p",{className:"text-xs text-bambu-green mt-1",children:l("configureAmsSlot.kFromCalibration",{value:d.k_value})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:l("configureAmsSlot.customColorLabel")}),$.length>0&&i.jsxs("div",{className:"mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:l("configureAmsSlot.presetColors",{name:Y?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:$.map(te=>i.jsxs("button",{onClick:()=>{const je=te.hex_color.replace("#","").toUpperCase();p(je),v(te.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===te.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:te.color_name,children:[i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/30 flex-shrink-0",style:{backgroundColor:te.hex_color}}),i.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:te.color_name})]},te.id))})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[UHe.map(te=>i.jsx("button",{onClick:()=>{p(te.hex),v(te.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===te.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${te.hex}`},title:te.name},te.hex)),i.jsx("button",{onClick:()=>A(!k),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:l(k?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:k?"−":"+"})]}),k&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:BHe.map(te=>i.jsx("button",{onClick:()=>{p(te.hex),v(te.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===te.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${te.hex}`},title:te.name},te.hex))}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${me}`}}),i.jsx("input",{type:"text",placeholder:l("configureAmsSlot.colorPlaceholder"),value:x,onChange:te=>{const je=te.target.value;v(je);const ue=HHe(je);if(ue)p(ue);else{const oe=je.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();oe.length===6?p(oe):oe.length===3&&p(oe.split("").map(_e=>_e+_e).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&i.jsx("button",{onClick:()=>{p(""),v("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:l("configureAmsSlot.clearCustomColor"),children:l("configureAmsSlot.clear")})]}),f&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:l("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),i.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>z.mutate(),disabled:z.isPending||G.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:z.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("configureAmsSlot.resetting")]}):i.jsxs(i.Fragment,{children:[i.jsx(Fo,{className:"w-4 h-4"}),l("configureAmsSlot.resetSlot")]})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:l("configureAmsSlot.cancel")}),i.jsx(Ce,{onClick:()=>G.mutate(),disabled:!ye,children:G.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("configureAmsSlot.configuring")]}):i.jsxs(i.Fragment,{children:[i.jsx(ed,{className:"w-4 h-4"}),l("configureAmsSlot.configureSlot")]})})]})]}),(G.isError||z.isError)&&i.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:G.error?.message||z.error?.message})]})]})}function W7(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function ja(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function Rc(t,e,n=40){const r=ja(t),a=ja(e);if(!r||!a||r.length<6||a.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(a.substring(0,2),16),u=parseInt(a.substring(2,4),16),d=parseInt(a.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function cI(t,e,n,r){if(r)return"External";const a=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${a}`:`AMS-${a} Slot ${e+1}`}function uI(t,e,n){return n?254+e:t>=128?t:t*4+e}function K7(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}const X7={"A00-W1":"Jade White","A00-P0":"Beige","A00-D2":"Light Gray","A00-Y0":"Yellow","A00-Y2":"Sunflower Yellow","A00-A1":"Pumpkin Orange","A00-A0":"Orange","A00-Y4":"Gold","A00-G3":"Bright Green","A00-G1":"Bambu Green","A00-G2":"Mistletoe Green","A00-R3":"Hot Pink","A00-P6":"Magenta","A00-R0":"Red","A00-R2":"Maroon Red","A00-P5":"Purple","A00-P2":"Indigo Purple","A00-B5":"Turquoise","A00-B8":"Cyan","A00-B3":"Cobalt Blue","A00-N0":"Brown","A00-N1":"Cocoa Brown","A00-Y3":"Bronze","A00-D0":"Gray","A00-D1":"Silver","A00-B1":"Blue Grey","A00-D3":"Dark Gray","A00-K0":"Black","A00-M3":"Pink Citrus","A00-M6":"Dusk Glare","A00-M0":"Arctic Whisper","A00-M1":"Solar Breeze","A00-M5":"Blueberry Bubblegum","A00-M4":"Mint Lime","A00-M2":"Ocean to Meadow","A00-M7":"Cotton Candy Cloud","A18-K0":"Black","A18-D0":"Gray","A18-W0":"White","A18-R0":"Red","A18-Y0":"Yellow","A18-B0":"Cyan","A18-B1":"Blue","A18-P0":"Matte Beige","A01-W2":"Ivory White","A01-W3":"Bone White","A01-Y2":"Lemon Yellow","A01-A2":"Mandarin Orange","A01-P3":"Sakura Pink","A01-P4":"Lilac Purple","A01-R3":"Plum","A01-R1":"Scarlet Red","A01-R4":"Dark Red","A01-G0":"Apple Green","A01-G1":"Grass Green","A01-G7":"Dark Green","A01-B4":"Ice Blue","A01-B0":"Sky Blue","A01-B3":"Marine Blue","A01-B6":"Dark Blue","A01-Y3":"Desert Tan","A01-N1":"Latte Brown","A01-N3":"Caramel","A01-R2":"Terracotta","A01-N2":"Dark Brown","A01-N0":"Dark Chocolate","A01-D3":"Ash Gray","A01-D0":"Nardo Gray","A01-K1":"Charcoal","A12-G0":"Green","A12-R0":"Pink","A12-A0":"Orange","A12-Y0":"Yellow","A12-B0":"Blue","A07-R5":"Red Granite","A07-D4":"White Marble","A11-W0":"White","A11-K0":"Black","A08-G3":"Alpine Green Sparkle","A08-D5":"Slate Gray Sparkle","A08-B7":"Royal Purple Sparkle","A08-R2":"Crimson Red Sparkle","A08-K2":"Onyx Black Sparkle","A08-Y1":"Classic Gold Sparkle","A02-B2":"Cobalt Blue Metallic","A02-G2":"Oxide Green Metallic","A02-Y1":"Iridium Gold Metallic","A02-D2":"Iron Gray Metallic","A17-B1":"Blue","A17-A0":"Orange","A17-P0":"Purple","A06-Y1":"Gold","A06-D0":"Titan Gray","A06-D1":"Silver","A06-W0":"White","A06-R0":"Candy Red","A06-G0":"Candy Green","A06-G1":"Mint","A06-B1":"Blue","A06-B0":"Baby Blue","A06-P0":"Purple","A06-R1":"Rose Gold","A06-R2":"Pink","A06-Y0":"Champagne","A05-M8":"Dawn Radiance","A05-M4":"Aurora Purple","A05-M1":"South Beach","A05-T3":"Neon City","A05-T2":"Midnight Blaze","A05-T1":"Gilded Rose","A05-T4":"Blue Hawaii","A05-T5":"Velvet Eclipse","A15-B0":"Purple","A15-G0":"Green","A15-G1":"Nebulae","A15-R0":"Brown","A16-K0":"Black Walnut","A16-R0":"Rosewood","A16-N0":"Clay Brown","A16-G0":"Classic Birch","A16-W0":"White Oak","A16-Y0":"Ochre Yellow","A50-D6":"Lava Gray","A50-K0":"Black","A50-B6":"Royal Blue","A10-W0":"White","A10-D0":"Gray","A09-B5":"Lavender Blue","A09-B4":"Light Blue","A09-A0":"Orange","A09-D1":"Silver","A09-R3":"Vermilion Red","A09-Y0":"Yellow","G02-K0":"Black","G02-W0":"White","G02-R0":"Red","G02-D0":"Gray","G02-D1":"Dark Gray","G02-Y1":"Cream","G02-Y0":"Yellow","G02-A0":"Orange","G02-N1":"Peanut Brown","G02-G1":"Lime Green","G02-G0":"Green","G02-G2":"Forest Green","G02-B1":"Lake Blue","G02-B0":"Blue","G01-G1":"Translucent Teal","G01-B0":"Translucent Light Blue","G01-C0":"Clear","G01-D0":"Translucent Gray","G01-G0":"Translucent Olive","G01-N0":"Translucent Brown","G01-A0":"Translucent Orange","G01-P1":"Translucent Pink","G01-P0":"Translucent Purple","G50-P7":"Violet Purple","G50-K0":"Black","B00-D1":"Silver","B00-K0":"Black","B00-W0":"White","B00-G6":"Bambu Green","B00-G7":"Olive","B00-Y1":"Tangerine Yellow","B00-A0":"Orange","B00-R0":"Red","B00-B4":"Azure","B00-B0":"Blue","B00-B6":"Navy Blue","B50-A0":"Orange","B50-K0":"Black","B01-W0":"White","B01-K0":"Black","B01-D0":"Gray","B02-W0":"White","C00-C1":"Transparent","C00-C0":"Clear Black","C00-K0":"Black","C00-W0":"White","C01-K0":"Black","U02-B0":"Blue","U02-D0":"Gray","U02-K0":"Black","N04-K0":"Black","N08-K0":"Black","S02-W0":"Nature","S02-W1":"White","S05-C0":"Black","S06-W0":"White","S03-G1":"Green","S04-Y0":"Clear"},qHe={W0:"White",W1:"Jade White",W2:"Ivory White",W3:"Bone White",Y0:"Yellow",Y1:"Gold",Y2:"Sunflower Yellow",Y3:"Bronze",Y4:"Gold",A0:"Orange",A1:"Pumpkin Orange",A2:"Mandarin Orange",R0:"Red",R1:"Scarlet Red",R2:"Maroon Red",R3:"Hot Pink",R4:"Dark Red",R5:"Red Granite",P0:"Beige",P1:"Pink",P2:"Indigo Purple",P3:"Sakura Pink",P4:"Lilac Purple",P5:"Purple",P6:"Magenta",P7:"Violet Purple",B0:"Blue",B1:"Blue Grey",B2:"Cobalt Blue",B3:"Cobalt Blue",B4:"Ice Blue",B5:"Turquoise",B6:"Navy Blue",B7:"Royal Purple",B8:"Cyan",G0:"Green",G1:"Grass Green",G2:"Mistletoe Green",G3:"Bright Green",G6:"Bambu Green",G7:"Dark Green",N0:"Brown",N1:"Peanut Brown",N2:"Dark Brown",N3:"Caramel",D0:"Gray",D1:"Silver",D2:"Light Gray",D3:"Dark Gray",D4:"White Marble",D5:"Slate Gray",D6:"Lava Gray",K0:"Black",K1:"Charcoal",K2:"Onyx Black",C0:"Clear Black",C1:"Transparent",M0:"Arctic Whisper",M1:"Solar Breeze",M2:"Ocean to Meadow",M3:"Pink Citrus",M4:"Aurora Purple",M5:"Blueberry Bubblegum",M6:"Dusk Glare",M7:"Cotton Candy Cloud",M8:"Dawn Radiance",T1:"Gilded Rose",T2:"Midnight Blaze",T3:"Neon City",T4:"Blue Hawaii",T5:"Velvet Eclipse"};function I2(t){if(!t)return null;if(X7[t])return X7[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return qHe[n]||null}function z2(t){if(!t||t.length<6)return"Unknown";const e=parseInt(t.substring(0,2),16),n=parseInt(t.substring(2,4),16),r=parseInt(t.substring(4,6),16),a=Math.max(e,n,r)/255,s=Math.min(e,n,r)/255,o=(a+s)/2;let l=0,c=0;if(a!==s){const u=a-s;c=o>.5?u/(2-a-s):u/(a+s);const d=e/255,h=n/255,f=r/255;a===d?l=((h-f)/u+(h.85?"White":c<.15?o<.4?"Dark Gray":o>.6?"Light Gray":"Gray":l>=15&&l<45&&o<.45||l>=45&&l<70&&o<.4?"Brown":l<15||l>=345?"Red":l<45?"Orange":l<70?"Yellow":l<150?"Green":l<200?"Cyan":l<260?"Blue":l<290?"Purple":"Pink"}function U2(t){return(t??.02).toFixed(3)}function Y7({side:t}){const{mode:e}=Jf(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return i.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded",style:{backgroundColor:n,color:"#00ae42"},children:t})}function dI(t){if(!t||t==="00000000"||t.length<6)return null;const e=t.slice(0,2),n=t.slice(2,4),r=t.slice(4,6),a=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return a===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${a})`}function GHe(t){if(!t||t.length<6)return!1;const e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);return(.299*e+.587*n+.114*r)/255>.6}function rne(t,e){if(!t)return"";if(t.includes("hardened"))return e("printers.nozzleHardenedSteel");if(t.includes("stainless"))return e("printers.nozzleStainlessSteel");if(t.includes("tungsten"))return e("printers.nozzleTungstenCarbide");if(t.length>=4){const n=t.slice(2,4);if(n==="00")return e("printers.nozzleStainlessSteel");if(n==="01")return e("printers.nozzleHardenedSteel");if(n==="05")return e("printers.nozzleTungstenCarbide")}return t==="00"?e("printers.nozzleStainlessSteel"):t==="01"?e("printers.nozzleHardenedSteel"):t==="05"?e("printers.nozzleTungstenCarbide"):t.startsWith("H")?e("printers.nozzleHardenedSteel"):t}function ane(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function ine({slot:t,index:e,activeStatus:n,filamentName:r,children:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),h=w.useRef(null),f=w.useRef(null),p=!t.nozzle_diameter&&!t.nozzle_type,x=t.stat===1;w.useEffect(()=>{if(o&&d.current&&h.current){const k=d.current.getBoundingClientRect(),A=h.current.offsetHeight,C=k.top-56,j=window.innerHeight-k.bottom;CC?u("bottom"):u("top")}},[o]);const v=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!0),80)},g=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const y=dI(t.filament_color),_=rne(t.nozzle_type,s),N=ane(t.nozzle_type,s);return i.jsxs("div",{ref:d,className:"relative",onMouseEnter:v,onMouseLeave:g,children:[a,o&&i.jsxs("div",{ref:h,className:` + `})]})]})}function RHe({isOpen:t,onClose:e,tagUid:n,trayUuid:r,printerId:a,amsId:s,trayId:o}){const{t:l}=Ut(),c=tn(),{showToast:u}=cn(),[d,h]=w.useState(""),{data:f,isLoading:p}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!1),enabled:t}),x=w.useMemo(()=>f?f.filter(g=>{if(g.tag_uid||g.tray_uuid)return!1;if(!d)return!0;const y=d.toLowerCase();return g.material.toLowerCase().includes(y)||g.brand&&g.brand.toLowerCase().includes(y)||g.color_name&&g.color_name.toLowerCase().includes(y)}):[],[f,d]),v=ot({mutationFn:g=>ne.linkTagToSpool(g,{tag_uid:n||void 0,tray_uuid:r||void 0,tag_type:r?"bambulab":"generic",data_origin:"nfc_link"}),onSuccess:()=>{c.invalidateQueries({queryKey:["inventory-spools"]}),c.invalidateQueries({queryKey:["inventory-assignments"]}),u(l("inventory.tagLinked"),"success"),e()},onError:g=>{u(g.message||l("inventory.tagLinkFailed"),"error")}});return t?i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative bg-bambu-dark-secondary rounded-xl shadow-xl w-full max-w-md mx-4 max-h-[80vh] flex flex-col border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/10",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Bb,{className:"w-5 h-5 text-bambu-green"}),l("inventory.linkToSpool")]}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["AMS ",s," T",o," · Printer #",a]})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 border-b border-white/10",children:[i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:d,onChange:g=>h(g.target.value),placeholder:l("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark rounded-lg border border-white/10 text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),(n||r)&&i.jsxs("p",{className:"text-xs text-bambu-gray mt-2 font-mono truncate",title:n||r,children:["Tag: ",n||r]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-2 min-h-0",children:p?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):x.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8 text-sm",children:l("inventory.noSpoolsMatch")}):x.map(g=>i.jsxs("button",{onClick:()=>v.mutate(g.id),disabled:v.isPending,className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-white/5 transition-colors text-left",children:[i.jsx("span",{className:"w-6 h-6 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:g.rgba?`#${g.rgba.substring(0,6)}`:"#808080"}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"text-sm text-white font-medium truncate",children:[g.brand?`${g.brand} `:"",g.material,g.subtype?` ${g.subtype}`:""]}),i.jsxs("div",{className:"text-xs text-bambu-gray truncate",children:[g.color_name||"No color"," · #",g.id]})]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(g.label_weight-g.weight_used),"g"]})]},g.id))}),i.jsx("div",{className:"p-4 border-t border-white/10 flex justify-end",children:i.jsx(Ce,{variant:"ghost",onClick:e,children:l("inventory.cancel")||"Cancel"})})]})]}):null}function FHe({isOpen:t,onClose:e,printerId:n,amsId:r,trayId:a,trayInfo:s}){const{t:o}=Ut(),l=tn(),{showToast:c}=cn(),[u,d]=w.useState(null),[h,f]=w.useState(""),{data:p,isLoading:x}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(),enabled:t}),{data:v}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),enabled:t}),g=ot({mutationFn:M=>ne.assignSpool({spool_id:M,printer_id:n,ams_id:r,tray_id:a}),onSuccess:M=>{l.setQueryData(["spool-assignments"],C=>{const j=(C||[]).filter(P=>!(P.printer_id===n&&P.ams_id===r&&P.tray_id===a));return j.push(M),j}),l.invalidateQueries({queryKey:["spool-assignments"]}),c(o("inventory.assignSuccess"),"success"),e()},onError:M=>{c(`${o("inventory.assignFailed")}: ${M.message}`,"error")}});if(!t)return null;const y=new Set((v||[]).filter(M=>!(M.printer_id===n&&M.ams_id===r&&M.tray_id===a)).map(M=>M.spool_id)),_=r===254||r===255,N=p?.filter(M=>!y.has(M.id)&&(_||!M.tag_uid&&!M.tray_uuid)),k=N?.filter(M=>{if(!h)return!0;const C=h.toLowerCase();return M.material.toLowerCase().includes(C)||(M.brand?.toLowerCase().includes(C)??!1)||(M.color_name?.toLowerCase().includes(C)??!1)||(M.subtype?.toLowerCase().includes(C)??!1)}),A=()=>{u&&g.mutate(u)};return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-md mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fi,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("inventory.assignSpool")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[s&&i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-1",children:[o("inventory.selectSpool"),":"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[s.color&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${s.color}`}}),i.jsx("span",{className:"text-white font-medium",children:s.type||o("ams.emptySlot")}),i.jsxs("span",{className:"text-bambu-gray",children:["(",s.location,")"]})]})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:h,onChange:M=>f(M.target.value),placeholder:o("inventory.searchSpools"),className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsx("div",{children:x?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):k&&k.length>0?i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-2",children:k.map(M=>i.jsx("button",{onClick:()=>d(M.id),className:`w-full p-3 rounded-lg border text-left transition-colors ${u===M.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center gap-2",children:[M.rgba&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:`#${M.rgba.substring(0,6)}`}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("p",{className:"text-white font-medium truncate",children:[M.brand?`${M.brand} `:"",M.material,M.subtype?` ${M.subtype}`:""]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[M.color_name||"",M.label_weight?` - ${M.label_weight}g`:"",M.label_weight?` (${Math.max(0,Math.round(M.label_weight-M.weight_used))}g ${o("ams.remainingUnit")})`:""]})]}),u===M.id&&i.jsx(ra,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]})},M.id))}):N&&N.length===0?i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noManualSpools")})}):i.jsx("div",{className:"text-center py-8 text-bambu-gray",children:i.jsx("p",{children:o("inventory.noSpoolsMatch")})})})]}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:o("common.cancel")}),i.jsx(Ce,{onClick:A,disabled:!u||g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),o("inventory.assigning")]}):i.jsxs(i.Fragment,{children:[i.jsx(fi,{className:"w-4 h-4"}),o("inventory.assignSpool")]})})]}),g.isError&&i.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:g.error.message})]})]})}function LHe(t,e){if(t===255)return"External";let n,r=!1;t>=128&&t<=135?(n=t-128,r=!0):t>=0&&t<=3?(n=t,r=e===1):n=0,n=Math.max(0,Math.min(n,7));const a=String.fromCharCode(65+n);return r?`HT-${a}`:`AMS-${a}`}function x_(t){const e=t.includes("_")?t.split("_")[0]:t;return e.startsWith("GFS")?"GF"+e.slice(3):(e.startsWith("PFUS")||e.startsWith("PFSP"),e)}const OHe=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","NYLON","PVA","HIPS","PP","PET"];function G7(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const a of OHe){const s=new RegExp(`\\b${a}\\b`,"i");if(s.test(n)){const o=e.split(s),l=o[0]?.trim()||"",c=o[1]?.trim()||"";return{material:a,brand:l,variant:c}}}const r=e.split(/\s+/);return r.length>=2?{material:r[1],brand:r[0],variant:r.slice(2).join(" ")}:{material:e,brand:"",variant:""}}function IHe(t){return!t.startsWith("GF")&&!t.startsWith("P1")}const zHe={white:"FFFFFF",black:"000000",red:"FF0000",green:"00FF00",blue:"0000FF",yellow:"FFFF00",cyan:"00FFFF",magenta:"FF00FF",orange:"FFA500",purple:"800080",pink:"FFC0CB",brown:"8B4513",gray:"808080",grey:"808080","jade white":"FFFEF2",ivory:"FFFFF0",beige:"F5F5DC",cream:"FFFDD0",silver:"C0C0C0",gold:"FFD700",bronze:"CD7F32",copper:"B87333",navy:"000080",teal:"008080",olive:"808000",maroon:"800000",coral:"FF7F50",salmon:"FA8072",lime:"32CD32",mint:"98FF98","forest green":"228B22","sky blue":"87CEEB","royal blue":"4169E1",turquoise:"40E0D0",lavender:"E6E6FA",violet:"EE82EE",plum:"DDA0DD",tan:"D2B48C",chocolate:"D2691E",charcoal:"36454F",slate:"708090",transparent:"000000",natural:"F5F5DC",wood:"DEB887"},UHe=[{name:"White",hex:"FFFFFF"},{name:"Black",hex:"000000"},{name:"Red",hex:"FF0000"},{name:"Blue",hex:"0000FF"},{name:"Green",hex:"00AA00"},{name:"Yellow",hex:"FFFF00"},{name:"Orange",hex:"FFA500"},{name:"Gray",hex:"808080"}],BHe=[{name:"Cyan",hex:"00FFFF"},{name:"Magenta",hex:"FF00FF"},{name:"Purple",hex:"800080"},{name:"Pink",hex:"FFC0CB"},{name:"Brown",hex:"8B4513"},{name:"Beige",hex:"F5F5DC"},{name:"Navy",hex:"000080"},{name:"Teal",hex:"008080"},{name:"Lime",hex:"32CD32"},{name:"Gold",hex:"FFD700"},{name:"Silver",hex:"C0C0C0"},{name:"Maroon",hex:"800000"},{name:"Olive",hex:"808000"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Indigo",hex:"4B0082"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Slate",hex:"708090"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Cream",hex:"FFFDD0"}];function HHe(t){const e=t.toLowerCase().trim();return zHe[e]||null}function $He(t){const e=t.indexOf("@");if(e<0)return null;const r=t.slice(e+1).trim().match(/^BBL\s+(.+?)(?:\s+[\d.]+\s*nozzle)?$/i);return r?r[1].trim():null}function VHe({isOpen:t,onClose:e,printerId:n,slotInfo:r,nozzleDiameter:a="0.4",printerModel:s,onSuccess:o}){const{t:l}=Ut(),[c,u]=w.useState(""),[d,h]=w.useState(null),[f,p]=w.useState(""),[x,v]=w.useState(""),[g,y]=w.useState(""),[_,N]=w.useState(!1),[k,A]=w.useState(!1),{data:M,isLoading:C,isError:j}=Je({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:t,retry:!1}),{data:P,isLoading:E}=Je({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets(),enabled:t}),{data:B,isLoading:O}=Je({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),enabled:t,staleTime:1/0}),{data:U,isLoading:R}=Je({queryKey:["kprofiles",n,a],queryFn:()=>ne.getKProfiles(n,a),enabled:t&&!!n}),{data:V}=Je({queryKey:["colorCatalog"],queryFn:()=>ne.getColorCatalog(),enabled:t,staleTime:1/0}),G=ot({mutationFn:async()=>{if(!c)throw new Error("No filament preset selected");const te=c.startsWith("local_"),je=c.startsWith("builtin_"),ue=te?parseInt(c.replace("local_",""),10):null,oe=je?c.replace("builtin_",""):null,_e=te?P?.filament.find(fe=>fe.id===ue):null,se=je?B?.find(fe=>fe.filament_id===oe):null,Oe=!te&&!je?M?.filament.find(fe=>fe.setting_id===c):null;if(!te&&!je&&!Oe)throw new Error("Selected preset not found");if(te&&!_e)throw new Error("Selected local preset not found");if(je&&!se)throw new Error("Selected builtin preset not found");const q=te?_e.name:je?se.name:Oe.name,X=G7(q),de=d?.slot_id??-1,Z=f||r.trayColor?.slice(0,6)||"FFFFFF",ie=q.replace(/@.+$/,"").trim();let le,Fe;if(te){const fe=(_e?.filament_type||X.material||"").toUpperCase(),ze={PLA:"GFL99","PLA-CF":"GFL98","PLA SILK":"GFL96","PLA HIGH SPEED":"GFL95",PETG:"GFG99","PETG HF":"GFG96","PETG-CF":"GFG98",PCTG:"GFG97",ABS:"GFB99",ASA:"GFB98",PC:"GFC99",PA:"GFN99","PA-CF":"GFN98",NYLON:"GFN99",TPU:"GFU99",PVA:"GFS99",HIPS:"GFS98",PE:"GFP99",PP:"GFP97"};le=ze[fe]||ze[fe.replace(/[-\s]?CF$/,"")]||ze[fe.replace(/\+$/,"")]||ze[fe.split(/[-\s]/)[0]]||"",Fe=""}else if(je)le=oe,Fe="";else if(le=x_(c),Fe=c,!c.startsWith("GFS"))try{const fe=await ne.getCloudSettingDetail(c);fe.filament_id?le=fe.filament_id:fe.base_id&&(le=x_(fe.base_id),console.log(`Derived tray_info_idx from base_id: ${fe.base_id} -> ${le}`))}catch(fe){console.warn("Failed to fetch preset detail for filament_id:",fe)}let pe=te&&_e?.nozzle_temp_min?_e.nozzle_temp_min:190,Q=te&&_e?.nozzle_temp_max?_e.nozzle_temp_max:230;if(!te||je||!_e?.nozzle_temp_min&&!_e?.nozzle_temp_max){const fe=(te&&_e?.filament_type||X.material).toUpperCase();fe.includes("PLA")?(pe=190,Q=230):fe.includes("PETG")?(pe=220,Q=260):fe.includes("ABS")||fe.includes("ASA")?(pe=240,Q=280):fe.includes("TPU")?(pe=200,Q=240):fe==="PCTG"?(pe=220,Q=260):fe.includes("PC")?(pe=260,Q=300):(fe.includes("PA")||fe.includes("NYLON"))&&(pe=250,Q=290)}const L=d?.k_value?parseFloat(d.k_value):0,D=te?_e?.filament_type||X.material||"PLA":X.material||"PLA",H=await ne.configureAmsSlot(n,r.amsId,r.trayId,{tray_info_idx:le,tray_type:D,tray_sub_brands:ie,tray_color:Z+"FF",nozzle_temp_min:pe,nozzle_temp_max:Q,cali_idx:de,nozzle_diameter:a,setting_id:Fe,kprofile_filament_id:d?.filament_id,kprofile_setting_id:d?.setting_id||void 0,k_value:L}),he=te?`local_${ue}`:je?`builtin_${oe}`:c,be=te?"local":je?"builtin":"cloud";try{await ne.saveSlotPreset(n,r.amsId,r.trayId,he,ie,be)}catch(fe){console.warn("Failed to save slot preset mapping:",fe)}return H},onSuccess:()=>{N(!0),o?.(),setTimeout(()=>{N(!1),e()},1500)}}),z=ot({mutationFn:async()=>ne.resetAmsSlot(n,r.amsId,r.trayId),onSuccess:()=>{N(!0),o?.(),setTimeout(()=>{N(!1),e()},1500)}}),K=w.useMemo(()=>{const te=g.toLowerCase(),je=[],ue=new Set,oe=r.savedPresetId,_e=r.trayInfoIdx;if(M?.filament)for(const se of M.filament){ue.add(se.setting_id);const Oe=oe===se.setting_id||_e&&(se.setting_id===_e||x_(se.setting_id)===_e);if(!(!Oe&&te&&!se.name.toLowerCase().includes(te))){if(!Oe&&s){const q=$He(se.name);if(q&&q.toUpperCase()!==s.toUpperCase())continue}je.push({id:se.setting_id,name:se.name,source:"cloud",isUser:IHe(se.setting_id)})}}if(P?.filament)for(const se of P.filament){const Oe=`local_${se.id}`,q=oe===Oe;if(!(!q&&te&&!se.name.toLowerCase().includes(te))){if(!q&&s&&se.compatible_printers){const X=se.compatible_printers.split(";").map(de=>{const Z=de.trim(),ie=Z.match(/^BBL\s+(.+)/i);return ie?ie[1].trim().toUpperCase():Z.toUpperCase()}).filter(Boolean);if(X.length>0&&!X.includes(s.toUpperCase()))continue}je.push({id:Oe,name:se.name,source:"local",isUser:!1})}}if(B)for(const se of B){if(ue.has(se.filament_id))continue;const Oe=se.filament_id.startsWith("GF")?"GFS"+se.filament_id.slice(2):se.filament_id;ue.has(Oe)||(!te||se.name.toLowerCase().includes(te))&&je.push({id:`builtin_${se.filament_id}`,name:se.name,source:"builtin",isUser:!1})}return je.sort((se,Oe)=>{const q={cloud:0,local:1,builtin:2};return se.source!==Oe.source?q[se.source]-q[Oe.source]:se.isUser&&!Oe.isUser?-1:!se.isUser&&Oe.isUser?1:se.name.localeCompare(Oe.name)})},[M?.filament,P?.filament,B,g,s,r.savedPresetId,r.trayInfoIdx]),Y=w.useMemo(()=>{if(!c)return null;let te=null;if(c.startsWith("local_")){const oe=parseInt(c.replace("local_",""),10);te=P?.filament.find(se=>se.id===oe)?.name||null}else if(c.startsWith("builtin_")){const oe=c.replace("builtin_","");te=B?.find(se=>se.filament_id===oe)?.name||null}else M?.filament&&(te=M.filament.find(_e=>_e.setting_id===c)?.name||null);if(!te)return null;let je=te.replace(/@.+$/,"").trim();je.startsWith("# ")&&(je=je.slice(2).trim());const ue=G7(je);return{fullName:je,material:ue.material,brand:ue.brand}},[c,M?.filament,P?.filament,B]),ae=Y?.fullName||"",$=w.useMemo(()=>{if(!V||!Y)return[];const{fullName:te,brand:je}=Y,ue=te.replace(/^(Bambu\s*(Lab)?|eSUN|Polymaker|Overture|Sunlu|Hatchbox)\s*/i,"").trim();return V.filter(oe=>{const _e=(oe.material||"").toUpperCase(),se=oe.manufacturer.toUpperCase();if(!(_e===ue.toUpperCase()||_e.includes(ue.toUpperCase())||ue.toUpperCase().includes(_e)))return!1;if(je){const q=je.toUpperCase();if(!se.includes(q)&&!q.includes(se))return!1}return!0})},[V,Y]),W=w.useMemo(()=>{if(!U?.profiles||!Y)return[];const{fullName:te,material:je,brand:ue}=Y,oe=te.toUpperCase(),_e=je.toUpperCase(),se=ue.toUpperCase();if(!_e||_e.length<2)return[];const Oe=U.profiles.filter(X=>{const de=X.name.toUpperCase();if(se)return!(!de.includes(se)||!de.includes(_e));if(de.includes(oe)||de.includes(_e))return!0;const ie={NYLON:["PA","PA-CF","PA6"],PA:["NYLON"]}[_e]||[];for(const le of ie)if(de.includes(le))return!0;return!1}),q=new Map;for(const X of Oe){const de=`${X.name}|${X.k_value}`,Z=q.get(de);Z?r.extruderId!==void 0&&X.extruder_id===r.extruderId&&Z.extruder_id!==r.extruderId&&q.set(de,X):q.set(de,X)}return Array.from(q.values())},[U?.profiles,Y,r.extruderId]);w.useEffect(()=>{if(t){if(r.savedPresetId)u(r.savedPresetId);else if(r.trayInfoIdx&&M?.filament){let te=M.filament.find(je=>je.setting_id===r.trayInfoIdx);te||(te=M.filament.find(je=>x_(je.setting_id)===r.trayInfoIdx)),te&&u(te.setting_id)}if(r.trayColor){const te=r.trayColor.slice(0,6);te&&p(te)}}else u(""),h(null),p(""),v(""),y(""),N(!1)},[t,r.savedPresetId,r.trayInfoIdx,r.trayColor,M?.filament]),w.useEffect(()=>{if(W.length>0){if(r.caliIdx!=null&&r.caliIdx>0){const te=W.find(je=>je.slot_id===r.caliIdx);if(te){h(te);return}}h(W[0])}else h(null)},[c,W,r.caliIdx]);const ee=w.useCallback(te=>{te.key==="Escape"&&e()},[e]);if(w.useEffect(()=>{if(t)return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[t,ee]),!t)return null;const J=C&&!j||E||O||R,ye=c&&!G.isPending,me=f||r.trayColor?.slice(0,6)||"FFFFFF";return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ed,{className:"w-5 h-5 text-bambu-blue"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:l("configureAmsSlot.title")})]}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4 max-h-[60vh] overflow-y-auto",children:[_&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-secondary/95 z-10 flex items-center justify-center rounded-xl",children:i.jsxs("div",{className:"text-center space-y-3",children:[i.jsx(ob,{className:"w-16 h-16 text-bambu-green mx-auto"}),i.jsx("p",{className:"text-lg font-semibold text-white",children:l("configureAmsSlot.slotConfigured")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:l("configureAmsSlot.settingsSentToPrinter")})]})}),i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:l("configureAmsSlot.configuringSlot")}),i.jsxs("div",{className:"flex items-center gap-2",children:[r.trayColor&&i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/20",style:{backgroundColor:`#${r.trayColor.slice(0,6)}`}}),i.jsx("span",{className:"text-white font-medium",children:l("configureAmsSlot.slotLabel",{ams:LHe(r.amsId,r.trayCount),slot:r.trayId+1})}),r.traySubBrands&&i.jsxs("span",{className:"text-bambu-gray",children:["(",r.traySubBrands,")"]})]})]}),J?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[l("configureAmsSlot.filamentProfile")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:l("configureAmsSlot.searchPresets"),value:g,onChange:te=>y(te.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none mb-2"}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:K.length===0?i.jsx("p",{className:"text-center py-4 text-bambu-gray",children:M?.filament?.length===0&&!P?.filament?.length?l("configureAmsSlot.noPresetsAvailable"):l("configureAmsSlot.noMatchingPresets")}):K.map(te=>i.jsx("button",{ref:c===te.id?je=>{je?.scrollIntoView({block:"nearest"})}:void 0,onClick:()=>u(te.id),className:`w-full p-2 rounded-lg border text-left transition-colors ${c===te.id?"bg-bambu-green/20 border-bambu-green":"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-white text-sm truncate",children:te.name}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[te.source==="local"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-green-500/20 text-green-400",children:l("profiles.localProfiles.badge")}),te.source==="builtin"&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-amber-500/20 text-amber-400",children:l("configureAmsSlot.builtin")}),te.isUser&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-blue/20 text-bambu-blue",children:l("configureAmsSlot.custom")})]})]})},te.id))})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-2",children:[l("configureAmsSlot.kProfileLabel"),ae&&i.jsx("span",{className:"ml-2 text-xs text-bambu-blue",children:l("configureAmsSlot.filteringFor",{material:ae})})]}),W.length>0?i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:d?.name||"",onChange:te=>{const je=W.find(ue=>ue.name===te.target.value);h(je||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 appearance-none pr-10",children:[i.jsx("option",{value:"",children:l("configureAmsSlot.noKProfile")}),W.map(te=>i.jsxs("option",{value:te.name,children:[te.name," (K=",te.k_value,")"]},`${te.name}-${te.extruder_id}`))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}):c?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:l("configureAmsSlot.noMatchingKProfiles")}):i.jsx("span",{className:"inline-block text-xs px-2 py-1 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30",children:l("configureAmsSlot.selectFilamentFirst")}),d&&i.jsx("p",{className:"text-xs text-bambu-green mt-1",children:l("configureAmsSlot.kFromCalibration",{value:d.k_value})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:l("configureAmsSlot.customColorLabel")}),$.length>0&&i.jsxs("div",{className:"mb-3",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1.5",children:l("configureAmsSlot.presetColors",{name:Y?.fullName})}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:$.map(te=>i.jsxs("button",{onClick:()=>{const je=te.hex_color.replace("#","").toUpperCase();p(je),v(te.color_name)},className:`h-7 px-2 rounded-md border-2 transition-all flex items-center gap-1.5 ${f===te.hex_color.replace("#","").toUpperCase()?"border-bambu-green scale-105":"border-white/20 hover:border-white/40"}`,title:te.color_name,children:[i.jsx("span",{className:"w-4 h-4 rounded-full border border-white/30 flex-shrink-0",style:{backgroundColor:te.hex_color}}),i.jsx("span",{className:"text-xs text-white/80 whitespace-nowrap",children:te.color_name})]},te.id))})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-2",children:[UHe.map(te=>i.jsx("button",{onClick:()=>{p(te.hex),v(te.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===te.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${te.hex}`},title:te.name},te.hex)),i.jsx("button",{onClick:()=>A(!k),className:"w-7 h-7 rounded-md border-2 border-white/20 hover:border-white/40 flex items-center justify-center text-white/60 hover:text-white/80 transition-all text-xs",title:l(k?"configureAmsSlot.showLessColors":"configureAmsSlot.showMoreColors"),children:k?"−":"+"})]}),k&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:BHe.map(te=>i.jsx("button",{onClick:()=>{p(te.hex),v(te.name)},className:`w-7 h-7 rounded-md border-2 transition-all ${f===te.hex?"border-bambu-green scale-110":"border-white/20 hover:border-white/40"}`,style:{backgroundColor:`#${te.hex}`},title:te.name},te.hex))}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"w-10 h-10 rounded-lg border-2 border-white/20 flex-shrink-0",style:{backgroundColor:`#${me}`}}),i.jsx("input",{type:"text",placeholder:l("configureAmsSlot.colorPlaceholder"),value:x,onChange:te=>{const je=te.target.value;v(je);const ue=HHe(je);if(ue)p(ue);else{const oe=je.replace(/[^0-9A-Fa-f]/g,"").toUpperCase();oe.length===6?p(oe):oe.length===3&&p(oe.split("").map(_e=>_e+_e).join(""))}},className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder:text-bambu-gray focus:border-bambu-green focus:outline-none text-sm"}),f&&i.jsx("button",{onClick:()=>{p(""),v("")},className:"px-2 py-1 text-xs text-bambu-gray hover:text-white bg-bambu-dark-tertiary rounded",title:l("configureAmsSlot.clearCustomColor"),children:l("configureAmsSlot.clear")})]}),f&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5",children:l("configureAmsSlot.hexLabel",{hex:f})})]})]})]}),i.jsxs("div",{className:"flex justify-between p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>z.mutate(),disabled:z.isPending||G.isPending,className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:z.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("configureAmsSlot.resetting")]}):i.jsxs(i.Fragment,{children:[i.jsx(Fo,{className:"w-4 h-4"}),l("configureAmsSlot.resetSlot")]})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:l("configureAmsSlot.cancel")}),i.jsx(Ce,{onClick:()=>G.mutate(),disabled:!ye,children:G.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("configureAmsSlot.configuring")]}):i.jsxs(i.Fragment,{children:[i.jsx(ed,{className:"w-4 h-4"}),l("configureAmsSlot.configureSlot")]})})]})]}),(G.isError||z.isError)&&i.jsx("div",{className:"mx-4 mb-4 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:G.error?.message||z.error?.message})]})]})}function W7(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function ja(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function Rc(t,e,n=40){const r=ja(t),a=ja(e);if(!r||!a||r.length<6||a.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(a.substring(0,2),16),u=parseInt(a.substring(2,4),16),d=parseInt(a.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function cI(t,e,n,r){if(r)return"External";const a=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${a}`:`AMS-${a} Slot ${e+1}`}function uI(t,e,n){return n?254+e:t>=128?t:t*4+e}function K7(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}const X7={"A00-W1":"Jade White","A00-P0":"Beige","A00-D2":"Light Gray","A00-Y0":"Yellow","A00-Y2":"Sunflower Yellow","A00-A1":"Pumpkin Orange","A00-A0":"Orange","A00-Y4":"Gold","A00-G3":"Bright Green","A00-G1":"Bambu Green","A00-G2":"Mistletoe Green","A00-R3":"Hot Pink","A00-P6":"Magenta","A00-R0":"Red","A00-R2":"Maroon Red","A00-P5":"Purple","A00-P2":"Indigo Purple","A00-B5":"Turquoise","A00-B8":"Cyan","A00-B3":"Cobalt Blue","A00-N0":"Brown","A00-N1":"Cocoa Brown","A00-Y3":"Bronze","A00-D0":"Gray","A00-D1":"Silver","A00-B1":"Blue Grey","A00-D3":"Dark Gray","A00-K0":"Black","A00-M3":"Pink Citrus","A00-M6":"Dusk Glare","A00-M0":"Arctic Whisper","A00-M1":"Solar Breeze","A00-M5":"Blueberry Bubblegum","A00-M4":"Mint Lime","A00-M2":"Ocean to Meadow","A00-M7":"Cotton Candy Cloud","A18-K0":"Black","A18-D0":"Gray","A18-W0":"White","A18-R0":"Red","A18-Y0":"Yellow","A18-B0":"Cyan","A18-B1":"Blue","A18-P0":"Matte Beige","A01-W2":"Ivory White","A01-W3":"Bone White","A01-Y2":"Lemon Yellow","A01-A2":"Mandarin Orange","A01-P3":"Sakura Pink","A01-P4":"Lilac Purple","A01-R3":"Plum","A01-R1":"Scarlet Red","A01-R4":"Dark Red","A01-G0":"Apple Green","A01-G1":"Grass Green","A01-G7":"Dark Green","A01-B4":"Ice Blue","A01-B0":"Sky Blue","A01-B3":"Marine Blue","A01-B6":"Dark Blue","A01-Y3":"Desert Tan","A01-N1":"Latte Brown","A01-N3":"Caramel","A01-R2":"Terracotta","A01-N2":"Dark Brown","A01-N0":"Dark Chocolate","A01-D3":"Ash Gray","A01-D0":"Nardo Gray","A01-K1":"Charcoal","A12-G0":"Green","A12-R0":"Pink","A12-A0":"Orange","A12-Y0":"Yellow","A12-B0":"Blue","A07-R5":"Red Granite","A07-D4":"White Marble","A11-W0":"White","A11-K0":"Black","A08-G3":"Alpine Green Sparkle","A08-D5":"Slate Gray Sparkle","A08-B7":"Royal Purple Sparkle","A08-R2":"Crimson Red Sparkle","A08-K2":"Onyx Black Sparkle","A08-Y1":"Classic Gold Sparkle","A02-B2":"Cobalt Blue Metallic","A02-G2":"Oxide Green Metallic","A02-Y1":"Iridium Gold Metallic","A02-D2":"Iron Gray Metallic","A17-B1":"Blue","A17-A0":"Orange","A17-P0":"Purple","A06-Y1":"Gold","A06-D0":"Titan Gray","A06-D1":"Silver","A06-W0":"White","A06-R0":"Candy Red","A06-G0":"Candy Green","A06-G1":"Mint","A06-B1":"Blue","A06-B0":"Baby Blue","A06-P0":"Purple","A06-R1":"Rose Gold","A06-R2":"Pink","A06-Y0":"Champagne","A05-M8":"Dawn Radiance","A05-M4":"Aurora Purple","A05-M1":"South Beach","A05-T3":"Neon City","A05-T2":"Midnight Blaze","A05-T1":"Gilded Rose","A05-T4":"Blue Hawaii","A05-T5":"Velvet Eclipse","A15-B0":"Purple","A15-G0":"Green","A15-G1":"Nebulae","A15-R0":"Brown","A16-K0":"Black Walnut","A16-R0":"Rosewood","A16-N0":"Clay Brown","A16-G0":"Classic Birch","A16-W0":"White Oak","A16-Y0":"Ochre Yellow","A50-D6":"Lava Gray","A50-K0":"Black","A50-B6":"Royal Blue","A10-W0":"White","A10-D0":"Gray","A09-B5":"Lavender Blue","A09-B4":"Light Blue","A09-A0":"Orange","A09-D1":"Silver","A09-R3":"Vermilion Red","A09-Y0":"Yellow","G02-K0":"Black","G02-W0":"White","G02-R0":"Red","G02-D0":"Gray","G02-D1":"Dark Gray","G02-Y1":"Cream","G02-Y0":"Yellow","G02-A0":"Orange","G02-N1":"Peanut Brown","G02-G1":"Lime Green","G02-G0":"Green","G02-G2":"Forest Green","G02-B1":"Lake Blue","G02-B0":"Blue","G01-G1":"Translucent Teal","G01-B0":"Translucent Light Blue","G01-C0":"Clear","G01-D0":"Translucent Gray","G01-G0":"Translucent Olive","G01-N0":"Translucent Brown","G01-A0":"Translucent Orange","G01-P1":"Translucent Pink","G01-P0":"Translucent Purple","G50-P7":"Violet Purple","G50-K0":"Black","B00-D1":"Silver","B00-K0":"Black","B00-W0":"White","B00-G6":"Bambu Green","B00-G7":"Olive","B00-Y1":"Tangerine Yellow","B00-A0":"Orange","B00-R0":"Red","B00-B4":"Azure","B00-B0":"Blue","B00-B6":"Navy Blue","B50-A0":"Orange","B50-K0":"Black","B01-W0":"White","B01-K0":"Black","B01-D0":"Gray","B02-W0":"White","C00-C1":"Transparent","C00-C0":"Clear Black","C00-K0":"Black","C00-W0":"White","C01-K0":"Black","U02-B0":"Blue","U02-D0":"Gray","U02-K0":"Black","N04-K0":"Black","N08-K0":"Black","S02-W0":"Nature","S02-W1":"White","S05-C0":"Black","S06-W0":"White","S03-G1":"Green","S04-Y0":"Clear"},qHe={W0:"White",W1:"Jade White",W2:"Ivory White",W3:"Bone White",Y0:"Yellow",Y1:"Gold",Y2:"Sunflower Yellow",Y3:"Bronze",Y4:"Gold",A0:"Orange",A1:"Pumpkin Orange",A2:"Mandarin Orange",R0:"Red",R1:"Scarlet Red",R2:"Maroon Red",R3:"Hot Pink",R4:"Dark Red",R5:"Red Granite",P0:"Beige",P1:"Pink",P2:"Indigo Purple",P3:"Sakura Pink",P4:"Lilac Purple",P5:"Purple",P6:"Magenta",P7:"Violet Purple",B0:"Blue",B1:"Blue Grey",B2:"Cobalt Blue",B3:"Cobalt Blue",B4:"Ice Blue",B5:"Turquoise",B6:"Navy Blue",B7:"Royal Purple",B8:"Cyan",G0:"Green",G1:"Grass Green",G2:"Mistletoe Green",G3:"Bright Green",G6:"Bambu Green",G7:"Dark Green",N0:"Brown",N1:"Peanut Brown",N2:"Dark Brown",N3:"Caramel",D0:"Gray",D1:"Silver",D2:"Light Gray",D3:"Dark Gray",D4:"White Marble",D5:"Slate Gray",D6:"Lava Gray",K0:"Black",K1:"Charcoal",K2:"Onyx Black",C0:"Clear Black",C1:"Transparent",M0:"Arctic Whisper",M1:"Solar Breeze",M2:"Ocean to Meadow",M3:"Pink Citrus",M4:"Aurora Purple",M5:"Blueberry Bubblegum",M6:"Dusk Glare",M7:"Cotton Candy Cloud",M8:"Dawn Radiance",T1:"Gilded Rose",T2:"Midnight Blaze",T3:"Neon City",T4:"Blue Hawaii",T5:"Velvet Eclipse"};function I2(t){if(!t)return null;if(X7[t])return X7[t];const e=t.split("-");if(e.length<2)return null;const n=e[1];return qHe[n]||null}function z2(t){if(!t||t.length<6)return"Unknown";const e=parseInt(t.substring(0,2),16),n=parseInt(t.substring(2,4),16),r=parseInt(t.substring(4,6),16),a=Math.max(e,n,r)/255,s=Math.min(e,n,r)/255,o=(a+s)/2;let l=0,c=0;if(a!==s){const u=a-s;c=o>.5?u/(2-a-s):u/(a+s);const d=e/255,h=n/255,f=r/255;a===d?l=((h-f)/u+(h.85?"White":c<.15?o<.4?"Dark Gray":o>.6?"Light Gray":"Gray":l>=15&&l<45&&o<.45||l>=45&&l<70&&o<.4?"Brown":l<15||l>=345?"Red":l<45?"Orange":l<70?"Yellow":l<150?"Green":l<200?"Cyan":l<260?"Blue":l<290?"Purple":"Pink"}function U2(t){return(t??.02).toFixed(3)}function Y7({side:t}){const{mode:e}=Jf(),n=e==="dark"?"#1a4d2e":"#e7f5e9";return i.jsx("span",{className:"inline-flex items-center justify-center w-4 h-4 text-[10px] font-bold rounded",style:{backgroundColor:n,color:"#00ae42"},children:t})}function dI(t){if(!t||t==="00000000"||t.length<6)return null;const e=t.slice(0,2),n=t.slice(2,4),r=t.slice(4,6),a=t.length>=8?parseInt(t.slice(6,8),16)/255:1;return a===0?null:`rgba(${parseInt(e,16)}, ${parseInt(n,16)}, ${parseInt(r,16)}, ${a})`}function GHe(t){if(!t||t.length<6)return!1;const e=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16);return(.299*e+.587*n+.114*r)/255>.6}function rne(t,e){if(!t)return"";if(t.includes("hardened"))return e("printers.nozzleHardenedSteel");if(t.includes("stainless"))return e("printers.nozzleStainlessSteel");if(t.includes("tungsten"))return e("printers.nozzleTungstenCarbide");if(t.length>=4){const n=t.slice(2,4);if(n==="00")return e("printers.nozzleStainlessSteel");if(n==="01")return e("printers.nozzleHardenedSteel");if(n==="05")return e("printers.nozzleTungstenCarbide")}return t==="00"?e("printers.nozzleStainlessSteel"):t==="01"?e("printers.nozzleHardenedSteel"):t==="05"?e("printers.nozzleTungstenCarbide"):t.startsWith("H")?e("printers.nozzleHardenedSteel"):t}function ane(t,e){return t?t.startsWith("HH")?e("printers.nozzleHighFlow"):t.startsWith("HS")?e("printers.nozzleStandardFlow"):"":""}function ine({slot:t,index:e,activeStatus:n,filamentName:r,children:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState("top"),d=w.useRef(null),h=w.useRef(null),f=w.useRef(null),p=!t.nozzle_diameter&&!t.nozzle_type,x=t.stat===1;w.useEffect(()=>{if(o&&d.current&&h.current){const k=d.current.getBoundingClientRect(),A=h.current.offsetHeight,C=k.top-56,j=window.innerHeight-k.bottom;CC?u("bottom"):u("top")}},[o]);const v=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!0),80)},g=()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),100)};w.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const y=dI(t.filament_color),_=rne(t.nozzle_type,s),N=ane(t.nozzle_type,s);return i.jsxs("div",{ref:d,className:"relative",onMouseEnter:v,onMouseLeave:g,children:[a,o&&i.jsxs("div",{ref:h,className:` absolute left-1/2 -translate-x-1/2 z-50 ${c==="top"?"bottom-full mb-2":"top-full mt-2"} animate-in fade-in-0 zoom-in-95 duration-150 @@ -8669,7 +8669,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Qs(t. ${!u&&!U?"border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80":""} ${G?"sm:cursor-default":""} `,onClick:G?()=>{window.innerWidth<640&&d()}:void 0,children:[G&&u&&i.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),i.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[R&&d&&i.jsx("button",{onClick:z=>{z.stopPropagation(),d()},className:`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${u?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:u&&i.jsx(ra,{className:"w-4 h-4"})}),R?i.jsx("div",{...M,...C,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:i.jsx(Ph,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?i.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]}):i.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),i.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?i.jsx("img",{src:t.plate_id!=null?ne.getArchivePlateThumbnail(t.archive_id,t.plate_id):ne.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?i.jsx("img",{src:t.plate_id!=null?ne.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ne.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(mi,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.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}`,(N?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${k.find(z=>z.index===t.plate_id)?.name||x("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?i.jsx(Ks,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewArchive"),children:i.jsx(Kr,{className:"w-3.5 h-3.5"})}):t.library_file_id?i.jsx(Ks,{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:i.jsx(Kr,{className:"w-3.5 h-3.5"})}):null]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[i.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?"text-blue-400":""}`,children:[i.jsx(xr,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),i.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model?`${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&&i.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[i.jsx(Lu,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Qs(t.print_time_seconds)]}),t.filament_used_grams&&i.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[i.jsx(mX,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Die(t.filament_used_grams)]}),t.created_by_username&&i.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:x("queue.addedBy",{name:t.created_by_username}),children:[i.jsx(td,{className:"w-3.5 h-3.5"}),t.created_by_username]}),R&&!t.manual_start&&i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),t.scheduled_time?new Date(t.scheduled_time).getTime()-Date.now()<-6e4?x?.("queue.time.overdue")??"Overdue":gv(t.scheduled_time,c,x):x?.("queue.time.asap")??"ASAP"]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&i.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:[i.jsx(iX,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.staged")]}),t.require_previous_success&&i.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&&i.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:[i.jsx(hd,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),x("queue.badges.autoPowerOff")]})]}),U&&v&&i.jsxs("div",{className:"mt-2 sm:mt-3",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[i.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:i.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${v.progress||0}%`}})}),i.jsxs("span",{className:"text-white",children:[Math.round(v.progress||0),"%"]})]}),i.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&&i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Gn,{className:"w-3 h-3"}),Qs(v.remaining_time*60)]}),i.jsxs("span",{className:"text-bambu-green font-medium",title:x("printers.estimatedCompletion"),children:["ETA ",MF(v.remaining_time,c,x)]})]}),v.layer_num!=null&&v.total_layers!=null&&v.total_layers>0&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(mi,{className:"w-3 h-3"}),v.layer_num,"/",v.total_layers]})]})]}),t.waiting_reason&&t.status==="pending"&&i.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[i.jsx(Ba,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),i.jsx("span",{children:t.waiting_reason})]}),t.error_message&&i.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[i.jsx(Ba,{className:"w-3 h-3"}),t.error_message]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:z=>z.stopPropagation(),children:[i.jsx(EQe,{status:t.status,waitingReason:t.waiting_reason,printerState:p,t:x}),i.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[U&&i.jsx(Ce,{variant:"ghost",size:"sm",onClick:s,disabled:!h("printers:control"),title:h("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:i.jsx(hhe,{className:"w-4 h-4"})}),R&&i.jsxs(i.Fragment,{children:[t.manual_start&&i.jsx(Ce,{variant:"ghost",size:"sm",onClick:l,disabled:!h("printers:control"),title:h("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:i.jsx(io,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:n,disabled:!f("queue","update",t.created_by_id),title:f("queue","update",t.created_by_id)?x("common.edit"):x("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:r,disabled:!f("queue","delete",t.created_by_id),title:f("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:i.jsx(Ft,{className:"w-4 h-4"})})]}),V&&i.jsxs(i.Fragment,{children:[i.jsx(Ce,{variant:"ghost",size:"sm",onClick:o,disabled:!h("queue:create"),title:h("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:i.jsx(Cr,{className:"w-4 h-4"})}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:a,disabled:!f("queue","delete",t.created_by_id),title:f("queue","delete",t.created_by_id)?x("common.remove"):x("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})]})]})]})}function DQe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r,hasAnyPermission:a,canModify:s}=Or(),[o,l]=w.useState(null),[c,u]=w.useState(""),[d,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(null),[g,y]=w.useState(null),[_,N]=w.useState(null),[k,A]=w.useState([]),[M,C]=w.useState(!1),[j,P]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[E,B]=w.useState(()=>{const L=localStorage.getItem("queue.historySortAsc");return L!==null?L==="true":!1}),[O,U]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[R,V]=w.useState(()=>{const L=localStorage.getItem("queue.pendingSortAsc");return L!==null?L==="true":!0});w.useEffect(()=>{localStorage.setItem("queue.historySortBy",j)},[j]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(E))},[E]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",O)},[O]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(R))},[R]);const G=lie(EC(SA,{activationConstraint:{distance:8}}),EC(wA,{coordinateGetter:Eie})),{data:z}=Je({queryKey:["settings"],queryFn:ne.getSettings}),K=z?.time_format||"system",{data:Y,isLoading:ae}=Je({queryKey:["queue",o,c],queryFn:()=>ne.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:$}=Je({queryKey:["printers"],queryFn:()=>ne.getPrinters()}),W=ot({mutationFn:L=>ne.cancelQueueItem(L),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),ee=ot({mutationFn:L=>ne.removeFromQueue(L),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),J=ot({mutationFn:L=>ne.stopQueueItem(L),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),ye=ot({mutationFn:L=>ne.startQueueItem(L),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),me=ot({mutationFn:L=>ne.reorderQueue(L),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),te=ot({mutationFn:async()=>{const L=Y?.filter(D=>["completed","failed","skipped","cancelled"].includes(D.status))||[];for(const D of L)await ne.removeFromQueue(D.id);return L.length},onSuccess:L=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:L}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),je=ot({mutationFn:L=>ne.bulkUpdateQueue(L),onSuccess:L=>{e.invalidateQueries({queryKey:["queue"]}),A([]),C(!1),n(L.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),ue=ot({mutationFn:async L=>{for(const D of L)await ne.cancelQueueItem(D);return L.length},onSuccess:L=>{e.invalidateQueries({queryKey:["queue"]}),A([]),n(t("queue.toast.bulkCancelled",{count:L}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),oe=L=>{A(D=>D.includes(L)?D.filter(H=>H!==L):[...D,L])},_e=w.useMemo(()=>{const L=new Set;return $?.forEach(D=>{D.location&&L.add(D.location)}),Y?.forEach(D=>{D.target_location&&L.add(D.target_location)}),Array.from(L).sort()},[$,Y]),se=w.useCallback(L=>d?L.target_location?L.target_location===d:L.printer_id?$?.find(H=>H.id===L.printer_id)?.location===d:!1:!0,[d,$]),Oe=w.useMemo(()=>{let L=Y?.filter(H=>H.status==="pending")||[];d&&(L=L.filter(se));const D=H=>{if(!H.scheduled_time)return 0;const he=new Date(H.scheduled_time).getTime(),be=Date.now()+4320*60*60*1e3;return he>be?0:he};return[...L].sort((H,he)=>{let be;if(O==="name"){const fe=H.archive_name||H.library_file_name||"",ze=he.archive_name||he.library_file_name||"";be=fe.localeCompare(ze)}else O==="printer"?be=(H.printer_name||"").localeCompare(he.printer_name||""):O==="time"?be=D(H)-D(he):be=H.position-he.position;return R?be:-be})},[Y,O,R,se,d]),q=()=>{const L=Oe.map(D=>D.id);k.length===L.length?A([]):A(L)},X=w.useMemo(()=>{let L=Y?.filter(D=>D.status==="printing")||[];return d&&(L=L.filter(se)),L},[Y,d,se]),de=w.useMemo(()=>{const L=new Set;return X.forEach(D=>{D.printer_id&&L.add(D.printer_id)}),Array.from(L)},[X]),Z=yF({queries:de.map(L=>({queryKey:["printerStatus",L],queryFn:()=>ne.getPrinterStatus(L),refetchInterval:5e3}))}),ie=w.useMemo(()=>{const L={};return de.forEach((D,H)=>{const he=Z[H];he?.data?.state&&(L[D]=he.data.state)}),L},[de,Z]),le=w.useMemo(()=>{let L=Y?.filter(D=>["completed","failed","skipped","cancelled"].includes(D.status))||[];return d&&(L=L.filter(se)),[...L].sort((D,H)=>{let he;if(j==="name"){const be=D.archive_name||D.library_file_name||"",fe=H.archive_name||H.library_file_name||"";he=be.localeCompare(fe)}else j==="printer"?he=(D.printer_name||"").localeCompare(H.printer_name||""):he=new Date(H.completed_at||H.created_at).getTime()-new Date(D.completed_at||D.created_at).getTime();return E?-he:he})},[Y,j,E,se,d]),Fe=w.useMemo(()=>Oe.reduce((L,D)=>L+(D.print_time_seconds||0),0),[Oe]),pe=w.useMemo(()=>Oe.reduce((L,D)=>L+(D.filament_used_grams||0),0),[Oe]),Q=L=>{const{active:D,over:H}=L;if(!H||D.id===H.id)return;const he=Oe.findIndex(fe=>fe.id===D.id),be=Oe.findIndex(fe=>fe.id===H.id);if(he!==-1&&be!==-1){const ze=CA(Oe,he,be).map((Ie,qe)=>({id:Ie.id,position:qe+1}));me.mutate(ze)}};return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsx("div",{className:"flex items-center justify-between mb-8",children:i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx(sX,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),i.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-2 sm:gap-3 lg:gap-4 mb-8",children:[i.jsx(vt,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-blue-500/20 flex items-center justify-center shrink-0",children:i.jsx(io,{className:"w-4 h-4 sm:w-5 sm:h-5 text-blue-400"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:X.length}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.printing")})]})]})})}),i.jsx(vt,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center shrink-0",children:i.jsx(Gn,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:Oe.length}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.queued")})]})]})})}),i.jsx(vt,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center shrink-0",children:i.jsx(Lu,{className:"w-4 h-4 sm:w-5 sm:h-5 text-bambu-green"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:Qs(Fe)}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.totalTime")})]})]})})}),i.jsx(vt,{className:"bg-gradient-to-br from-purple-500/10 to-transparent border-purple-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-purple-500/20 flex items-center justify-center shrink-0",children:i.jsx(mX,{className:"w-4 h-4 sm:w-5 sm:h-5 text-purple-500"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:Die(pe)}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.totalWeight")})]})]})})}),i.jsx(vt,{className:"col-span-2 sm:col-span-1 bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:i.jsx(_t,{className:"p-3 sm:p-4",children:i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3",children:[i.jsx("div",{className:"w-8 h-8 sm:w-10 sm:h-10 rounded-lg bg-gray-500/20 flex items-center justify-center shrink-0",children:i.jsx(pr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-gray-400"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-xl sm:text-2xl font-bold text-white truncate",children:le.length}),i.jsx("p",{className:"text-xs sm:text-sm text-bambu-gray truncate",children:t("queue.summary.history")})]})]})})})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[i.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:L=>{const D=L.target.value;l(D==="unassigned"?-1:D===""?null:Number(D))},children:[i.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),i.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),$?.map(L=>i.jsx("option",{value:L.id,children:L.name},L.id))]}),i.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:L=>u(L.target.value),children:[i.jsx("option",{value:"",children:t("queue.filter.allStatus")}),i.jsx("option",{value:"pending",children:t("queue.status.pending")}),i.jsx("option",{value:"printing",children:t("queue.status.printing")}),i.jsx("option",{value:"completed",children:t("queue.status.completed")}),i.jsx("option",{value:"failed",children:t("queue.status.failed")}),i.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),i.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),_e.length>0&&i.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:d,onChange:L=>h(L.target.value),children:[i.jsx("option",{value:"",children:t("queue.filter.allLocations")}),_e.map(L=>i.jsx("option",{value:L,children:L},L))]}),i.jsx("div",{className:"hidden sm:block flex-1"}),le.length>0&&i.jsxs(Ce,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>p(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[i.jsx(Jt,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),ae?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Y?.length===0?i.jsxs(vt,{className:"p-12 text-center border-dashed",children:[i.jsx(na,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),i.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),i.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):i.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[X.length>0&&i.jsxs("div",{children:[i.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),i.jsx("div",{className:"space-y-2 sm:space-y-3",children:X.map(L=>i.jsx(Sj,{item:L,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:L}),onRequeue:()=>{},onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,printerState:L.printer_id?ie[L.printer_id]:null,t},L.id))})]}),Oe.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[i.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Gn,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),i.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:Oe.length}),")"]}),i.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.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:O,onChange:L=>U(L.target.value),children:[i.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),i.jsx("option",{value:"name",children:t("queue.sort.byName")}),i.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),i.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>V(!R),title:t(R?"common.ascending":"common.descending"),className:"px-2",children:R?i.jsx(Af,{className:"w-4 h-4"}):i.jsx(ib,{className:"w-4 h-4"})})]})]}),i.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:[i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:q,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[k.length===Oe.length&&Oe.length>0?i.jsx(so,{className:"w-4 h-4 text-bambu-green"}):i.jsx(vl,{className:"w-4 h-4"}),k.length===Oe.length&&Oe.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),k.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:k.length})}),i.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>C(!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:!a("queue:update_own","queue:update_all"),title:a("queue:update_own","queue:update_all")?t("queue.bulkEdit.editSelected"):t("queue.permissions.noEditItems"),children:[i.jsx($a,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>ue.mutate(k),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:ue.isPending||!a("queue:delete_own","queue:delete_all"),title:a("queue:delete_own","queue:delete_all")?t("queue.bulkEdit.cancelSelected"):t("queue.permissions.noCancelItems"),children:[i.jsx(Ft,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),i.jsx(Cie,{sensors:G,collisionDetection:hie,onDragEnd:Q,children:i.jsx(Tie,{items:Oe.map(L=>L.id),strategy:vQe,children:i.jsx("div",{className:"space-y-2 sm:space-y-3",children:Oe.map((L,D)=>i.jsx(Sj,{item:L,position:D+1,onEdit:()=>v(L),onCancel:()=>N({type:"cancel",item:L}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>ye.mutate(L.id),timeFormat:K,isSelected:k.includes(L.id),onToggleSelect:()=>oe(L.id),hasPermission:r,canModify:s,t},L.id))})})})]}),le.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[i.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(pr,{className:"w-4 h-4 sm:w-5 sm:h-5 text-bambu-gray"}),t("queue.sections.history"),i.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:le.length}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.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:j,onChange:L=>P(L.target.value),children:[i.jsx("option",{value:"date",children:t("queue.sort.byDate")}),i.jsx("option",{value:"name",children:t("queue.sort.byName")}),i.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>B(!E),title:t(E?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:E?i.jsx(Af,{className:"w-4 h-4"}):i.jsx(ib,{className:"w-4 h-4"})})]})]}),i.jsx("div",{className:"space-y-2 sm:space-y-3",children:le.slice(0,20).map((L,D)=>i.jsx(Sj,{item:L,position:D+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:L}),onStop:()=>{},onRequeue:()=>y(L),onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,t},L.id))})]})]}),x&&i.jsx(Xu,{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)}),g&&i.jsx(Xu,{mode:"add-to-queue",archiveId:g.archive_id??void 0,libraryFileId:g.library_file_id??void 0,archiveName:g.archive_name||g.library_file_name||`File #${g.archive_id||g.library_file_id}`,onClose:()=>y(null)}),_&&i.jsx(gn,{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"?W.mutate(_.item.id):_.type==="stop"?J.mutate(_.item.id):ee.mutate(_.item.id),N(null)},onCancel:()=>N(null)}),f&&i.jsx(gn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:le.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{te.mutate(),p(!1)},onCancel:()=>p(!1)}),M&&i.jsx(jQe,{selectedCount:k.length,printers:$?.map(L=>({id:L.id,name:L.name}))||[],onSave:L=>{Object.keys(L).length>0&&je.mutate({item_ids:k,...L})},onClose:()=>C(!1),isSaving:je.isPending,t})]})}function RQe({printDates:t,months:e=3}){const n=w.useRef(null),[r,a]=w.useState(0);w.useEffect(()=>{const _=n.current;if(!_)return;const N=new ResizeObserver(k=>{const A=k[0]?.contentRect.width||0;a(A)});return N.observe(_),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const _={};t.forEach(B=>{const O=B.split("T")[0];_[O]=(_[O]||0)+1});const N=new Date,k=new Date(N);k.setMonth(k.getMonth()-e),k.setDate(k.getDate()-k.getDay());const A=[],M=[];let C=[],j=-1;const P=new Date(k);let E=0;for(;P<=N;)P.getDay()===0&&C.length>0&&(A.push(C),C=[],E++),P.getMonth()!==j&&(M.push({month:P.toLocaleDateString("en-US",{month:"short"}),weekIndex:E}),j=P.getMonth()),C.push(new Date(P)),P.setDate(P.getDate()+1);return C.length>0&&A.push(C),{weeks:A,monthLabels:M,printCounts:_}},[t,e]),c=Math.max(1,...Object.values(l)),u=_=>{if(_===0)return"bg-bambu-dark";const N=_/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=s.length,f=32,p=2,x=r-f-16,v=h>0?Math.floor((x-(h-1)*p)/h):12,g=Math.max(8,Math.min(20,v)),y=g<=10?10:12;return i.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&i.jsxs("div",{children:[i.jsx("div",{className:"flex mb-1",style:{marginLeft:f+4},children:o.map(({month:_,weekIndex:N},k)=>i.jsx("div",{className:"text-bambu-gray",style:{fontSize:y,marginLeft:k===0?0:`${(N-(o[k-1]?.weekIndex||0))*(g+p)-24}px`},children:_},k))}),i.jsxs("div",{className:"flex",style:{gap:p},children:[i.jsx("div",{className:"flex flex-col",style:{gap:p,marginRight:4,width:f},children:d.map((_,N)=>i.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:f,height:g,fontSize:y,visibility:N%2===1?"visible":"hidden"},children:_},_))}),s.map((_,N)=>i.jsx("div",{className:"flex flex-col",style:{gap:p},children:[0,1,2,3,4,5,6].map(k=>{const A=_.find(P=>P.getDay()===k);if(!A)return i.jsx("div",{style:{width:g,height:g}},k);const M=A.toISOString().split("T")[0],C=l[M]||0,j=M===new Date().toISOString().split("T")[0];return i.jsx("div",{className:`rounded-sm ${u(C)} ${j?"ring-1 ring-white":""}`,style:{width:g,height:g},title:`${A.toLocaleDateString()}: ${C} print${C!==1?"s":""}`},k)})},N))]}),i.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:y},children:[i.jsx("span",{children:"Less"}),i.jsxs("div",{className:"flex",style:{gap:p},children:[i.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:g,height:g}}),i.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:g,height:g}})]}),i.jsx("span",{children:"More"})]})]})})}const R_=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function FQe(t){const e=new Date;switch(t){case"7d":return new Date(e.getTime()-10080*60*1e3);case"30d":return new Date(e.getTime()-720*60*60*1e3);case"90d":return new Date(e.getTime()-2160*60*60*1e3);case"365d":return new Date(e.getTime()-365*24*60*60*1e3);case"all":return new Date(0)}}function LQe({archives:t,currency:e="$"}){const[n,r]=w.useState("30d"),a=w.useMemo(()=>{const p=FQe(n);return t.filter(x=>(di(x.completed_at||x.created_at)||new Date(0))>=p)},[t,n]),s=w.useMemo(()=>{const p=new Map;return a.forEach(x=>{const v=di(x.completed_at||x.created_at)||new Date,g=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`,y=p.get(g)||{date:g,filament:0,cost:0,prints:0};y.filament+=x.filament_used_grams||0,y.cost+=x.cost||0,y.prints+=x.quantity||1,p.set(g,y)}),Array.from(p.values()).sort((x,v)=>x.date.localeCompare(v.date)).map(x=>({...x,dateLabel:new Date(x.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[a]),o=w.useMemo(()=>{if(n==="7d"||n==="30d")return s;const p=new Map;return a.forEach(x=>{const v=di(x.completed_at||x.created_at)||new Date,g=new Date(v);g.setDate(v.getDate()-v.getDay());const y=`${g.getFullYear()}-${String(g.getMonth()+1).padStart(2,"0")}-${String(g.getDate()).padStart(2,"0")}`,_=p.get(y)||{week:y,filament:0,cost:0,prints:0};_.filament+=x.filament_used_grams||0,_.cost+=x.cost||0,_.prints+=x.quantity||1,p.set(y,_)}),Array.from(p.values()).sort((x,v)=>x.week.localeCompare(v.week)).map(x=>({date:x.week,dateLabel:`Week of ${new Date(x.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...x}))},[a,s,n]),l=w.useMemo(()=>{const p=new Map;return a.forEach(x=>{const g=(x.filament_type||"Unknown").split(", ");g.forEach(y=>{const _=(x.filament_used_grams||0)/g.length;p.set(y,(p.get(y)||0)+_)})}),Array.from(p.entries()).map(([x,v])=>({name:x,value:Math.round(v)})).sort((x,v)=>v.value-x.value)},[a]),c=w.useMemo(()=>{const p=new Date,x=[];for(let v=5;v>=0;v--){const g=new Date(p.getFullYear(),p.getMonth()-v,1),y=new Date(p.getFullYear(),p.getMonth()-v+1,0),_=g.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(k=>{const A=di(k.completed_at||k.created_at)||new Date(0);return A>=g&&A<=y});x.push({month:_,filament:Math.round(N.reduce((k,A)=>k+(A.filament_used_grams||0),0)),cost:N.reduce((k,A)=>k+(A.cost||0),0),prints:N.reduce((k,A)=>k+(A.quantity||1),0)})}return x},[t]),u=n==="7d"||n==="30d"?s:o,d=a.reduce((p,x)=>p+(x.filament_used_grams||0),0),h=a.reduce((p,x)=>p+(x.cost||0),0),f=a.reduce((p,x)=>p+(x.quantity||1),0);return i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between max-[550px]:flex-col max-[550px]:items-start max-[550px]:gap-2",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),i.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(p=>i.jsx("button",{onClick:()=>r(p),className:`px-3 py-1 text-sm rounded-md transition-colors ${n===p?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:p==="all"?"All":p.replace("d","D")},p))})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:"Period Filament"}),i.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[(d/1e3).toFixed(2),"kg"]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:"Period Cost"}),i.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,h.toFixed(2)]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[f," prints"]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:"Avg per Print"}),i.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[f>0?(d/f).toFixed(0):0,"g"]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,f>0?(h/f).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),i.jsx(Z_,{width:"100%",height:250,children:i.jsxs(jHe,{data:u,children:[i.jsx("defs",{children:i.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[i.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),i.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),i.jsx(MN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),i.jsx(DN,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),i.jsx(RN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),i.jsx(e1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:p=>[`${Number(p??0).toFixed(0)}g`,"Filament"]}),i.jsx(Fte,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):i.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx(Z_,{width:160,height:160,children:i.jsxs(PHe,{children:[i.jsx(ote,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((p,x)=>i.jsx(F0,{fill:R_[x%R_.length]},`cell-${x}`))}),i.jsx(e1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:p=>[`${p??0}g`,"Usage"]})]})}),i.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((p,x)=>{const v=l.reduce((y,_)=>y+_.value,0),g=v>0?(p.value/v*100).toFixed(0):0;return i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:R_[x%R_.length]}}),i.jsx("span",{className:"text-white truncate flex-1",children:p.name}),i.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[g,"%"]})]},p.name)})})]}):i.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[i.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),i.jsx(Z_,{width:"100%",height:200,children:i.jsxs(xHe,{data:c,children:[i.jsx(MN,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),i.jsx(DN,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),i.jsx(RN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),i.jsx(e1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(p,x)=>[x==="filament"?`${p??0}g`:x==="cost"?`${e}${Number(p??0).toFixed(2)}`:p??0,x==="filament"?"Filament":x==="cost"?"Cost":"Prints"]}),i.jsx(DL,{}),i.jsx(Ute,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function OQe({id:t,title:e,component:n,isHidden:r,size:a,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:u,setNodeRef:d,transform:h,transition:f,isDragging:p}=Pie({id:t}),x={transform:Db.Transform.toString(h),transition:f,opacity:p?.5:1};return r?null:i.jsxs("div",{ref:d,style:{...x,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${p?"ring-2 ring-bambu-green shadow-lg":""}`,children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("button",{...c,...u,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:i.jsx(Ph,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),i.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:l,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${a===1?"1/4":a===2?"1/2":"Full"} - Click to cycle`,children:a===4?i.jsx(SF,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):i.jsx($C,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),i.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:i.jsx(o0,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),i.jsx("div",{className:"p-4",children:typeof n=="function"?n(a):n})]})}function IQe({widgets:t,storageKey:e,columns:n=4,stackBelow:r,hideControls:a=!1,onResetLayout:s,renderControls:o}){const l=()=>{const j={};return t.forEach(P=>{j[P.id]=P.defaultSize||4}),j},[c,u]=w.useState(()=>{const j=localStorage.getItem(e);if(j)try{const P=JSON.parse(j);return P.sizes||(P.sizes=l()),P}catch{}return{order:t.map(P=>P.id),hidden:t.filter(P=>P.defaultVisible===!1).map(P=>P.id),sizes:l()}}),[d,h]=w.useState(!1),[f,p]=w.useState(!1);w.useEffect(()=>{if(!r)return;const j=window.matchMedia(`(max-width: ${r}px)`),P=B=>{p(B.matches)};P(j);const E=B=>P(B);return j.addEventListener?j.addEventListener("change",E):j.addListener(E),()=>{j.removeEventListener?j.removeEventListener("change",E):j.removeListener(E)}},[r]);const x=r&&f?1:n;w.useEffect(()=>{const j=()=>h(P=>!P);return window.addEventListener("toggle-hidden-panel",j),()=>window.removeEventListener("toggle-hidden-panel",j)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),w.useEffect(()=>{const P=t.map(E=>E.id).filter(E=>!c.order.includes(E));P.length>0&&u(E=>({...E,order:[...E.order,...P]}))},[t,c.order]);const v=lie(EC(SA,{activationConstraint:{distance:8}}),EC(wA,{coordinateGetter:Eie})),g=j=>{const{active:P,over:E}=j;E&&P.id!==E.id&&u(B=>{const O=B.order.indexOf(P.id),U=B.order.indexOf(E.id);return{...B,order:CA(B.order,O,U)}})},y=j=>{u(P=>({...P,hidden:P.hidden.includes(j)?P.hidden.filter(E=>E!==j):[...P.hidden,j]}))},_=j=>{u(P=>{const E=P.sizes[j]||4,B=E===1?2:E===2?4:1;return{...P,sizes:{...P.sizes,[j]:B}}})},N=()=>{const j={order:t.map(P=>P.id),hidden:t.filter(P=>P.defaultVisible===!1).map(P=>P.id),sizes:l()};u(j),s?.()},k=c.order.map(j=>t.find(P=>P.id===j)).filter(Boolean),A=k.filter(j=>!c.hidden.includes(j.id)),M=k.filter(j=>c.hidden.includes(j.id)),C=o?.({hiddenCount:M.length,showHiddenPanel:d,setShowHiddenPanel:h,resetLayout:N});return i.jsxs("div",{className:"space-y-4",children:[C,!a&&!o&&i.jsxs("div",{className:"flex items-center justify-end gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:N,children:[i.jsx(Fo,{className:"w-4 h-4"}),"Reset Layout"]}),M.length>0&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>h(!d),children:[i.jsx(Ql,{className:"w-4 h-4"}),M.length," Hidden"]})]}),d&&M.length>0&&i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(j=>i.jsxs("button",{onClick:()=>y(j.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:[i.jsx(Ql,{className:"w-3 h-3"}),j.title]},j.id))})]}),i.jsx(Cie,{sensors:v,collisionDetection:hie,onDragEnd:g,children:i.jsx(Tie,{items:A.map(j=>j.id),strategy:i4,children:i.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${x}, minmax(0, 1fr))`},children:A.map(j=>{const P=c.sizes[j.id]||2,E=Math.min(P,x);return i.jsx(OQe,{id:j.id,title:j.title,component:j.component,isHidden:c.hidden.includes(j.id),size:P,columnSpan:E,onToggleVisibility:()=>y(j.id),onToggleSize:()=>_(j.id)},j.id)})})})}),A.length===0&&i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx("p",{children:"All widgets are hidden."}),i.jsx(Ce,{className:"mt-4",onClick:N,children:"Reset Layout"})]})]})}function zQe({stats:t,currency:e,t:n}){return i.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(fi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),i.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:i.jsx(Gn,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:i.jsx(fi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:i.jsx(Jj,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:i.jsx(Vh,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(3)||"0.000"," kWh"]})]})]}),i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:i.jsx(Jj,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),i.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function UQe({stats:t,printerMap:e,size:n=1,t:r}){const a=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,s=n===1?112:n===2?128:144,o=s/2-8,l=o*2*Math.PI;return i.jsxs("div",{className:"flex items-center gap-6",children:[i.jsxs("div",{className:"relative flex-shrink-0",style:{width:s,height:s},children:[i.jsxs("svg",{className:"w-full h-full -rotate-90",children:[i.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),i.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${a/100*l} ${l}`})]}),i.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:i.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[a,"%"]})})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),i.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(hi,{className:"w-4 h-4 text-status-error flex-shrink-0"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),i.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&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),i.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(([c,u])=>i.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[i.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),i.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function BQe({stats:t,printerMap:e,size:n=1,t:r}){const a=t?.average_time_accuracy;if(a==null)return i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,a))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(a),u=a-100,d=n===1?112:n===2?128:144,h=d/2-8,f=h*2*Math.PI,p=n===1?3:n===2?6:999,x=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,p):[];return i.jsxs("div",{className:"flex items-center gap-6",children:[i.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[i.jsxs("svg",{className:"w-full h-full -rotate-90",children:[i.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),i.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*f} ${f}`})]}),i.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[i.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[a.toFixed(0),"%"]}),i.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[i.jsx(dX,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{children:r("stats.perfectEstimate")})]}),x.length>0&&i.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,g])=>i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),i.jsxs("span",{className:`font-medium ${g>=95&&g<=105?"text-status-ok":g>105?"text-blue-400":"text-status-warning"}`,children:[g.toFixed(0),"%"]})]},v))})]})]})}function HQe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return i.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noFilamentData")});const r=Object.entries(t.prints_by_filament_type).sort(([,l],[,c])=>c-l),a=e===1?5:e===2?8:999,s=r.slice(0,a),o=r.length>a;return e===4&&s.length>4?i.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),i.jsx("span",{className:"text-bambu-gray",children:c})]}),i.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:i.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):i.jsxs("div",{className:"space-y-3",children:[s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-white",children:l}),i.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:i.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&i.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-a})})]})}function $Qe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return i.jsx(RQe,{printDates:t,months:n})}function VQe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?i.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,a])=>i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:i.jsx(xr,{className:"w-4 h-4 text-bambu-green"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[a," ",n("common.prints")]})]})]},r))})}function qQe({archives:t,currency:e,t:n}){return!t||t.length===0?i.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):i.jsx(LQe,{archives:t,currency:e})}function GQe({size:t=1,t:e}){const{data:n,isLoading:r}=Je({queryKey:["failureAnalysis"],queryFn:()=>ne.getFailureAnalysis({days:30})});if(r)return i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return i.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const a=t===1?5:t===2?8:999,s=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=s.slice(0,a),l=s.length>a;return i.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[i.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[i.jsx("div",{className:"flex items-center gap-4",children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Tn,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),i.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),i.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:e("stats.failedPrintsCount",{failed:n.failed_prints,total:n.total_prints})}),n.trend&&n.trend.length>=2&&i.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(CF,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate0&&i.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[i.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),i.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>i.jsxs("div",{className:"flex items-center justify-between text-sm",children:[i.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),i.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:s.length-a})})]})]})}function WQe(){const{t}=Ut(),{showToast:e}=cn(),{hasPermission:n}=Or(),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(0),[u,d]=w.useState(0),[h,f]=w.useState(!1);w.useEffect(()=>{const P=()=>{try{const B=localStorage.getItem("bambusy-dashboard-layout");if(B){const O=JSON.parse(B);d(O.hidden?.length||0)}}catch{d(0)}};P(),window.addEventListener("storage",P);const E=setInterval(P,500);return()=>{window.removeEventListener("storage",P),clearInterval(E)}},[l]);const{data:p,isLoading:x,refetch:v}=Je({queryKey:["archiveStats"],queryFn:ne.getArchiveStats}),{data:g}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:y}=Je({queryKey:["archives"],queryFn:()=>ne.getArchives(void 0,void 0,1e3,0)}),{data:_}=Je({queryKey:["settings"],queryFn:ne.getSettings}),N=async P=>{o(!1),a(!0);try{const{blob:E,filename:B}=await ne.exportStats({format:P,days:90}),O=URL.createObjectURL(E),U=document.createElement("a");U.href=O,U.download=B,U.click(),URL.revokeObjectURL(O),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{a(!1)}},k=async()=>{f(!0);try{const P=await ne.recalculateCosts();await v(),e(t("stats.recalculatedCosts",{count:P.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},A=rl(_?.currency||"USD"),M=new Map(g?.map(P=>[String(P.id),P.name])||[]),C=y?.map(P=>P.created_at)||[];if(x)return i.jsx("div",{className:"p-4 md:p-8",children:i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const j=[{id:"quick-stats",title:t("stats.quickStats"),component:i.jsx(zQe,{stats:p,currency:A,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:P=>i.jsx(UQe,{stats:p,printerMap:M,size:P,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:P=>i.jsx(BQe,{stats:p,printerMap:M,size:P,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:P=>i.jsx(HQe,{stats:p,size:P,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:P=>i.jsx(GQe,{size:P,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:P=>i.jsx($Qe,{printDates:C,size:P}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:i.jsx(VQe,{stats:p,printerMap:M,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:i.jsx(qQe,{archives:y||[],currency:A,t}),defaultSize:4}];return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&i.jsxs(Ce,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[i.jsx(Ql,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(P=>P+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[i.jsx(Fo,{className:"w-4 h-4"}),t("stats.resetLayout")]}),i.jsxs(Ce,{variant:"secondary",onClick:k,disabled:h||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[h?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(qde,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),i.jsxs("div",{className:"relative",children:[i.jsxs(Ce,{variant:"secondary",onClick:()=>o(!s),disabled:r,children:[r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(b1,{className:"w-4 h-4"}),t("stats.exportStats")]}),s&&i.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:[i.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:()=>N("csv"),children:[i.jsx(Ms,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),i.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:()=>N("xlsx"),children:[i.jsx(b1,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),i.jsx(IQe,{widgets:j,storageKey:"bambusy-dashboard-layout",stackBelow:640,hideControls:!0},l)]})}function KQe({plug:t,onEdit:e}){const{t:n}=Ut(),r=tn(),{showToast:a}=cn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[u,d]=w.useState(!1),[h,f]=w.useState(!1),{data:p,isLoading:x}=Je({queryKey:["smart-plug-status",t.id],queryFn:()=>ne.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),g=v?.find(E=>E.id===t.printer_id),y=ot({mutationFn:E=>ne.controlSmartPlug(t.id,E),onMutate:async E=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const B=r.getQueryData(["smart-plug-status",t.id]),O=E==="on"?"ON":E==="off"||p?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],U=>({...U,state:O})),{previousStatus:B}},onError:(E,B,O)=>{O?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],O.previousStatus),a(`Failed to turn ${B} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),_=ot({mutationFn:E=>ne.updateSmartPlug(t.id,E),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=ot({mutationFn:()=>ne.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),k=p?.state==="ON",A=t.plug_type==="mqtt"&&p?.energy?.power!==null&&p?.energy?.power!==void 0,M=(p?.reachable??!1)||A,C=y.isPending,P=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const E=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${E}/`:`http://${E}/`})();return i.jsxs(i.Fragment,{children:[i.jsx(vt,{className:"relative",children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?M?"bg-teal-500/20":"bg-red-500/20":M?k?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?i.jsx(_F,{className:`w-5 h-5 ${M?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?i.jsx(l0,{className:`w-5 h-5 ${M?k?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):i.jsx(fl,{className:`w-5 h-5 ${M?k?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),i.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.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.ip_address})]})]}),i.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[x?i.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?i.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[i.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),M&&i.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?i.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[i.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),i.jsx("span",{className:M?k?"text-status-ok":"text-bambu-gray":"text-status-error",children:M?p?.state||"?":"Offline"})]}):M?i.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[i.jsx(Vg,{className:"w-4 h-4 text-status-ok"}),i.jsx("span",{className:k?"text-status-ok":"text-bambu-gray",children:p?.state||"Unknown"})]}):i.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[i.jsx(Pf,{className:"w-4 h-4"}),i.jsx("span",{children:n("smartPlugs.offline")})]}),P&&i.jsxs("a",{href:P,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:[i.jsx(Kr,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),g&&i.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),i.jsx("span",{className:"text-sm text-white",children:g.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&i.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&i.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:[i.jsx(Ql,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&i.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:[i.jsx(Hg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&i.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:[i.jsx(na,{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?`On ${t.schedule_on_time}`:`Off ${t.schedule_off_time}`]})]}),t.plug_type!=="mqtt"&&i.jsxs("div",{className:"flex gap-2 mb-3",children:[i.jsxs(Ce,{size:"sm",variant:k?"primary":"secondary",disabled:!M||C,onClick:()=>c(!0),className:"flex-1",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(hd,{className:"w-4 h-4"}),"On"]}),i.jsxs(Ce,{size:"sm",variant:k?"secondary":"primary",disabled:!M||C,onClick:()=>d(!0),className:"flex-1",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(GC,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&p?.energy&&i.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[p.energy.power!==null&&p.energy.power!==void 0&&i.jsxs("div",{className:"flex-1 text-center",children:[i.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(p.energy.power),"W"]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),p.energy.today!==null&&p.energy.today!==void 0&&i.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-lg font-semibold text-white",children:p.energy.today.toFixed(3)}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),i.jsxs("button",{onClick:()=>f(!h),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(ed,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),i.jsx("span",{children:h?"-":"+"})]}),h&&i.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(c0,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:E=>_.mutate({show_in_switchbar:E.target.checked}),className:"sr-only peer"}),i.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"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Enabled"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.enabled,onChange:E=>_.mutate({enabled:E.target.checked}),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Auto On"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:E=>_.mutate({auto_on:E.target.checked}),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:E=>_.mutate({auto_off:E.target.checked}),className:"sr-only peer"}),i.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&&i.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),i.jsxs("div",{className:"flex gap-2",children:[i.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:[i.jsx(Gn,{className:"w-4 h-4"}),"Time"]}),i.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:[i.jsx(XC,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),i.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:E=>_.mutate({off_delay_minutes:parseInt(E.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"})]}):i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),i.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:E=>_.mutate({off_temp_threshold:parseInt(E.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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),i.jsxs("div",{className:"flex gap-2 pt-2",children:[i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[i.jsx(Jm,{className:"w-4 h-4"}),"Edit"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})]})}),s&&i.jsx(gn,{title:n("smartPlugs.deleteSmartPlug"),message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&i.jsx(gn,{title:n("smartPlugs.turnOnSmartPlug"),message:`Are you sure you want to turn on "${t.name}"?`,confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{y.mutate("on"),c(!1)},onCancel:()=>c(!1)}),u&&i.jsx(gn,{title:n("smartPlugs.turnOffSmartPlug"),message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{y.mutate("off"),d(!1)},onCancel:()=>d(!1)})]})}function XQe({plug:t,onClose:e}){const{t:n}=Ut(),r=tn(),a=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[u,d]=w.useState(t?.ip_address||""),[h,f]=w.useState(t?.username||""),[p,x]=w.useState(t?.password||""),[v,g]=w.useState(t?.ha_entity_id||""),[y,_]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,k]=w.useState(t?.mqtt_power_path||""),[A,M]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,j]=w.useState(t?.mqtt_energy_topic||""),[P,E]=w.useState(t?.mqtt_energy_path||""),[B,O]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[U,R]=w.useState(t?.mqtt_state_topic||""),[V,G]=w.useState(t?.mqtt_state_path||""),[z,K]=w.useState(t?.mqtt_state_on_value||""),[Y,ae]=w.useState(t?.ha_power_entity||""),[$,W]=w.useState(t?.ha_energy_today_entity||""),[ee,J]=w.useState(t?.ha_energy_total_entity||""),[ye,me]=w.useState(""),[te,je]=w.useState(""),[ue,oe]=w.useState(!1),_e=w.useRef(null),[se,Oe]=w.useState(""),[q,X]=w.useState(!1),de=w.useRef(null),[Z,ie]=w.useState(""),[le,Fe]=w.useState(!1),pe=w.useRef(null),[Q,L]=w.useState(""),[D,H]=w.useState(!1),he=w.useRef(null),[be,fe]=w.useState(t?.printer_id||null),[ze,Ie]=w.useState(null),[qe,tt]=w.useState(null),[Ee,Se]=w.useState(t?.power_alert_enabled||!1),[Me,xe]=w.useState(t?.power_alert_high?.toString()||""),[ve,He]=w.useState(t?.power_alert_low?.toString()||""),[Pe,nt]=w.useState(t?.schedule_enabled||!1),[Te,Ge]=w.useState(t?.schedule_on_time||""),[Re,Le]=w.useState(t?.schedule_off_time||""),[Ke,ft]=w.useState(t?.show_in_switchbar||!1),[kt,Lt]=w.useState(t?.show_on_printer_card??!0),[Kt,Mt]=w.useState(!1),[Ue,bt]=w.useState({scanned:0,total:0}),[wt,qt]=w.useState([]),Cn=w.useRef(null),{data:yr}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:Qn}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:tr}=Je({queryKey:["settings"],queryFn:ne.getSettings}),Pn=!!(tr?.ha_enabled&&tr?.ha_url&&tr?.ha_token);w.useEffect(()=>{const Ne=setTimeout(()=>{je(ye)},300);return()=>clearTimeout(Ne)},[ye]),w.useEffect(()=>{const Ne=lt=>{_e.current&&!_e.current.contains(lt.target)&&oe(!1),de.current&&!de.current.contains(lt.target)&&X(!1),pe.current&&!pe.current.contains(lt.target)&&Fe(!1),he.current&&!he.current.contains(lt.target)&&H(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[]);const{data:dr,isLoading:Ar,error:ii}=Je({queryKey:["ha-entities",te],queryFn:()=>ne.getHAEntities(te||void 0),enabled:s==="homeassistant"&&Pn,retry:!1,staleTime:0}),{data:De}=Je({queryKey:["ha-sensor-entities"],queryFn:ne.getHASensorEntities,enabled:s==="homeassistant"&&Pn,retry:!1,staleTime:0});w.useEffect(()=>{const Ne=lt=>{lt.key==="Escape"&&e()};return window.addEventListener("keydown",Ne),()=>{window.removeEventListener("keydown",Ne),Cn.current&&clearInterval(Cn.current)}},[e]);const we=async()=>{Mt(!0),qt([]),bt({scanned:0,total:0}),tt(null);try{await ne.startTasmotaScan();const Ne=async()=>{try{const lt=await ne.getTasmotaScanStatus();bt({scanned:lt.scanned,total:lt.total});const pt=await ne.getDiscoveredTasmotaDevices();qt(pt),lt.running||(Mt(!1),Cn.current&&(clearInterval(Cn.current),Cn.current=null))}catch(lt){console.error("Polling error:",lt)}};await Ne(),Cn.current=setInterval(Ne,500)}catch(Ne){Mt(!1);const lt=Ne instanceof Error?Ne.message:typeof Ne=="string"?Ne:JSON.stringify(Ne);tt(lt||"Failed to start scan")}},et=async()=>{try{await ne.stopTasmotaScan()}catch{}Mt(!1),Cn.current&&(clearInterval(Cn.current),Cn.current=null)},st=Ne=>{d(Ne.ip_address),c(Ne.name),Ie(null)},Ve=ot({mutationFn:()=>ne.testSmartPlugConnection(u,h||null,p||null),onSuccess:Ne=>{Ie(Ne),tt(null),!l&&Ne.device_name&&c(Ne.device_name)},onError:Ne=>{Ie(null),tt(Ne.message)}}),Ot=ot({mutationFn:Ne=>ne.createSmartPlug(Ne),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Ne=>{tt(Ne.message)}}),ge=ot({mutationFn:Ne=>ne.updateSmartPlug(t.id,Ne),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Ne=>{tt(Ne.message)}}),Be=yr?.filter(Ne=>s==="tasmota"?!Qn?.some(pt=>pt.printer_id===Ne.id&&pt.id!==t?.id&&pt.plug_type==="tasmota"):!0),Xe=Ne=>{if(Ne.preventDefault(),tt(null),!l.trim()){tt("Name is required");return}if(s==="tasmota"&&!u.trim()){tt("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){tt("Entity is required for Home Assistant plugs");return}if(s==="mqtt"){const pt=y.trim(),at=C.trim(),At=U.trim();if(!pt&&!at&&!At){tt("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const lt={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?u.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&Y||null,ha_energy_today_entity:s==="homeassistant"&&$||null,ha_energy_total_entity:s==="homeassistant"&&ee||null,mqtt_power_topic:s==="mqtt"&&y.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(A)||1,mqtt_energy_topic:s==="mqtt"&&C.trim()||null,mqtt_energy_path:s==="mqtt"&&P.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(B)||1,mqtt_state_topic:s==="mqtt"&&U.trim()||null,mqtt_state_path:s==="mqtt"&&V.trim()||null,mqtt_state_on_value:s==="mqtt"&&z.trim()||null,username:s==="tasmota"&&h.trim()||null,password:s==="tasmota"&&p.trim()||null,printer_id:be,power_alert_enabled:Ee,power_alert_high:Me?parseFloat(Me):null,power_alert_low:ve?parseFloat(ve):null,schedule_enabled:Pe,schedule_on_time:Te||null,schedule_off_time:Re||null,show_in_switchbar:Ke,show_on_printer_card:kt};a?ge.mutate(lt):Ot.mutate(lt)},We=Ot.isPending||ge.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.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:Ne=>Ne.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:a?"Edit Smart Plug":"Add Smart Plug"}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:Xe,className:"p-6 space-y-4 overflow-y-auto",children:[qe&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:qe}),!a&&i.jsxs("div",{className:"flex gap-2 mb-2",children:[i.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Ie(null),tt(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:[i.jsx(fl,{className:"w-4 h-4"}),"Tasmota"]}),i.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Ie(null),tt(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:[i.jsx(l0,{className:"w-4 h-4"}),"HA"]}),i.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Ie(null),tt(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:[i.jsx(_F,{className:"w-4 h-4"}),"MQTT"]})]}),!a&&s==="tasmota"&&i.jsxs("div",{className:"space-y-3",children:[Kt?i.jsxs(Ce,{type:"button",variant:"secondary",onClick:et,className:"w-full",children:[i.jsx(Ft,{className:"w-4 h-4"}),"Stop Scanning"]}):i.jsxs(Ce,{type:"button",variant:"primary",onClick:we,className:"w-full",children:[i.jsx(kr,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),Kt&&Ue.total>0&&i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),i.jsxs("span",{children:[Ue.scanned," / ",Ue.total]})]}),i.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ue.scanned/Ue.total*100}%`}})})]}),wt.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",wt.length," device(s) - click to select:"]}),i.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:wt.map(Ne=>i.jsxs("button",{type:"button",onClick:()=>st(Ne),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:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fl,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:Ne.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:Ne.ip_address})]})]}),Ne.state&&i.jsxs("span",{className:`flex items-center gap-1 text-xs ${Ne.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[i.jsx(hd,{className:"w-3 h-3"}),Ne.state]})]},Ne.ip_address))})]}),!Kt&&wt.length===0&&Ue.total>0&&i.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),s==="homeassistant"&&i.jsxs("div",{className:"space-y-3",children:[!Pn&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["Home Assistant is not configured. Set it up in"," ",i.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),i.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:i.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),Pn&&i.jsxs(i.Fragment,{children:[Ar&&i.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[i.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),ii&&i.jsxs("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:["Failed to load entities: ",ii.message]}),(()=>{const Ne=Qn?.filter(at=>at.ha_entity_id&&at.id!==t?.id).map(at=>at.ha_entity_id)||[],lt=(dr||[]).filter(at=>!Ne.includes(at.entity_id)),pt=dr?.find(at=>at.entity_id===v);return i.jsxs("div",{ref:_e,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:ue?ye:pt?`${pt.friendly_name} (${pt.entity_id})`:"",onChange:at=>{me(at.target.value),ue||oe(!0)},onFocus:()=>{oe(!0),me("")},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&&!ue&&i.jsx("button",{type:"button",onClick:()=>{g(""),me("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ft,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Ar&&i.jsx(it,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),ue&&i.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:[Ar&&i.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Ar&<.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:te?`No entities found matching "${te}"`:"No entities available"}),!Ar&<.map(at=>i.jsxs("button",{type:"button",onClick:()=>{g(at.entity_id),oe(!1),me(""),l||c(at.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${at.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[i.jsx("span",{children:at.entity_id}),i.jsx("span",{className:at.state==="on"?"text-bambu-green":"",children:at.state})]})]},at.entity_id))]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:te?`Searching all entities (${lt.length} found)`:`Showing switch, light, input_boolean (${lt.length} available)`})]})})(),v&&De&&De.length>0&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),i.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const Ne=De.filter(at=>at.unit_of_measurement==="W"||at.unit_of_measurement==="kW"||at.unit_of_measurement==="mW"),lt=se?Ne.filter(at=>at.entity_id.toLowerCase().includes(se.toLowerCase())||at.friendly_name.toLowerCase().includes(se.toLowerCase())):Ne,pt=De.find(at=>at.entity_id===Y);return i.jsxs("div",{ref:de,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:q?se:pt?`${pt.friendly_name} (${pt.state} ${pt.unit_of_measurement})`:"",onChange:at=>{Oe(at.target.value),q||X(!0)},onFocus:()=>{X(!0),Oe("")},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"}),Y&&!q&&i.jsx("button",{type:"button",onClick:()=>{ae(""),Oe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ft,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),q&&i.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:[i.jsx("button",{type:"button",onClick:()=>{ae(""),X(!1),Oe("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),lt.map(at=>i.jsxs("button",{type:"button",onClick:()=>{ae(at.entity_id),X(!1),Oe("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${at.entity_id===Y?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[at.entity_id," • ",at.state," ",at.unit_of_measurement]})]},at.entity_id)),lt.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Ne=De.filter(at=>at.unit_of_measurement==="kWh"||at.unit_of_measurement==="Wh"||at.unit_of_measurement==="MWh"),lt=Z?Ne.filter(at=>at.entity_id.toLowerCase().includes(Z.toLowerCase())||at.friendly_name.toLowerCase().includes(Z.toLowerCase())):Ne,pt=De.find(at=>at.entity_id===$);return i.jsxs("div",{ref:pe,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:le?Z:pt?`${pt.friendly_name} (${pt.state} ${pt.unit_of_measurement})`:"",onChange:at=>{ie(at.target.value),le||Fe(!0)},onFocus:()=>{Fe(!0),ie("")},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"}),$&&!le&&i.jsx("button",{type:"button",onClick:()=>{W(""),ie("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ft,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),le&&i.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:[i.jsx("button",{type:"button",onClick:()=>{W(""),Fe(!1),ie("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),lt.map(at=>i.jsxs("button",{type:"button",onClick:()=>{W(at.entity_id),Fe(!1),ie("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${at.entity_id===$?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[at.entity_id," • ",at.state," ",at.unit_of_measurement]})]},at.entity_id)),lt.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const Ne=De.filter(at=>at.unit_of_measurement==="kWh"||at.unit_of_measurement==="Wh"||at.unit_of_measurement==="MWh"),lt=Q?Ne.filter(at=>at.entity_id.toLowerCase().includes(Q.toLowerCase())||at.friendly_name.toLowerCase().includes(Q.toLowerCase())):Ne,pt=De.find(at=>at.entity_id===ee);return i.jsxs("div",{ref:he,className:"relative",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),i.jsx("input",{type:"text",value:D?Q:pt?`${pt.friendly_name} (${pt.state} ${pt.unit_of_measurement})`:"",onChange:at=>{L(at.target.value),D||H(!0)},onFocus:()=>{H(!0),L("")},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"}),ee&&!D&&i.jsx("button",{type:"button",onClick:()=>{J(""),L("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ft,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),D&&i.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:[i.jsx("button",{type:"button",onClick:()=>{J(""),H(!1),L("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),lt.map(at=>i.jsxs("button",{type:"button",onClick:()=>{J(at.entity_id),H(!1),L("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${at.entity_id===ee?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[i.jsx("div",{className:"font-medium",children:at.friendly_name}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[at.entity_id," • ",at.state," ",at.unit_of_measurement]})]},at.entity_id)),lt.length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),s==="mqtt"&&i.jsxs("div",{className:"space-y-3",children:[!tr?.mqtt_broker&&i.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["MQTT broker not configured. Set broker address in"," ",i.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),tr?.mqtt_broker&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[i.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),i.jsx("p",{className:"text-xs opacity-80",children:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system."})]}),i.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),i.jsx("input",{type:"text",value:y,onChange:Ne=>_(Ne.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"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),i.jsx("input",{type:"text",value:N,onChange:Ne=>k(Ne.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),i.jsx("input",{type:"text",value:A,onChange:Ne=>M(Ne.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"})]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:['JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.',i.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),i.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",i.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),i.jsx("input",{type:"text",value:C,onChange:Ne=>j(Ne.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"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),i.jsx("input",{type:"text",value:P,onChange:Ne=>E(Ne.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),i.jsx("input",{type:"text",value:B,onChange:Ne=>O(Ne.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"})]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",i.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),i.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",i.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),i.jsx("input",{type:"text",value:U,onChange:Ne=>R(Ne.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"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),i.jsx("input",{type:"text",value:V,onChange:Ne=>G(Ne.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),i.jsx("input",{type:"text",value:z,onChange:Ne=>K(Ne.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"})]})]}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",i.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),s==="tasmota"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:u,onChange:Ne=>{d(Ne.target.value),Ie(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"}),i.jsxs(Ce,{type:"button",variant:"secondary",onClick:()=>Ve.mutate(),disabled:!u.trim()||Ve.isPending,children:[Ve.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Vg,{className:"w-4 h-4"}),"Test"]})]})]}),s==="tasmota"&&ze&&i.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ze.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:ze.success?i.jsxs(i.Fragment,{children:[i.jsx(pr,{className:"w-5 h-5"}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium",children:"Connected!"}),i.jsxs("p",{className:"text-sm opacity-80",children:[ze.device_name&&`Device: ${ze.device_name} - `,"State: ",ze.state]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx(Pf,{className:"w-5 h-5"}),i.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),i.jsx("input",{type:"text",value:l,onChange:Ne=>c(Ne.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"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),i.jsx("input",{type:"text",value:h,onChange:Ne=>f(Ne.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),i.jsx("input",{type:"password",value:p,onChange:Ne=>x(Ne.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"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),s!=="mqtt"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),i.jsxs("select",{value:be??"",onChange:Ne=>fe(Ne.target.value?Number(Ne.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:[i.jsx("option",{value:"",children:"No printer (manual control only)"}),Be?.map(Ne=>i.jsx("option",{value:Ne.id,children:Ne.name},Ne.id))]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Hg,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Ee,onChange:Ne=>Se(Ne.target.checked),className:"sr-only peer"}),i.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"})]})]}),Ee&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),i.jsx("input",{type:"number",value:Me,onChange:Ne=>xe(Ne.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),i.jsx("input",{type:"number",value:ve,onChange:Ne=>He(Ne.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"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),s!=="mqtt"&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Gn,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Pe,onChange:Ne=>nt(Ne.target.checked),className:"sr-only peer"}),i.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Pe&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),i.jsx("input",{type:"time",value:Te,onChange:Ne=>Ge(Ne.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),i.jsx("input",{type:"time",value:Re,onChange:Ne=>Le(Ne.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"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action."})]})]}),i.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(c0,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:Ke,onChange:Ne=>ft(Ne.target.checked),className:"sr-only peer"}),i.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"&&i.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ql,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white font-medium",children:"Show on Printer Card"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Display button on printer card"})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:kt,onChange:Ne=>Lt(Ne.target.checked),className:"sr-only peer"}),i.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"})]})]})}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),i.jsxs(Ce,{type:"submit",disabled:We,className:"flex-1",children:[We?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ps,{className:"w-4 h-4"}),a?"Save":"Add"]})]})]})]})})}function On({checked:t,onChange:e,disabled:n}){const r=a=>{a.preventDefault(),a.stopPropagation(),n||e(!t)};return i.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:i.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"}`})})}const YQe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function QQe({provider:t,onEdit:e}){const n=tn(),[r,a]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(null),{data:u}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),d=u?.find(v=>v.id===t.printer_id),h=ot({mutationFn:v=>ne.updateNotificationProvider(t.id,v),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),f=ot({mutationFn:()=>ne.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=ot({mutationFn:()=>ne.testNotificationProvider(t.id),onSuccess:v=>{c(v),n.invalidateQueries({queryKey:["notification-providers"]})},onError:v=>{c({success:!1,message:v.message})}}),x=v=>v||"";return i.jsxs(i.Fragment,{children:[i.jsx(vt,{className:"relative",children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-start justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:i.jsx(Hg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),i.jsxs("div",{children:[i.jsx("h3",{className:"font-medium text-white",children:t.name}),i.jsx("p",{className:"text-sm text-bambu-gray",children:YQe[t.provider_type]||t.provider_type})]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&i.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",cb(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(di(t.last_error_at)?.getTime()||0)>(di(t.last_success)?.getTime()||0))&&i.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),i.jsx(On,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]})]}),d&&i.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),i.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&i.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),i.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&i.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:"Start"}),t.on_plate_not_empty&&i.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:"Plate Check"}),t.on_print_complete&&i.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&i.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&i.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&i.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&i.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&i.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&i.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:"Low Filament"}),t.on_maintenance_due&&i.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:"Maintenance"}),t.on_ams_humidity_high&&i.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:"AMS Humidity"}),t.on_ams_temperature_high&&i.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:"AMS Temp"}),t.on_ams_ht_humidity_high&&i.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:"AMS-HT Humidity"}),t.on_ams_ht_temperature_high&&i.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:"AMS-HT Temp"}),t.on_bed_cooled&&i.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:"Bed Cooled"}),t.quiet_hours_enabled&&i.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[i.jsx(y1,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&i.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[i.jsx(na,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),i.jsx("div",{className:"mb-3",children:i.jsxs(Ce,{size:"sm",variant:"secondary",disabled:p.isPending,onClick:()=>{c(null),p.mutate()},className:"w-full",children:[p.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(WC,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&i.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${l.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[l.success?i.jsx(pr,{className:"w-4 h-4"}):i.jsx(hi,{className:"w-4 h-4"}),i.jsx("span",{children:l.message})]}),i.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors border-t border-bambu-dark-tertiary",children:[i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(ed,{className:"w-4 h-4"}),"Event Settings"]}),s?i.jsx(yl,{className:"w-4 h-4"}):i.jsx(Un,{className:"w-4 h-4"})]}),s&&i.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Enabled"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),i.jsx(On,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Started"}),i.jsx(On,{checked:t.on_print_start,onChange:v=>h.mutate({on_print_start:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),i.jsx(On,{checked:t.on_plate_not_empty??!0,onChange:v=>h.mutate({on_plate_not_empty:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),i.jsx(On,{checked:t.on_print_complete,onChange:v=>h.mutate({on_print_complete:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Bed Cooled"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Bed cooled below threshold after print"})]}),i.jsx(On,{checked:t.on_bed_cooled??!1,onChange:v=>h.mutate({on_bed_cooled:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),i.jsx(On,{checked:t.on_print_failed,onChange:v=>h.mutate({on_print_failed:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),i.jsx(On,{checked:t.on_print_stopped,onChange:v=>h.mutate({on_print_stopped:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),i.jsx(On,{checked:t.on_print_progress,onChange:v=>h.mutate({on_print_progress:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),i.jsx(On,{checked:t.on_printer_offline,onChange:v=>h.mutate({on_printer_offline:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),i.jsx(On,{checked:t.on_printer_error,onChange:v=>h.mutate({on_printer_error:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),i.jsx(On,{checked:t.on_filament_low,onChange:v=>h.mutate({on_filament_low:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),i.jsx(On,{checked:t.on_maintenance_due??!1,onChange:v=>h.mutate({on_maintenance_due:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),i.jsx(On,{checked:t.on_ams_humidity_high??!1,onChange:v=>h.mutate({on_ams_humidity_high:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),i.jsx(On,{checked:t.on_ams_temperature_high??!1,onChange:v=>h.mutate({on_ams_temperature_high:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),i.jsx(On,{checked:t.on_ams_ht_humidity_high??!1,onChange:v=>h.mutate({on_ams_ht_humidity_high:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),i.jsx(On,{checked:t.on_ams_ht_temperature_high??!1,onChange:v=>h.mutate({on_ams_ht_temperature_high:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Added"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),i.jsx(On,{checked:t.on_queue_job_added??!1,onChange:v=>h.mutate({on_queue_job_added:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),i.jsx(On,{checked:t.on_queue_job_assigned??!1,onChange:v=>h.mutate({on_queue_job_assigned:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Started"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),i.jsx(On,{checked:t.on_queue_job_started??!1,onChange:v=>h.mutate({on_queue_job_started:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),i.jsx(On,{checked:t.on_queue_job_waiting??!0,onChange:v=>h.mutate({on_queue_job_waiting:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),i.jsx(On,{checked:t.on_queue_job_skipped??!0,onChange:v=>h.mutate({on_queue_job_skipped:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),i.jsx(On,{checked:t.on_queue_job_failed??!0,onChange:v=>h.mutate({on_queue_job_failed:v})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),i.jsx(On,{checked:t.on_queue_completed??!1,onChange:v=>h.mutate({on_queue_completed:v})})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(y1,{className:"w-4 h-4 text-purple-400"}),i.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),i.jsx(On,{checked:t.quiet_hours_enabled,onChange:v=>h.mutate({quiet_hours_enabled:v})})]}),t.quiet_hours_enabled&&i.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Gn,{className:"w-4 h-4 text-bambu-gray"}),i.jsxs("span",{className:"text-sm text-white",children:[x(t.quiet_hours_start)||"22:00"," - ",x(t.quiet_hours_end)||"07:00"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(na,{className:"w-4 h-4 text-emerald-400"}),i.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),i.jsx(On,{checked:t.daily_digest_enabled,onChange:v=>h.mutate({daily_digest_enabled:v})})]}),t.daily_digest_enabled&&i.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[i.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Gn,{className:"w-4 h-4 text-bambu-gray"}),i.jsxs("span",{className:"text-sm text-white",children:["Send at ",x(t.daily_digest_time)||"08:00"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),i.jsxs("div",{className:"flex gap-2 pt-2",children:[i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[i.jsx(Jm,{className:"w-4 h-4"}),"Edit"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>a(!0),className:"text-red-400 hover:text-red-300",children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})]})}),r&&i.jsx(gn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{f.mutate(),a(!1)},onCancel:()=>a(!1)})]})}const KW=[{value:"email",label:"Email",description:"SMTP email notifications"},{value:"telegram",label:"Telegram",description:"Notifications via Telegram bot"},{value:"discord",label:"Discord",description:"Send to Discord channel via webhook"},{value:"ntfy",label:"ntfy",description:"Free, self-hostable push notifications"},{value:"pushover",label:"Pushover",description:"Simple, reliable push notifications"},{value:"callmebot",label:"CallMeBot/WhatsApp",description:"Free WhatsApp notifications via CallMeBot"},{value:"webhook",label:"Webhook",description:"Generic HTTP POST to any URL"}];function ZQe({provider:t,onClose:e}){const n=tn(),r=!!t,[a,s]=w.useState(t?.name||""),[o,l]=w.useState(t?.provider_type||"email"),[c,u]=w.useState(t?.printer_id||null),[d,h]=w.useState(t?.quiet_hours_enabled||!1),[f,p]=w.useState(t?.quiet_hours_start||"22:00"),[x,v]=w.useState(t?.quiet_hours_end||"07:00"),[g,y]=w.useState(t?.daily_digest_enabled||!1),[_,N]=w.useState(t?.daily_digest_time||"08:00"),[k,A]=w.useState(t?.on_print_start??!1),[M,C]=w.useState(t?.on_print_complete??!0),[j,P]=w.useState(t?.on_print_failed??!0),[E,B]=w.useState(t?.on_print_stopped??!0),[O,U]=w.useState(t?.on_print_progress??!1),[R,V]=w.useState(t?.on_printer_offline??!1),[G,z]=w.useState(t?.on_printer_error??!1),[K,Y]=w.useState(t?.on_filament_low??!1),[ae,$]=w.useState(t?.on_maintenance_due??!1),[W,ee]=w.useState(t?.on_bed_cooled??!1),[J,ye]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([le,Fe])=>[le,String(Fe)])):{}),[me,te]=w.useState(null),[je,ue]=w.useState(null),{data:oe}=Je({queryKey:["printers"],queryFn:ne.getPrinters});w.useEffect(()=>{const le=Fe=>{Fe.key==="Escape"&&e()};return window.addEventListener("keydown",le),()=>window.removeEventListener("keydown",le)},[e]);const _e=ot({mutationFn:()=>ne.testNotificationConfig({provider_type:o,config:J}),onSuccess:le=>{te(le),ue(null)},onError:le=>{te({success:!1,message:le.message})}}),se=ot({mutationFn:le=>ne.createNotificationProvider(le),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:le=>{ue(le.message)}}),Oe=ot({mutationFn:le=>ne.updateNotificationProvider(t.id,le),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:le=>{ue(le.message)}}),q=le=>{if(le.preventDefault(),ue(null),!a.trim()){ue("Name is required");return}const Fe=Z(o);for(const Q of Fe)if(!J[Q.key]?.trim()){ue(`${Q.label} is required`);return}const pe={name:a.trim(),provider_type:o,config:J,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?f:null,quiet_hours_end:d?x:null,daily_digest_enabled:g,daily_digest_time:g?_:null,on_print_start:k,on_print_complete:M,on_print_failed:j,on_print_stopped:E,on_print_progress:O,on_printer_offline:R,on_printer_error:G,on_filament_low:K,on_maintenance_due:ae,on_bed_cooled:W};r?Oe.mutate(pe):se.mutate(pe)},X=se.isPending||Oe.isPending,de=le=>{switch(le){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:Fe=>Fe.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:Fe=>Fe.payload_format!=="slack"}];default:return[]}},Z=le=>de(le).filter(Fe=>Fe.required),ie=de(o);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:i.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:le=>le.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:q,className:"p-6 space-y-4",children:[je&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:je}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),i.jsx("input",{type:"text",value:a,onChange:le=>s(le.target.value),placeholder:"My Notifications",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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),i.jsx("select",{value:o,onChange:le=>{l(le.target.value),ye({}),te(null)},disabled:r,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:KW.map(le=>i.jsx("option",{value:le.value,children:le.label},le.value))}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:KW.find(le=>le.value===o)?.description})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),ie.filter(le=>!("showIf"in le)||le.showIf?.(J)!==!1).map(le=>i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[le.label," ",le.required&&"*"]}),le.type==="select"&&"options"in le&&le.options?i.jsx("select",{value:J[le.key]||le.options[0]?.value||"",onChange:Fe=>{ye({...J,[le.key]:Fe.target.value}),te(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:le.options.map(Fe=>i.jsx("option",{value:Fe.value,children:Fe.label},Fe.value))}):i.jsx("input",{type:le.type,value:J[le.key]||"",onChange:Fe=>{ye({...J,[le.key]:Fe.target.value}),te(null)},placeholder:le.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"})]},le.key))]}),i.jsx("div",{className:"flex gap-2",children:i.jsxs(Ce,{type:"button",variant:"secondary",onClick:()=>{te(null),_e.mutate()},disabled:_e.isPending||!J[Z(o)[0]?.key],className:"flex-1",children:[_e.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(WC,{className:"w-4 h-4"}),"Test Configuration"]})}),me&&i.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${me.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:me.success?i.jsxs(i.Fragment,{children:[i.jsx(pr,{className:"w-5 h-5"}),i.jsx("span",{children:me.message})]}):i.jsxs(i.Fragment,{children:[i.jsx(hi,{className:"w-5 h-5"}),i.jsx("span",{children:me.message})]})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),i.jsxs("select",{value:c??"",onChange:le=>u(le.target.value?Number(le.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:[i.jsx("option",{value:"",children:"All printers"}),oe?.map(le=>i.jsx("option",{value:le.id,children:le.name},le.id))]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),i.jsx(On,{checked:d,onChange:h})]}),d&&i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),i.jsx("input",{type:"time",value:f,onChange:le=>p(le.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),i.jsx("input",{type:"time",value:x,onChange:le=>v(le.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"})]})]})]}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),i.jsx(On,{checked:g,onChange:y})]}),g&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),i.jsx("input",{type:"time",value:_,onChange:le=>N(le.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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),i.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Start"}),i.jsx(On,{checked:k,onChange:A})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Complete"}),i.jsx(On,{checked:M,onChange:C})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Failed"}),i.jsx(On,{checked:j,onChange:P})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Stopped"}),i.jsx(On,{checked:E,onChange:B})]}),i.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:"Progress"}),i.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),i.jsx(On,{checked:O,onChange:U})]}),i.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-white",children:"Bed Cooled"}),i.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(after print completes)"})]}),i.jsx(On,{checked:W,onChange:ee})]})]})]}),i.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Offline"}),i.jsx(On,{checked:R,onChange:V})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Error"}),i.jsx(On,{checked:G,onChange:z})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),i.jsx(On,{checked:K,onChange:Y})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),i.jsx(On,{checked:ae,onChange:$})]})]})]})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),i.jsxs(Ce,{type:"submit",disabled:X,className:"flex-1",children:[X?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ps,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function JQe({template:t,onClose:e}){const n=tn(),r=w.useRef(null),[a,s]=w.useState(t.title_template),[o,l]=w.useState(t.body_template),[c,u]=w.useState(null),[d,h]=w.useState(!0),{data:f}=Je({queryKey:["template-variables"],queryFn:ne.getTemplateVariables}),p=f?.find(A=>A.event_type===t.event_type),{data:x,isLoading:v}=Je({queryKey:["template-preview",t.event_type,a,o],queryFn:()=>ne.previewTemplate({event_type:t.event_type,title_template:a,body_template:o}),enabled:d&&a.length>0&&o.length>0});w.useEffect(()=>{const A=M=>{M.key==="Escape"&&e()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[e]);const g=ot({mutationFn:A=>ne.updateNotificationTemplate(t.id,A),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:A=>{u(A.message)}}),y=ot({mutationFn:()=>ne.resetNotificationTemplate(t.id),onSuccess:A=>{s(A.title_template),l(A.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:A=>{u(A.message)}}),_=A=>{if(A.preventDefault(),u(null),!a.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}g.mutate({title_template:a,body_template:o})},N=A=>{const M=r.current;if(!M)return;const C=M.selectionStart,j=M.selectionEnd,P=o,E=P.substring(0,C),B=P.substring(j),O=E+`{${A}}`+B;l(O),setTimeout(()=>{M.focus();const U=C+A.length+2;M.setSelectionRange(U,U)},0)},k=a!==t.title_template||o!==t.body_template;return i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("form",{onSubmit:_,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),i.jsx("input",{type:"text",value:a,onChange:A=>s(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:"Notification title..."})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),i.jsx("textarea",{ref:r,value:o,onChange:A=>l(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:"Notification body..."})]}),p&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:p.variables.map(A=>i.jsxs("button",{type:"button",onClick:()=>N(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:[i.jsx(Xn,{className:"w-3 h-3"}),A]},A))}),i.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[i.jsx(Ql,{className:"w-4 h-4"}),"Live Preview"]}),i.jsx("button",{type:"button",onClick:()=>h(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&i.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:v?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):x?i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),i.jsx("div",{className:"text-white font-medium",children:x.title})]}),i.jsxs("div",{children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),i.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:x.body})]})]}):i.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[i.jsxs(Ce,{type:"button",variant:"ghost",onClick:()=>y.mutate(),disabled:y.isPending,className:"text-orange-400 hover:text-orange-300",children:[y.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(Fo,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),i.jsxs(Ce,{onClick:_,disabled:g.isPending||!k,children:[g.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(ps,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const eZe={print_start:"Print Started",print_complete:"Print Complete",print_failed:"Print Failed",print_stopped:"Print Stopped",print_progress:"Progress",printer_offline:"Printer Offline",printer_error:"Printer Error",filament_low:"Low Filament",maintenance_due:"Maintenance Due",test:"Test"},tZe={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 nZe({onClose:t}){const e=tn(),{showToast:n}=cn(),[r,a]=w.useState(7),[s,o]=w.useState(null),[l,c]=w.useState(!1),{data:u}=Je({queryKey:["settings"],queryFn:ne.getSettings}),d=u?.time_format||"system",{data:h,isLoading:f,refetch:p,isRefetching:x}=Je({queryKey:["notification-logs",r,l],queryFn:()=>ne.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:v}=Je({queryKey:["notification-log-stats",r],queryFn:()=>ne.getNotificationLogStats(r)}),g=ot({mutationFn:()=>ne.clearNotificationLogs(30),onSuccess:_=>{n(_.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:_=>{n(`Failed to clear logs: ${_.message}`,"error")}}),y=_=>{const N=di(_);if(!N)return"";const A=new Date().getTime()-N.getTime();return A<6e4?"Just now":A<36e5?`${Math.floor(A/6e4)}m ago`:A<864e5?`${Math.floor(A/36e5)}h ago`:N.toLocaleDateString()+" "+pge(N,d)};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.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:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(mv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),v&&i.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:i.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[i.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",i.jsx("span",{className:"text-white font-medium",children:v.total})," notifications"]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[i.jsx(pr,{className:"w-4 h-4"}),v.success_count," sent"]}),v.failure_count>0&&i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(hi,{className:"w-4 h-4"}),v.failure_count," failed"]})]})}),i.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[i.jsxs("select",{value:r,onChange:_=>a(Number(_.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:[i.jsx("option",{value:1,children:"Last 24 hours"}),i.jsx("option",{value:7,children:"Last 7 days"}),i.jsx("option",{value:30,children:"Last 30 days"}),i.jsx("option",{value:90,children:"Last 90 days"})]}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:l,onChange:_=>c(_.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),"Show failed only"]}),i.jsx("div",{className:"flex-1"}),i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>p(),disabled:x,children:[x?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),"Refresh"]}),i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>g.mutate(),disabled:g.isPending,className:"text-red-400 hover:text-red-300",children:[g.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),"Clear Old"]})]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):h&&h.length>0?i.jsx("div",{className:"space-y-2",children:h.map(_=>i.jsx(rZe,{log:_,isExpanded:s===_.id,onToggle:()=>o(s===_.id?null:_.id),formatDate:y,formatFullDate:N=>jf(N,d)},_.id))}):i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(mv,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function rZe({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:a}){return i.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:[i.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?i.jsx(pr,{className:"w-4 h-4 text-bambu-green shrink-0"}):i.jsx(hi,{className:"w-4 h-4 text-red-400 shrink-0"}),i.jsx("span",{className:`text-xs font-medium ${tZe[t.event_type]||"text-bambu-gray"}`,children:eZe[t.event_type]||t.event_type}),i.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&i.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),i.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?i.jsx(yl,{className:"w-4 h-4 text-bambu-gray shrink-0"}):i.jsx(Un,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&i.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),i.jsx("p",{className:"text-sm text-white",children:t.title})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),i.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),i.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),i.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[i.jsxs("span",{children:["Provider: ",t.provider_type]}),i.jsxs("span",{children:["Time: ",a(t.created_at)]})]})]})]})}function aZe({formData:t,setFormData:e,groups:n,onClose:r,onCreate:a,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Ut();w.useEffect(()=>{const u=d=>{d.key==="Escape"&&r()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r]);const c=u=>{e({...t,group_ids:t.group_ids.includes(u)?t.group_ids.filter(d=>d!==u):[...t.group_ids,u]})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:i.jsxs(vt,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex flex-col gap-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(hh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),i.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:r,children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"text",value:t.username,onChange:u=>e({...t,username:u.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})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"email",value:t.email,onChange:u=>e({...t,email:u.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})]}),i.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:i.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."})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),i.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(u=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:t.group_ids.includes(u.id),onChange:()=>c(u.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:u.name}),u.is_system&&i.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},u.id)),n.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),i.jsx(Ce,{onClick:a,disabled:o,children:s?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):i.jsxs(i.Fragment,{children:[i.jsx(Xn,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function iZe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),[r,a]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[u,d]=w.useState(!1),[h,f]=w.useState(!0),[p,x]=w.useState("all"),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),{data:A,isLoading:M}=Je({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings}),{data:C,isLoading:j,refetch:P}=Je({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,refetchInterval:3e4}),{data:E}=Je({queryKey:["printers"],queryFn:ne.getPrinters});w.useEffect(()=>{A&&(a(A.spoolman_enabled==="true"),o(A.spoolman_url||""),c(A.spoolman_sync_mode||"auto"),d(A.spoolman_disable_weight_sync==="true"),f(A.spoolman_report_partial_usage!=="false"),g(!0))},[A]),w.useEffect(()=>{if(!v||!A)return;if(A.spoolman_enabled==="true"!==r||(A.spoolman_url||"")!==s||(A.spoolman_sync_mode||"auto")!==l||A.spoolman_disable_weight_sync==="true"!==u||A.spoolman_report_partial_usage!=="false"!==h){const W=setTimeout(()=>{B.mutate()},500);return()=>clearTimeout(W)}},[r,s,l,u,h,v]);const B=ot({mutationFn:()=>ne.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:u?"true":"false",spoolman_report_partial_usage:h?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),n(t("settings.toast.settingsSaved"))}}),O=ot({mutationFn:ne.connectSpoolman,onSuccess:()=>{P()}}),U=ot({mutationFn:ne.disconnectSpoolman,onSuccess:()=>{P()}}),R=ot({mutationFn:ne.syncAllPrintersAms,onSuccess:$=>{$.success}}),V=ot({mutationFn:$=>ne.syncPrinterAms($),onSuccess:$=>{$.success}}),G=()=>{p==="all"?R.mutate():V.mutate(p)},z=ot({mutationFn:ne.syncWeightsFromAms,onSuccess:$=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("settings.amsSyncSuccess",{synced:$.synced,skipped:$.skipped}),"success"),k(!1)},onError:()=>{n(t("settings.amsSyncError"),"error"),k(!1)}}),K=R.isPending||V.isPending,Y=p==="all"?R.data:V.data,ae=p==="all"?R.isSuccess:V.isSuccess;return M?i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pc,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),i.jsx(_t,{children:i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pc,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),B.isPending&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>a(!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:[i.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[i.jsx(fi,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),i.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),i.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&i.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[i.jsx(ra,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),i.jsxs("button",{type:"button",onClick:()=>a(!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:[i.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[i.jsx(Kr,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),i.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&i.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[i.jsx(ra,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[i.jsx("li",{children:t("settings.builtInFeatureRfid")}),i.jsx("li",{children:t("settings.builtInFeatureUsage")}),i.jsx("li",{children:t("settings.builtInFeatureCatalog")}),i.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>k(!0),disabled:z.isPending,children:[z.isPending?i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs text-blue-300",children:[i.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),i.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[i.jsx("li",{children:t("settings.syncInfoRfidOnly")}),i.jsx("li",{children:t("settings.syncInfoAutoCreate")}),i.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),i.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),i.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),i.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:$=>o($.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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),i.jsxs("select",{value:l,onChange:$=>c($.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:[i.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),i.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:u,onChange:$=>d($.target.checked),className:"sr-only peer"}),i.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"})]})]}),u&&i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:h,onChange:$=>f($.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),j?i.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):C?.connected?i.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[i.jsx(ra,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):i.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[i.jsx(Ft,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),i.jsx("div",{className:"flex gap-2",children:C?.connected?i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:[U.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx($me,{className:"w-4 h-4"}),t("settings.disconnect")]}):i.jsxs(Ce,{size:"sm",onClick:()=>O.mutate(),disabled:O.isPending||!s,children:[O.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Eh,{className:"w-4 h-4"}),t("settings.connect")]})})]}),O.isError&&i.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:O.error.message}),C?.connected&&i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsxs("select",{value:p,onChange:$=>x($.target.value==="all"?"all":Number($.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:[i.jsx("option",{value:"all",children:t("settings.allPrinters")}),E?.map($=>i.jsx("option",{value:$.id,children:$.name},$.id))]}),i.jsx(Un,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:G,disabled:K,children:[K?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),ae&&Y&&i.jsxs("div",{className:"mt-3 space-y-2",children:[i.jsx("div",{className:`p-2 rounded text-sm ${Y.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:Y.success?`Synced ${Y.synced_count} spool${Y.synced_count!==1?"s":""} successfully`:`Synced ${Y.synced_count} spool${Y.synced_count!==1?"s":""} with ${Y.errors.length} error${Y.errors.length!==1?"s":""}`}),Y.skipped_count>0&&i.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[i.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{className:"font-medium",children:[Y.skipped_count," spool",Y.skipped_count!==1?"s":""," skipped"]})]}),Y.skipped_count>5&&i.jsx("button",{onClick:()=>_(!y),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:y?"Show less":"Show all"})]}),i.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(y?Y.skipped:Y.skipped.slice(0,5)).map(($,W)=>i.jsxs("li",{className:"flex items-center gap-2",children:[$.color&&i.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${$.color}`}}),i.jsx("span",{children:$.location}),i.jsxs("span",{className:"text-amber-300/60",children:["- ",$.reason]})]},W)),!y&&Y.skipped_count>5&&i.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",Y.skipped_count-5," more"]})]})]}),Y.errors.length>0&&i.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[i.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),i.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:Y.errors.map(($,W)=>i.jsx("li",{children:$},W))})]})]})]})]})]}),N&&i.jsx(gn,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:z.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>z.mutate(),onCancel:()=>k(!1)})]})}function sZe(){const{t}=Ut(),{showToast:e}=cn(),[n,r]=w.useState([]),[a,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,g]=w.useState(""),[y,_]=w.useState(!1),[N,k]=w.useState(null),[A,M]=w.useState(!1),C=w.useCallback(async()=>{try{const z=await ne.getSpoolCatalog();r(z)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{C()},[C]);const j=n.filter(z=>z.name.toLowerCase().includes(o.toLowerCase())),P=async()=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const z=await ne.addCatalogEntry({name:p.trim(),weight:parseInt(v)});r(K=>[...K,z].sort((Y,ae)=>Y.name.localeCompare(ae.name))),d(!1),x(""),g(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{_(!1)}},E=z=>{f(z.id),x(z.name),g(z.weight.toString())},B=()=>{f(null),x(""),g("")},O=async z=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}_(!0);try{const K=await ne.updateCatalogEntry(z,{name:p.trim(),weight:parseInt(v)});r(Y=>Y.map(ae=>ae.id===z?K:ae).sort((ae,$)=>ae.name.localeCompare($.name))),f(null),x(""),g(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{_(!1)}},U=async()=>{if(N)try{await ne.deleteCatalogEntry(N.id),r(z=>z.filter(K=>K.id!==N.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{k(null)}},R=async()=>{M(!1),s(!0);try{await ne.resetSpoolCatalog(),await C(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},V=()=>{const z=n.map(({name:$,weight:W})=>({name:$,weight:W})),K=new Blob([JSON.stringify(z,null,2)],{type:"application/json"}),Y=URL.createObjectURL(K),ae=document.createElement("a");ae.href=Y,ae.download="spool-catalog.json",document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(Y),e(t("settings.catalog.exported",{count:n.length}),"success")},G=async z=>{const K=z.target.files?.[0];if(K){try{const Y=await K.text(),ae=JSON.parse(Y);if(!Array.isArray(ae))throw new Error("Invalid format");let $=0,W=0;for(const ee of ae){if(!ee.name||typeof ee.weight!="number"){W++;continue}if(n.some(ye=>ye.name.toLowerCase()===ee.name.toLowerCase())){W++;continue}try{const ye=await ne.addCatalogEntry({name:ee.name,weight:ee.weight});r(me=>[...me,ye].sort((te,je)=>te.name.localeCompare(je.name))),$++}catch{W++}}e(t("settings.catalog.imported",{added:$,skipped:W}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return i.jsxs(vt,{children:[i.jsxs(In,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(Pc,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("button",{onClick:V,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:[i.jsx(ua,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),i.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:[i.jsx(Ra,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),i.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:G}),i.jsxs("button",{onClick:()=>M(!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:[i.jsx(Fo,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),i.jsxs("button",{onClick:()=>d(!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:[i.jsx(Xn,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.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:z=>l(z.target.value)})]}),u&&i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsx("div",{className:"flex-1 min-w-0",children:i.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:p,onChange:z=>x(z.target.value)})}),i.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:z=>g(z.target.value)}),i.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),i.jsxs("button",{onClick:P,disabled:y,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:[y?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ra,{className:"w-4 h-4"}),t("common.add")]}),i.jsx("button",{onClick:()=>{d(!1),x(""),g("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:i.jsx(Ft,{className:"w-4 h-4"})})]})]}),a?i.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[i.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):i.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),i.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),i.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),i.jsx("th",{className:"px-4 py-2 w-24"})]})}),i.jsx("tbody",{children:j.length===0?i.jsx("tr",{children:i.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):j.map(z=>i.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:h===z.id?i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-4 py-2",children:i.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:p,onChange:K=>x(K.target.value)})}),i.jsx("td",{className:"px-4 py-2",children:i.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:K=>g(K.target.value)})}),i.jsx("td",{className:"px-4 py-2 text-center",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),i.jsx("td",{className:"px-4 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>O(z.id),disabled:y,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:y?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ra,{className:"w-4 h-4"})}),i.jsx("button",{onClick:B,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(Ft,{className:"w-4 h-4"})})]})})]}):i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-4 py-2 text-white",children:z.name}),i.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[z.weight,"g"]}),i.jsx("td",{className:"px-4 py-2 text-center",children:z.is_default?i.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),i.jsx("td",{className:"px-4 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>E(z),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>k(z),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]})},z.id))})]})})]}),N&&i.jsx(gn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:N.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:U,onCancel:()=>k(null)}),A&&i.jsx(gn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:R,onCancel:()=>M(!1)})]})}function oZe(){const{t}=Ut(),{showToast:e}=cn(),[n,r]=w.useState([]),[a,s]=w.useState(!0),[o,l]=w.useState(""),[c,u]=w.useState("Bambu Lab"),d=w.useRef(null),[h,f]=w.useState(!1),[p,x]=w.useState(null),[v,g]=w.useState(""),[y,_]=w.useState(""),[N,k]=w.useState("#FFFFFF"),[A,M]=w.useState(""),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[B,O]=w.useState(null),[U,R]=w.useState(null),[V,G]=w.useState(!1),z=w.useCallback(async()=>{try{const oe=await ne.getColorCatalog();r(oe)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{z()},[z]);const K=[...new Set(n.map(oe=>oe.manufacturer))].sort(),Y=n.filter(oe=>{const _e=o===""||oe.manufacturer.toLowerCase().includes(o.toLowerCase())||oe.color_name.toLowerCase().includes(o.toLowerCase())||(oe.material?.toLowerCase().includes(o.toLowerCase())??!1),se=c===""||oe.manufacturer===c;return _e&&se}),ae=()=>{g(""),_(""),k("#FFFFFF"),M("")},$=async()=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const oe=await ne.addColorEntry({manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:A.trim()||null});r(_e=>[..._e,oe].sort((se,Oe)=>se.manufacturer.localeCompare(Oe.manufacturer)||(se.material||"").localeCompare(Oe.material||"")||se.color_name.localeCompare(Oe.color_name))),f(!1),ae(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{j(!1)}},W=oe=>{x(oe.id),g(oe.manufacturer),_(oe.color_name),k(oe.hex_color),M(oe.material||"")},ee=()=>{x(null),ae()},J=async oe=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const _e=await ne.updateColorEntry(oe,{manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:A.trim()||null});r(se=>se.map(Oe=>Oe.id===oe?_e:Oe).sort((Oe,q)=>Oe.manufacturer.localeCompare(q.manufacturer)||(Oe.material||"").localeCompare(q.material||"")||Oe.color_name.localeCompare(q.color_name))),x(null),ae(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{j(!1)}},ye=async()=>{if(U)try{await ne.deleteColorEntry(U.id),r(oe=>oe.filter(_e=>_e.id!==U.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{R(null)}},me=async()=>{G(!1),s(!0);try{await ne.resetColorCatalog(),await z(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},te=async()=>{E(!0),O(null);try{const oe={},_e=nd();_e&&(oe.Authorization=`Bearer ${_e}`);const se=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:oe});if(!se.ok)throw new Error("Failed to start sync");const Oe=se.body?.getReader();if(!Oe)throw new Error("No response body");const q=new TextDecoder;let X="";for(;;){const{done:de,value:Z}=await Oe.read();if(de)break;X+=q.decode(Z,{stream:!0});const ie=X.split(` -`);X=ie.pop()||"";for(const le of ie)if(le.startsWith("data: "))try{const Fe=JSON.parse(le.slice(6));Fe.type==="progress"?O({fetched:Fe.total_fetched,total:Fe.total_available}):Fe.type==="complete"?Fe.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:Fe.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:Fe.added,skipped:Fe.skipped}),"success"):Fe.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${Fe.error}`,"error")}catch{}}await z()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{E(!1),O(null)}},je=()=>{const oe=n.map(({manufacturer:q,color_name:X,hex_color:de,material:Z})=>({manufacturer:q,color_name:X,hex_color:de,material:Z})),_e=new Blob([JSON.stringify(oe,null,2)],{type:"application/json"}),se=URL.createObjectURL(_e),Oe=document.createElement("a");Oe.href=se,Oe.download="color-catalog.json",document.body.appendChild(Oe),Oe.click(),document.body.removeChild(Oe),URL.revokeObjectURL(se),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},ue=async oe=>{const _e=oe.target.files?.[0];if(_e){try{const se=await _e.text(),Oe=JSON.parse(se);if(!Array.isArray(Oe))throw new Error("Invalid format");let q=0,X=0;for(const de of Oe){if(!de.manufacturer||!de.color_name||!de.hex_color){X++;continue}if(n.some(ie=>ie.manufacturer.toLowerCase()===de.manufacturer.toLowerCase()&&ie.color_name.toLowerCase()===de.color_name.toLowerCase()&&(ie.material||"").toLowerCase()===(de.material||"").toLowerCase())){X++;continue}try{const ie=await ne.addColorEntry({manufacturer:de.manufacturer,color_name:de.color_name,hex_color:de.hex_color,material:de.material||null});r(le=>[...le,ie].sort((Fe,pe)=>Fe.manufacturer.localeCompare(pe.manufacturer)||(Fe.material||"").localeCompare(pe.material||"")||Fe.color_name.localeCompare(pe.color_name))),q++}catch{X++}}e(t("settings.colorCatalog.imported",{added:q,skipped:X}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}d.current&&(d.current.value="")}};return i.jsxs(vt,{children:[i.jsxs(In,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(VC,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("button",{onClick:je,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:[i.jsx(ua,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),i.jsxs("button",{onClick:()=>d.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:[i.jsx(Ra,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),i.jsx("input",{ref:d,type:"file",accept:".json",className:"hidden",onChange:ue}),i.jsxs("button",{onClick:te,disabled:P,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:[P?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(zb,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:P?B?`${Math.min(B.fetched,B.total)} / ${B.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),i.jsxs("button",{onClick:()=>G(!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:[i.jsx(Fo,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),i.jsxs("button",{onClick:()=>f(!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:[i.jsx(Xn,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),i.jsxs("div",{className:"flex gap-2 flex-wrap",children:[i.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.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:oe=>l(oe.target.value)})]}),i.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:oe=>u(oe.target.value),children:[i.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),K.map(oe=>i.jsx("option",{value:oe,children:oe},oe))]})]}),h&&i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),i.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[i.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:oe=>g(oe.target.value)}),i.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:y,onChange:oe=>_(oe.target.value)}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:oe=>k(oe.target.value)}),i.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:N,onChange:oe=>k(oe.target.value)})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.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:A,onChange:oe=>M(oe.target.value)}),i.jsxs("button",{onClick:$,disabled:C,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:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ra,{className:"w-4 h-4"}),t("common.add")]}),i.jsx("button",{onClick:()=>{f(!1),ae()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:i.jsx(Ft,{className:"w-4 h-4"})})]})]})]}),(o||c)&&i.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:Y.length,total:n.length})}),a?i.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[i.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):i.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),i.jsx("th",{className:"px-3 py-2 w-16"})]})}),i.jsx("tbody",{children:Y.length===0?i.jsx("tr",{children:i.jsx("td",{colSpan:6,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):Y.map(oe=>i.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:p===oe.id?i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-3 py-2",children:i.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:_e=>k(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:_e=>g(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:A,onChange:_e=>M(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:y,onChange:_e=>_(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:_e=>k(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>J(oe.id),disabled:C,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ra,{className:"w-4 h-4"})}),i.jsx("button",{onClick:ee,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(Ft,{className:"w-4 h-4"})})]})})]}):i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-3 py-2",children:i.jsx("div",{className:"w-8 h-8 rounded border border-bambu-dark-tertiary",style:{backgroundColor:oe.hex_color},title:oe.hex_color})}),i.jsx("td",{className:"px-3 py-2 text-white",children:oe.manufacturer}),i.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:oe.material||"-"}),i.jsx("td",{className:"px-3 py-2 text-white",children:oe.color_name}),i.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:oe.hex_color}),i.jsx("td",{className:"px-3 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>W(oe),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>R(oe),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]})},oe.id))})]})})]}),U&&i.jsx(gn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${U.manufacturer} - ${U.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:ye,onCancel:()=>R(null)}),V&&i.jsx(gn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:me,onCancel:()=>G(!1)})]})}function lZe({link:t,onClose:e}){const{t:n}=Ut(),r=tn(),a=!!t,s=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.url||""),[d,h]=w.useState(t?.icon||"link"),[f,p]=w.useState(t?.open_in_new_tab||!1),[x,v]=w.useState(!!t?.custom_icon),[g,y]=w.useState(t?.custom_icon?ne.getExternalLinkIconUrl(t.id):null),[_,N]=w.useState(null),[k,A]=w.useState(null);w.useEffect(()=>{const U=R=>{R.key==="Escape"&&e()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[e]);const M=ot({mutationFn:async U=>{const R=await ne.createExternalLink(U);return _?await ne.uploadExternalLinkIcon(R.id,_):R},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{A(U.message)}}),C=ot({mutationFn:async U=>{let R=await ne.updateExternalLink(t.id,U);return _?R=await ne.uploadExternalLinkIcon(t.id,_):!x&&t?.custom_icon&&(R=await ne.deleteExternalLinkIcon(t.id)),R},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{A(U.message)}}),j=U=>{const R=U.target.files?.[0];if(R){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(R.type)){A("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(R.size>1024*1024){A("Image file must be less than 1MB");return}N(R),v(!0);const G=new FileReader;G.onload=z=>{y(z.target?.result)},G.readAsDataURL(R)}},P=()=>{N(null),y(null),v(!1),s.current&&(s.current.value="")},E=U=>{if(U.preventDefault(),A(null),!o.trim()){A("Name is required");return}if(!c.trim()){A("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){A("URL must start with http:// or https://");return}const R={name:o.trim(),url:c.trim(),icon:d,open_in_new_tab:f};a?C.mutate(R):M.mutate(R)},B=M.isPending||C.isPending,O=QC(d);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:U=>U.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:x&&g?i.jsx("img",{src:g,alt:"",className:"w-5 h-5 rounded"}):i.jsx(O,{className:"w-5 h-5"})}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a?"Edit Link":"Add External Link"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:E,className:"p-6 space-y-4",children:[k&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:k}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),i.jsx("input",{type:"text",value:o,onChange:U=>l(U.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),i.jsx("input",{type:"text",value:c,onChange:U=>u(U.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"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),i.jsx("button",{type:"button",onClick:()=>p(!f),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${f?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${f?"translate-x-6":"translate-x-1"}`})})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),i.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),i.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:j}),x&&g?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("img",{src:g,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:P,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:i.jsx(Jt,{className:"w-4 h-4"})})]}):i.jsxs(Ce,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[i.jsx(Ra,{className:"w-4 h-4"}),"Upload"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!x&&i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),i.jsx(nge,{value:d,onChange:h})]})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),i.jsxs(Ce,{type:"submit",disabled:B,className:"flex-1",children:[B?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ps,{className:"w-4 h-4"}),a?"Save":"Add"]})]})]})]})})}function cZe(){const{t}=Ut(),e=tn(),[n,r]=w.useState(!1),[a,s]=w.useState(null),[o,l]=w.useState(null),[c,u]=w.useState(null),{data:d,isLoading:h}=Je({queryKey:["external-links"],queryFn:ne.getExternalLinks}),f=ot({mutationFn:N=>ne.deleteExternalLink(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),p=ot({mutationFn:N=>ne.reorderExternalLinks(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),x=(N,k)=>{u(k),N.dataTransfer.effectAllowed="move"},v=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},g=(N,k)=>{if(N.preventDefault(),c===null||c===k||!d)return;const A=d.map(P=>P.id),M=A.indexOf(c),C=A.indexOf(k);if(M===-1||C===-1)return;const j=[...A];j.splice(M,1),j.splice(C,0,c),p.mutate(j),u(null)},y=N=>{l(N)},_=()=>{o&&(f.mutate(o.id),l(null))};return i.jsxs(i.Fragment,{children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Eh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),i.jsxs(Ce,{size:"sm",onClick:()=>r(!0),children:[i.jsx(Xn,{className:"w-4 h-4"}),"Add Link"]})]})}),i.jsxs(_t,{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),h?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):d&&d.length>0?i.jsx("div",{className:"space-y-2",children:d.map(N=>{const k=QC(N.icon);return i.jsxs("div",{draggable:!0,onDragStart:A=>x(A,N.id),onDragOver:v,onDrop:A=>g(A,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===N.id?"opacity-50":""}`,children:[i.jsx(Ph,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(k,{className:"w-4 h-4"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-white font-medium truncate",children:N.name}),i.jsx(Kr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),i.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[i.jsx("button",{onClick:()=>s(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>y(N),disabled:f.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:i.jsx(Jt,{className:"w-4 h-4"})})]})]},N.id)})}):i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Eh,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:t("externalLinks.noLinksConfigured")}),i.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||a)&&i.jsx(lZe,{link:a,onClose:()=>{r(!1),s(null)}}),o&&i.jsx(gn,{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 _j={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function uZe({printer:t,models:e}){const{t:n}=Ut(),r=tn(),{showToast:a}=cn(),[s,o]=w.useState(!0),[l,c]=w.useState(t.enabled),[u,d]=w.useState(t.name),[h,f]=w.useState(""),[p,x]=w.useState(t.mode==="queue"?"review":t.mode),[v,g]=w.useState(t.target_printer_id),[y,_]=w.useState(t.bind_ip||""),[N,k]=w.useState(t.remote_interface_ip||""),[A,M]=w.useState(t.model||""),[C,j]=w.useState(!1),[P,E]=w.useState(null),[B,O]=w.useState(!1);w.useEffect(()=>{P||(c(t.enabled),x(t.mode==="queue"?"review":t.mode),d(t.name),g(t.target_printer_id),_(t.bind_ip||""),k(t.remote_interface_ip||""),M(t.model||""))},[t,P]);const{data:U}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:R}=Je({queryKey:["network-interfaces"],queryFn:()=>ne.getNetworkInterfaces().then(te=>te.interfaces)}),V=ot({mutationFn:te=>w1.update(t.id,te),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),a(n("virtualPrinter.toast.updated")),E(null)},onError:te=>{a(te.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),x(t.mode==="queue"?"review":t.mode),g(t.target_printer_id),_(t.bind_ip||""),E(null)}}),G=ot({mutationFn:()=>w1.remove(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),a(n("virtualPrinter.toast.deleted")),O(!1)},onError:te=>{a(te.message||n("virtualPrinter.toast.failedToDelete"),"error"),O(!1)}}),z=te=>{te.stopPropagation();const je=!l;if(je){if(!y){a(n("virtualPrinter.toast.bindIpRequired"),"error");return}if(p==="proxy"){if(!v){a(n("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!h&&!t.access_code_set){a(n("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(je),E("toggle"),V.mutate({enabled:je})},K=()=>{u.trim()&&(E("name"),V.mutate({name:u.trim()}))},Y=()=>{if(!h){a(n("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(h.length!==8){a(n("virtualPrinter.toast.accessCodeLength"),"error");return}E("accessCode"),V.mutate({access_code:h}),f("")},ae=te=>{x(te),E("mode"),V.mutate({mode:te})},$=te=>{M(te),E("model"),V.mutate({model:te})},W=te=>{g(te),E("targetPrinter"),V.mutate({target_printer_id:te})},ee=te=>{k(te),E("remoteInterface"),V.mutate({remote_interface_ip:te})},J=t.status?.running||!1,ye=n(`virtualPrinter.mode.${_j[p]||"archive"}`),me=U?.find(te=>te.id===v)?.name;return i.jsxs(i.Fragment,{children:[i.jsxs(vt,{children:[i.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[i.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?i.jsx(Un,{className:"w-4 h-4"}):i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${J?"bg-green-400 animate-pulse":"bg-gray-500"}`}),i.jsx("span",{className:"text-white font-medium truncate",children:t.name}),i.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:ye}),t.model_name&&i.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),me&&i.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[p==="proxy"&&i.jsx(Yj,{className:"w-3 h-3 inline mr-1"}),me]}),y&&i.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:y}),N&&i.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:N}),i.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:te=>te.stopPropagation(),children:i.jsx("button",{onClick:z,disabled:P==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${P==="toggle"?"opacity-50":""}`,children:i.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&&i.jsxs(_t,{className:"pt-0 space-y-4",children:[i.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"text",value:u,onChange:te=>d(te.target.value),onBlur:K,onKeyDown:te=>te.key==="Enter"&&K(),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"}),i.jsx("span",{className:"text-xs text-bambu-gray font-mono",children:t.serial}),i.jsx("button",{onClick:()=>O(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.mode.title")}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(te=>i.jsxs("button",{onClick:()=>ae(te),disabled:P==="mode",className:`p-2 rounded-lg border text-left transition-colors ${p===te?te==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[te==="proxy"&&i.jsx(Yj,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${_j[te]}`)]}),i.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${_j[te]}Desc`)})]},te))})]}),p!=="proxy"&&i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.model.title")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("virtualPrinter.model.description")}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:A,onChange:te=>$(te.target.value),disabled:P==="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(([te,je])=>i.jsxs("option",{value:te,children:[je," (",te,")"]},te))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),p==="proxy"&&i.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("virtualPrinter.proxy.accessCodeHint")})]})}),p!=="proxy"&&i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.accessCode.title")}),t.access_code_set?i.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[i.jsx(ra,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.isSet")]}):i.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[i.jsx(Tn,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.notSet")]})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:C?"text":"password",value:h,onChange:te=>f(te.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"}),i.jsx("button",{onClick:()=>j(!C),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:C?i.jsx(o0,{className:"w-4 h-4"}):i.jsx(Ql,{className:"w-4 h-4"})})]}),i.jsx(Ce,{onClick:Y,disabled:!h||P==="accessCode",variant:"primary",children:P==="accessCode"?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("common.save")})]}),h&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i.jsx("span",{className:h.length===8?"text-green-400":"text-yellow-400",children:n("virtualPrinter.accessCode.charCount",{count:h.length})})})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.targetPrinter.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:v??"",onChange:te=>{const je=parseInt(te.target.value,10);isNaN(je)||W(je)},disabled:P==="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:[i.jsx("option",{value:"",children:n("virtualPrinter.targetPrinter.placeholder")}),U?.map(te=>i.jsxs("option",{value:te.id,children:[te.name," (",te.ip_address,")"]},te.id))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.bindIp.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:y,onChange:te=>{_(te.target.value),E("bindIp"),V.mutate({bind_ip:te.target.value})},disabled:P==="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:[i.jsx("option",{value:"",children:n("virtualPrinter.bindIp.placeholder")}),R?.map(te=>i.jsxs("option",{value:te.ip,children:[te.name," (",te.ip,")",te.is_alias?" [alias]":""," - ",te.subnet]},te.ip))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("virtualPrinter.bindIp.hint")})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.remoteInterface.title")}),N?i.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:i.jsx(ra,{className:"w-3 h-3"})}):i.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:n("virtualPrinter.remoteInterface.optional"),children:i.jsx(Zs,{className:"w-3 h-3"})})]}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:N,onChange:te=>ee(te.target.value),disabled:P==="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:[i.jsx("option",{value:"",children:n("virtualPrinter.remoteInterface.placeholder")}),R?.map(te=>i.jsxs("option",{value:te.ip,children:[te.name," (",te.ip,") - ",te.subnet]},te.ip))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),B&&i.jsx(gn,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:G.isPending,onConfirm:()=>G.mutate(),onCancel:()=>O(!1)})]})}const XW={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function dZe({onClose:t}){const{t:e}=Ut(),n=tn(),{showToast:r}=cn(),[a,s]=w.useState(""),[o,l]=w.useState("immediate"),[c,u]=w.useState(null),{data:d}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),h=ot({mutationFn:()=>w1.create({name:a.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:f=>{r(f.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:i.jsx(vt,{className:"w-full max-w-md",onClick:f=>f.stopPropagation(),children:i.jsxs(_t,{className:"p-6 space-y-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),i.jsx("input",{type:"text",value:a,onChange:f=>s(f.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})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(f=>i.jsxs("button",{onClick:()=>l(f),className:`p-2 rounded-lg border text-left transition-colors ${o===f?f==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[f==="proxy"&&i.jsx(Yj,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${XW[f]}`)]}),i.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${XW[f]}Desc`)})]},f))})]}),o==="proxy"&&i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:c??"",onChange:f=>{const p=parseInt(f.target.value,10);u(isNaN(p)?null:p)},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:[i.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),d?.map(f=>i.jsxs("option",{value:f.id,children:[f.name," (",f.ip_address,")"]},f.id))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",disabled:h.isPending,children:e("common.cancel")}),i.jsx(Ce,{variant:"primary",onClick:()=>h.mutate(),className:"flex-1",disabled:h.isPending,children:h.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function hZe(){const{t}=Ut(),[e,n]=w.useState(!1),{data:r,isLoading:a}=Je({queryKey:["virtual-printers"],queryFn:w1.list,refetchInterval:1e4});if(a)return i.jsx(vt,{children:i.jsx(_t,{className:"py-8 flex justify-center",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const s=r?.printers||[],o=r?.models||{};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4 items-stretch",children:[i.jsx(vt,{className:"border-l-4 border-l-yellow-500",children:i.jsx(_t,{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs",children:[i.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),i.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:[i.jsx(Kr,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),i.jsx(vt,{className:"lg:col-span-3",children:i.jsx(_t,{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),i.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[i.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),i.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),i.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(xr,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s.length,")"]})]}),i.jsxs(Ce,{variant:"primary",onClick:()=>n(!0),children:[i.jsx(Xn,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),s.length===0?i.jsx(vt,{children:i.jsxs(_t,{className:"py-8 text-center",children:[i.jsx(xr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),i.jsxs(Ce,{variant:"primary",onClick:()=>n(!0),children:[i.jsx(Xn,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:s.map(l=>i.jsx(uZe,{printer:l,models:o},l.id))}),e&&i.jsx(dZe,{onClose:()=>n(!1)})]})}function YW({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:i.jsx(pr,{className:"w-3 h-3"}),failed:i.jsx(hi,{className:"w-3 h-3"}),skipped:i.jsx(NF,{className:"w-3 h-3"}),running:i.jsx(it,{className:"w-3 h-3 animate-spin"})};return i.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 mZe(t){return t?new Date(t).toLocaleString():"-"}function fZe(){const t=tn(),{showToast:e}=cn(),{t:n}=Ut(),[r,a]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[u,d]=w.useState(!1),[h,f]=w.useState("daily"),[p,x]=w.useState(!0),[v,g]=w.useState(!0),[y,_]=w.useState(!1),[N,k]=w.useState(!0),[A,M]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState(""),[B,O]=w.useState(!1),[U,R]=w.useState(null),[V,G]=w.useState(null),z=w.useRef(null);w.useEffect(()=>{if(A||C){const L=D=>(D.preventDefault(),D.returnValue="A backup operation is in progress. Are you sure you want to leave?",D.returnValue);return window.addEventListener("beforeunload",L),()=>window.removeEventListener("beforeunload",L)}},[A,C]);const[K,Y]=w.useState(!1),[ae,$]=w.useState(null),W=w.useRef(null),ee=w.useRef(!1),{data:J,isLoading:ye}=Je({queryKey:["github-backup-config"],queryFn:ne.getGitHubBackupConfig}),{data:me}=Je({queryKey:["github-backup-status"],queryFn:ne.getGitHubBackupStatus,refetchInterval:Q=>Q.state.data?.is_running?500:1e4}),{data:te}=Je({queryKey:["github-backup-logs"],queryFn:()=>ne.getGitHubBackupLogs(20)}),{data:je}=Je({queryKey:["cloud-status"],queryFn:ne.getCloudStatus}),{data:ue}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),oe=yF({queries:(ue??[]).map(Q=>({queryKey:["printerStatus",Q.id],queryFn:()=>ne.getPrinterStatus(Q.id),staleTime:1e4,refetchInterval:3e4}))}),_e=(ue??[]).map((Q,L)=>({printer:Q,connected:oe[L]?.data?.connected??!1})),se=_e.length,Oe=_e.filter(Q=>Q.connected).length,q=se>0&&Oe===0,X=Oe>0&&Oe{J&&(a(J.repository_url),c(J.branch),d(J.schedule_enabled),f(J.schedule_type),x(J.backup_kprofiles),g(J.backup_cloud_profiles),_(J.backup_settings),k(J.enabled),o(""),setTimeout(()=>{ee.current=!0},100))},[J]);const de=w.useCallback(async(Q=!1)=>{if(J?.has_token)try{Q&&s?(await ne.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),o(""),e("Token updated")):(await ne.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(L){e(`Failed to save: ${L.message}`,"error")}},[J?.has_token,r,s,l,u,h,p,v,y,N,t,e]);w.useEffect(()=>{if(!(!ee.current||!J?.has_token))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{de(!1)},500),()=>{W.current&&clearTimeout(W.current)}},[r,l,u,h,p,v,y,N,de,J?.has_token]),w.useEffect(()=>{if(!(!ee.current||!J?.has_token||!s))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{de(!0)},1e3),()=>{W.current&&clearTimeout(W.current)}},[s,de,J?.has_token]);const Z=ot({mutationFn:Q=>ne.saveGitHubBackupConfig(Q),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),o(""),ee.current=!0},onError:Q=>{e(`Failed to save: ${Q.message}`,"error")}}),ie=ot({mutationFn:ne.triggerGitHubBackup,onSuccess:Q=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),Q.success?Q.files_changed>0?e(`Backup complete - ${Q.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${Q.message}`,"error")},onError:Q=>{e(`Backup failed: ${Q.message}`,"error")}}),le=ot({mutationFn:()=>ne.clearGitHubBackupLogs(0),onSuccess:Q=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${Q.deleted} logs`)},onError:Q=>{e(`Failed to clear logs: ${Q.message}`,"error")}}),Fe=async()=>{Y(!0),$(null);try{let Q;if(s){if(!r){e("Enter repository URL","error"),Y(!1);return}Q=await ne.testGitHubConnection(r,s)}else if(J?.has_token)Q=await ne.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),Y(!1);return}$({success:Q.success,message:Q.message})}catch(Q){$({success:!1,message:Q.message})}finally{Y(!1)}},pe=()=>{if(!r){e("Repository URL is required","error");return}if(!s){e("Access token is required","error");return}Z.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N})};return ye?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(e3,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),J&&je?.is_authenticated&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),i.jsx(On,{checked:N,onChange:k})]})]})}),i.jsx(_t,{className:"space-y-4",children:je?.is_authenticated?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),i.jsx("input",{type:"text",value:r,onChange:Q=>{a(Q.target.value),$(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"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",J?.has_token&&i.jsx("span",{className:"text-green-400",children:"(saved)"})]}),i.jsx("input",{type:"password",value:s,onChange:Q=>{o(Q.target.value),$(null)},placeholder:J?.has_token?"Enter new token to update":"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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),i.jsx("input",{type:"text",value:l,onChange:Q=>c(Q.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),i.jsxs("select",{value:u?h:"disabled",onChange:Q=>{Q.target.value==="disabled"?d(!1):(d(!0),f(Q.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:[i.jsx("option",{value:"disabled",children:"Manual only"}),i.jsx("option",{value:"hourly",children:"Hourly"}),i.jsx("option",{value:"daily",children:"Daily"}),i.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:`flex items-start gap-2 ${q?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[i.jsx("input",{type:"checkbox",checked:p,onChange:Q=>x(Q.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:q}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`text-sm ${q?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),q&&i.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:[i.jsx(Tn,{className:"w-3 h-3"}),"No printers connected"]}),X&&i.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:[i.jsx(Tn,{className:"w-3 h-3"}),Oe,"/",se," connected"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:v,onChange:Q=>g(Q.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:!je?.is_authenticated}),i.jsxs("div",{children:[i.jsx("span",{className:`text-sm ${je?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:y,onChange:Q=>_(Q.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"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white text-sm",children:"App Settings"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (complete database)"})]})]})]})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[me?.configured&&i.jsxs("div",{className:"flex items-center justify-between text-sm",children:[i.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:me.last_backup_at?i.jsxs(i.Fragment,{children:[i.jsxs("span",{children:["Last backup: ",gv(me.last_backup_at,"system",n)]}),i.jsx(YW,{status:me.last_backup_status})]}):i.jsx("span",{children:"No backups yet"})}),me.next_scheduled_run&&i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx(Gn,{className:"w-3 h-3 inline mr-1"}),"Next: ",gv(me.next_scheduled_run,"system",n)]})]}),ae&&i.jsxs("div",{className:`text-sm flex items-center gap-1 ${ae.success?"text-green-400":"text-red-400"}`,children:[ae.success?i.jsx(pr,{className:"w-4 h-4"}):i.jsx(hi,{className:"w-4 h-4"}),ae.message]}),i.jsx("div",{className:"flex flex-wrap items-center gap-2",children:me?.configured?i.jsx(i.Fragment,{children:ie.isPending||me.is_running?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),i.jsx("span",{className:"text-sm",children:me.progress||"Starting backup..."})]}):i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"primary",size:"sm",onClick:()=>ie.mutate(),disabled:!J?.enabled,children:[i.jsx(io,{className:"w-4 h-4"}),"Backup Now"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Fe,disabled:K,children:[K?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),"Test"]})]})}):i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"primary",size:"sm",onClick:pe,disabled:Z.isPending||!r||!s,children:[Z.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(pr,{className:"w-4 h-4"}),"Enable Backup"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Fe,disabled:K||!r||!s,children:[K?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):i.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),te&&te.length>0&&i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mv,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>le.mutate(),disabled:le.isPending,children:[i.jsx(Jt,{className:"w-4 h-4"}),"Clear"]})]})}),i.jsx(_t,{children:i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),i.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),i.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),i.jsx("tbody",{children:te.slice(0,10).map(Q=>i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[i.jsx("td",{className:"py-2 px-2 text-white",children:mZe(Q.started_at)}),i.jsx("td",{className:"py-2 px-2",children:i.jsx(YW,{status:Q.status})}),i.jsx("td",{className:"py-2 px-2",children:Q.commit_sha?i.jsxs("a",{href:`${J?.repository_url}/commit/${Q.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[Q.commit_sha.substring(0,7),i.jsx(Kr,{className:"w-3 h-3"})]}):i.jsx("span",{className:"text-bambu-gray",children:"-"})})]},Q.id))})]})})})]})]}),i.jsx("div",{className:"space-y-6",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pc,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files."}),i.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Download Backup"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:A||C,onClick:async()=>{M(!0),E("Preparing backup...");try{E("Creating backup archive... This may take a while for large archives.");const{blob:Q,filename:L}=await ne.exportBackup();E("Downloading backup file...");const D=URL.createObjectURL(Q),H=document.createElement("a");H.href=D,H.download=L,H.click(),URL.revokeObjectURL(D),e("Backup downloaded successfully")}catch(Q){e(`Failed to create backup: ${Q instanceof Error?Q.message:"Unknown error"}`,"error")}finally{M(!1),E("")}},children:[i.jsx(ua,{className:"w-4 h-4"}),"Download"]})]}),i.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),i.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),i.jsx("input",{ref:z,type:"file",accept:".zip",className:"hidden",onChange:Q=>{const L=Q.target.files?.[0];L&&(R(L),O(!0)),Q.target.value=""}}),i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:C||A,onClick:()=>z.current?.click(),children:[i.jsx(Ra,{className:"w-4 h-4"}),"Restore"]})]}),V&&i.jsx("div",{className:`p-3 rounded-lg ${V.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[V.success?i.jsx(pr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):i.jsx(hi,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:V.success?"text-green-200":"text-red-200",children:[V.message,V.success&&i.jsx("div",{className:"mt-2",children:i.jsxs(Ce,{size:"sm",onClick:()=>window.location.reload(),children:[i.jsx(Fo,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),i.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-yellow-200",children:[i.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",i.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),B&&U&&i.jsx(gn,{title:"Restore Backup",message:`Are you sure you want to restore from "${U.name}"? This will completely replace your current database and all files. The application will need to be restarted after restore.`,confirmText:"Restore Backup",variant:"danger",onConfirm:async()=>{O(!1),j(!0),G(null);try{E("Uploading backup file...");const Q=await ne.importBackup(U);G(Q),Q.success?e("Backup restored. Please restart Bambuddy.","success"):e(Q.message,"error")}catch(Q){const L=Q instanceof Error?Q.message:"Failed to restore backup";G({success:!1,message:L}),e(L,"error")}finally{j(!1),E(""),R(null)}},onCancel:()=>{O(!1),R(null)}}),(A||C)&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:i.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:[i.jsx("div",{className:"flex justify-center mb-4",children:i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),i.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),i.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:A?"Creating Backup":"Restoring Backup"}),i.jsx("p",{className:"text-bambu-gray mb-4",children:P||(A?"Preparing...":"Processing...")}),i.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}const pZe={starttls:587,ssl:465,none:25},gZe={587:"starttls",465:"ssl",25:"none"};function bZe(){const{t}=Ut(),{showToast:e}=cn(),n=tn(),[r,a]=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}=Je({queryKey:["smtpSettings"],queryFn:()=>ne.getSMTPSettings()}),{data:u}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()});w.useEffect(()=>{l&&a({...l,smtp_password:""})},[l]);const d=M=>{a({...r,smtp_security:M,smtp_port:pZe[M]})},h=M=>{const C=gZe[M];a({...r,smtp_port:M,...C?{smtp_security:C}:{}})},f=M=>{a({...r,smtp_auth_enabled:M,...M?{}:{smtp_username:"",smtp_password:""}})},p=ot({mutationFn:M=>ne.saveSMTPSettings(M),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:M=>{e(M.message,"error")}}),x=ot({mutationFn:M=>ne.testSMTP(M),onSuccess:M=>{e(M.message,M.success?"success":"error")},onError:M=>{e(M.message,"error")}}),v=ot({mutationFn:M=>M?ne.enableAdvancedAuth():ne.disableAdvancedAuth(),onSuccess:M=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(M.message,"success")},onError:M=>{e(M.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}p.mutate(r)},y=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.smtpServerAndEmail"),"error");return}if(r.smtp_auth_enabled&&(!r.smtp_username||!r.smtp_password)){e(t("settings.email.errors.usernamePasswordRequired"),"error");return}x.mutate({smtp_host:r.smtp_host,smtp_port:r.smtp_port,smtp_username:r.smtp_username,smtp_password:r.smtp_password,smtp_security:r.smtp_security,smtp_auth_enabled:r.smtp_auth_enabled,smtp_from_email:r.smtp_from_email,test_recipient:s})},_=()=>{if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}v.mutate(!u?.advanced_auth_enabled)};if(c)return i.jsx("div",{className:"flex items-center justify-center p-12",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})});const N=u?.advanced_auth_enabled??!1,k="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",A="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";return i.jsxs("div",{className:"space-y-6",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),i.jsx(Ce,{onClick:_,disabled:v.isPending,variant:N?"danger":"primary",children:N?i.jsxs(i.Fragment,{children:[i.jsx(I_,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):i.jsxs(i.Fragment,{children:[i.jsx(zm,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),i.jsx(_t,{children:i.jsx("div",{className:"space-y-4",children:N?i.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(pr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),i.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[i.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),i.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),i.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),i.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):i.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Tn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),i.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),i.jsx("div",{className:N?"":"opacity-50 pointer-events-none",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),i.jsx(_t,{children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.authentication")||"Authentication"}),i.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:M=>f(M.target.value==="true"),className:k,children:[i.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),i.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),i.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:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.username")||"Username"}),i.jsx("input",{type:"text",value:r.smtp_username||"",onChange:M=>a({...r,smtp_username:M.target.value}),placeholder:"your.email@gmail.com",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?k:A})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.password")||"Password"}),i.jsx("input",{type:"password",value:r.smtp_password||"",onChange:M=>a({...r,smtp_password:M.target.value}),placeholder:l?"••••••••":"App password",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?k:A})]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),i.jsx("input",{type:"text",value:r.smtp_host,onChange:M=>a({...r,smtp_host:M.target.value}),placeholder:"smtp.gmail.com",className:k})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.smtpPort")||"SMTP Port"}),i.jsx("input",{type:"number",value:r.smtp_port,onChange:M=>h(parseInt(M.target.value)||587),placeholder:"587",className:k})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.security")||"Security"}),i.jsxs("select",{value:r.smtp_security,onChange:M=>d(M.target.value),className:k,children:[i.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),i.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),i.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.fromEmail")||"From Email"," *"]}),i.jsx("input",{type:"email",value:r.smtp_from_email,onChange:M=>a({...r,smtp_from_email:M.target.value}),placeholder:"your@email.com",className:k})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.fromName")||"From Name"}),i.jsx("input",{type:"text",value:r.smtp_from_name,onChange:M=>a({...r,smtp_from_name:M.target.value}),placeholder:"BamBuddy",className:k})]})]}),i.jsx("div",{className:"flex gap-2",children:i.jsx(Ce,{onClick:g,disabled:p.isPending,className:"flex-1",children:p.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),i.jsx("div",{className:N?"":"opacity-50 pointer-events-none",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),i.jsx(_t,{children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.testRecipient")||"Test Recipient Email"}),i.jsx("input",{type:"email",value:s,onChange:M=>o(M.target.value),placeholder:"test@example.com",className:k})]}),i.jsx(Ce,{onClick:y,disabled:x.isPending,variant:"secondary",children:x.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):i.jsxs(i.Fragment,{children:[i.jsx(WC,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})}const xZe={get:"bg-blue-500/20 text-blue-400 border-blue-500/30",post:"bg-green-500/20 text-green-400 border-green-500/30",put:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",patch:"bg-orange-500/20 text-orange-400 border-orange-500/30",delete:"bg-red-500/20 text-red-400 border-red-500/30"};function yZe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const a of n)r=r[a];return r}function Ly(t,e,n=0){if(n>5)return"...";if(e.$ref)return Ly(t,yZe(t,e.$ref),n+1);if(e.allOf){const r={};for(const a of e.allOf){const s=Ly(t,a,n+1);typeof s=="object"&&s!==null&&Object.assign(r,s)}return r}if(e.example!==void 0)return e.example;if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:"string";case"integer":case"number":return 0;case"boolean":return!1;case"array":return e.items?[Ly(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[a,s]of Object.entries(e.properties))r[a]=Ly(t,s,n+1);return r}return{};default:return null}}function vZe({path:t,method:e,spec:n,schema:r,apiKey:a}){const[s,o]=w.useState(!1),[l,c]=w.useState({}),[u,d]=w.useState(""),[h,f]=w.useState(null),[p,x]=w.useState(!1),[v,g]=w.useState(!1);w.useEffect(()=>{if(s&&n.parameters){const j={};for(const P of n.parameters)P.schema?.default!==void 0&&(j[P.name]=String(P.schema.default));c(P=>({...j,...P}))}},[s,n.parameters]),w.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!u){const j=n.requestBody.content["application/json"].schema,P=Ly(r,j);d(JSON.stringify(P,null,2))}},[s,n.requestBody,r,u]);const _=(()=>{const j=[];for(const P of n.parameters||[])if(P.in==="path"||P.required){const E=l[P.name];(E===void 0||E==="")&&j.push(P.name)}return j})(),N=async()=>{if(_.length>0){f({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${_.join(", ")}`,duration:0});return}x(!0),f(null);try{let j=t;const P=new URLSearchParams;for(const ae of n.parameters||[]){const $=l[ae.name];$!==void 0&&$!==""&&(ae.in==="path"?j=j.replace(`{${ae.name}}`,encodeURIComponent($)):ae.in==="query"&&P.append(ae.name,$))}const E=P.toString(),B=`${j}${E?`?${E}`:""}`,O={"Content-Type":"application/json"};a&&(O["X-API-Key"]=a);const U={method:e.toUpperCase(),headers:O};["post","put","patch"].includes(e)&&u&&(U.body=u);const R=performance.now(),V=await fetch(B,U),G=Math.round(performance.now()-R),z={};V.headers.forEach((ae,$)=>{z[$]=ae});let K;V.headers.get("content-type")?.includes("application/json")?K=await V.json():K=await V.text(),f({status:V.status,statusText:V.statusText,headers:z,body:K,duration:G})}catch(j){f({status:0,statusText:"Network Error",headers:{},body:j instanceof Error?j.message:"Unknown error",duration:0})}finally{x(!1)}},k=async()=>{if(h){const j=typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2);try{await navigator.clipboard.writeText(j),g(!0),setTimeout(()=>g(!1),2e3)}catch{const P=document.createElement("textarea");P.value=j,P.style.position="fixed",P.style.left="-999999px",document.body.appendChild(P),P.select(),document.execCommand("copy"),document.body.removeChild(P),g(!0),setTimeout(()=>g(!1),2e3)}}},A=(n.parameters||[]).filter(j=>j.in==="path"),M=(n.parameters||[]).filter(j=>j.in==="query"),C=["post","put","patch"].includes(e)&&n.requestBody;return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[s?i.jsx(Un,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${xZe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),i.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&i.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&i.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),A.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),i.jsx("div",{className:"space-y-2",children:A.map(j=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&i.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),i.jsx("input",{type:"text",value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),M.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),i.jsx("div",{className:"space-y-2",children:M.map(j=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&i.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),j.schema?.enum?i.jsxs("select",{value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:"-- Select --"}),j.schema.enum.map(P=>i.jsx("option",{value:P,children:P},P))]}):i.jsx("input",{type:"text",value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),C&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),i.jsx("textarea",{value:u,onChange:j=>d(j.target.value),rows:8,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono focus:border-bambu-green focus:outline-none resize-y",placeholder:"JSON request body..."})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{onClick:N,disabled:p,children:[p?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(io,{className:"w-4 h-4"}),"Execute"]}),_.length>0&&i.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[i.jsx(Ba,{className:"w-3 h-3"}),"Fill in: ",_.join(", ")]})]}),h&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",i.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${h.status>=200&&h.status<300?"bg-green-500/20 text-green-400":h.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[h.status," ",h.statusText]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[h.duration,"ms"]})]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:k,children:v?i.jsx(pr,{className:"w-3 h-3 text-green-400"}):i.jsx(Yl,{className:"w-3 h-3"})})]}),i.jsx("pre",{className:"p-3 bg-bambu-dark rounded-lg text-sm font-mono text-white overflow-auto max-h-96 border border-bambu-dark-tertiary",children:typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2)})]})]})]})}function wZe({apiKey:t=""}){const[e,n]=w.useState(null),[r,a]=w.useState(!0),[s,o]=w.useState(null),[l,c]=w.useState(new Set),[u,d]=w.useState("");if(w.useEffect(()=>{async function g(){try{const y=await fetch("/openapi.json");if(!y.ok)throw new Error("Failed to fetch OpenAPI schema");const _=await y.json();n(_)}catch(y){o(y instanceof Error?y.message:"Unknown error")}finally{a(!1)}}g()},[]),r)return i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return i.jsx(vt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-red-400",children:[i.jsx(Ba,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{children:"Failed to load API schema"}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const h={};for(const[g,y]of Object.entries(e.paths))for(const[_,N]of Object.entries(y)){if(_==="parameters")continue;const k=N.tags||["Other"];for(const A of k)h[A]||(h[A]=[]),h[A].push({path:g,method:_,spec:N})}const f=Object.entries(h).map(([g,y])=>{if(!u)return{tag:g,endpoints:y};const _=y.filter(({path:N,method:k,spec:A})=>{const M=u.toLowerCase();return N.toLowerCase().includes(M)||k.toLowerCase().includes(M)||(A.summary?.toLowerCase()||"").includes(M)||(A.description?.toLowerCase()||"").includes(M)});return{tag:g,endpoints:_}}).filter(({endpoints:g})=>g.length>0).sort((g,y)=>g.tag.localeCompare(y.tag)),p=g=>{c(y=>{const _=new Set(y);return _.has(g)?_.delete(g):_.add(g),_})},x=()=>{c(new Set(f.map(g=>g.tag)))},v=()=>{c(new Set)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsx("div",{className:"flex-1",children:i.jsx("input",{type:"text",value:u,onChange:g=>d(g.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:v,children:"Collapse All"}),i.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[i.jsx(Kr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[f.reduce((g,y)=>g+y.endpoints.length,0)," endpoints in ",f.length," categories"]}),i.jsx("div",{className:"space-y-3",children:f.map(({tag:g,endpoints:y})=>i.jsxs(vt,{children:[i.jsx("button",{onClick:()=>p(g),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:i.jsxs("div",{className:"flex items-center gap-2",children:[l.has(g)?i.jsx(Un,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(pi,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:g.replace(/-/g," ")}),i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:y.length})]})}),l.has(g)&&i.jsx(_t,{className:"pt-0 space-y-2",children:y.map(({path:_,method:N,spec:k})=>i.jsx(vZe,{path:_,method:N,spec:k,schema:e,apiKey:t},`${N}-${_}`))})]},g))})]})}const SZe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"],_Ze={database:"bg-blue-600",library_files:"bg-green-500",library_thumbnails:"bg-teal-500",library_other:"bg-emerald-700",archive_timelapses:"bg-red-500",archive_thumbnails:"bg-amber-500",archive_files:"bg-sky-500",virtual_printer_uploads:"bg-purple-500",virtual_printer_upload_cache:"bg-fuchsia-500",virtual_printer_certs:"bg-violet-500",virtual_printer_other:"bg-purple-700",downloads:"bg-cyan-500",plate_calibration:"bg-lime-500",logs:"bg-orange-500",other_data:"bg-yellow-500"},QW=["bg-blue-500","bg-green-500","bg-yellow-500","bg-red-500","bg-orange-500","bg-teal-500","bg-cyan-500","bg-purple-500"],ZW=(t,e)=>_Ze[t]||QW[e%QW.length];function NZe(){const t=tn(),e=rc(),[n,r]=dF(),{t:a,i18n:s}=Ut(),{showToast:o}=cn(),{authEnabled:l,user:c,refreshAuth:u}=Or(),{mode:d,darkStyle:h,darkBackground:f,darkAccent:p,lightStyle:x,lightBackground:v,lightAccent:g,setDarkStyle:y,setDarkBackground:_,setDarkAccent:N,setLightStyle:k,setLightBackground:A,setLightAccent:M}=Jf(),[C,j]=w.useState(null),[P,E]=w.useState(!1),[B,O]=w.useState(null),[U,R]=w.useState(!1),[V,G]=w.useState(null),[z,K]=w.useState(null),[Y,ae]=w.useState(!1),[$,W]=w.useState(yX()),ee=n.get("tab"),J=ee==="email",ye=J?"users":ee&&SZe.includes(ee)?ee:"general",[me,te]=w.useState(ye),[je,ue]=w.useState(J?"email":"users"),oe=ce=>{te(ce),ce==="users"&&ue("users"),ce==="general"?n.delete("tab"):n.set("tab",ce),r(n,{replace:!0})},[_e,se]=w.useState(!1),[Oe,q]=w.useState(""),[X,de]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[Z,ie]=w.useState(null),[le,Fe]=w.useState(null),[pe,Q]=w.useState(""),[L,D]=w.useState(!1),[H,he]=w.useState(!1),[be,fe]=w.useState(null),[ze,Ie]=w.useState(!1),[qe,tt]=w.useState(!1),[Ee,Se]=w.useState(!1),[Me,xe]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[ve,He]=w.useState(!1),[Pe,nt]=w.useState(!1),[Te,Ge]=w.useState(!1),[Re,Le]=w.useState(!1),[Ke,ft]=w.useState(null),[kt,Lt]=w.useState(null),[Kt,Mt]=w.useState(null),[Ue,bt]=w.useState(!1),[wt,qt]=w.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[Cn,yr]=w.useState(null),[Qn,tr]=w.useState(null),[Pn,dr]=w.useState(!1),[Ar,ii]=w.useState({}),[De,we]=w.useState({}),et=ce=>{W(ce),cge(ce),o(a("settings.toast.settingsSaved"),"success")},st=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:Ve,isLoading:Ot}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:ge,isLoading:Be,isFetching:Xe}=Je({queryKey:["storage-usage"],queryFn:()=>ne.getStorageUsage(),enabled:me==="general",staleTime:1/0,refetchInterval:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),We=async()=>{nt(!0);try{const ce=await ne.getStorageUsage({refresh:!0});t.setQueryData(["storage-usage"],ce)}catch(ce){const Et=ce instanceof Error?ce.message:"Failed to refresh storage usage";o(Et,"error")}finally{nt(!1)}},{data:Ne,isLoading:lt}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:pt,isLoading:at}=Je({queryKey:["smart-plugs-energy",Ne?.map(ce=>ce.id)],queryFn:async()=>{if(!Ne||Ne.length===0)return null;const ce=await Promise.all(Ne.filter(mo=>mo.enabled).map(async mo=>{try{const _s=await ne.getSmartPlugStatus(mo.id);return{plug:mo,status:_s}}catch{return{plug:mo,status:null}}}));let Et=0,ia=0,Gr=0,Xc=0,op=0;for(const{plug:mo,status:_s}of ce){const kA=mo.plug_type==="mqtt"&&_s?.energy?.power!=null;(_s?.reachable||kA)&&_s?.energy&&(op++,_s.energy?.power!=null&&(Et+=_s.energy.power),_s.energy?.today!=null&&(ia+=_s.energy.today),_s.energy?.yesterday!=null&&(Gr+=_s.energy.yesterday),_s.energy?.total!=null&&(Xc+=_s.energy.total))}return{totalPower:Et,totalToday:ia,totalYesterday:Gr,totalLifetime:Xc,reachableCount:op,totalPlugs:Ne.filter(mo=>mo.enabled).length}},enabled:me==="plugs"&&!!Ne&&Ne.length>0,refetchInterval:me==="plugs"?1e4:!1}),{data:At,isLoading:Ht}=Je({queryKey:["notification-providers"],queryFn:ne.getNotificationProviders}),{data:Dt,isLoading:Pt}=Je({queryKey:["api-keys"],queryFn:ne.getAPIKeys}),an=ot({mutationFn:ce=>ne.createAPIKey(ce),onSuccess:ce=>{ie(ce.key||null),se(!1),q(""),t.invalidateQueries({queryKey:["api-keys"]}),o(a("settings.toast.apiKeyCreated"))},onError:ce=>{o(`Failed to create API key: ${ce.message}`,"error")}}),Zt=ot({mutationFn:ce=>ne.deleteAPIKey(ce),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(a("settings.toast.apiKeyDeleted"))},onError:ce=>{o(`Failed to delete API key: ${ce.message}`,"error")}}),{data:un}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:kn,isLoading:jn}=Je({queryKey:["notification-templates"],queryFn:ne.getNotificationTemplates}),{data:Xt}=Je({queryKey:["virtual-printer-settings"],queryFn:Qpe.getSettings,refetchInterval:1e4}),mn=Xt?.status?.running??!1,{data:fn}=Je({queryKey:["ffmpeg-status"],queryFn:ne.checkFfmpeg}),{data:qr}=Je({queryKey:["version"],queryFn:ne.getVersion}),{data:pn,refetch:Dn,isRefetching:aa}=Je({queryKey:["updateCheck"],queryFn:ne.checkForUpdates,enabled:Ve?.check_updates!==!1,staleTime:300*1e3}),{data:Sn,refetch:va}=Je({queryKey:["updateStatus"],queryFn:ne.getUpdateStatus,refetchInterval:ce=>{const Et=ce.state.data;return Et?.status==="downloading"||Et?.status==="installing"?1e3:!1}}),{data:sr}=Je({queryKey:["mqtt-status"],queryFn:ne.getMQTTStatus,refetchInterval:me==="network"?5e3:!1}),{data:ha}=Je({queryKey:["github-backup-status"],queryFn:ne.getGitHubBackupStatus}),{data:xt}=Je({queryKey:["cloud-status"],queryFn:ne.getCloudStatus}),{data:Rt={advanced_auth_enabled:!1,smtp_configured:!1}}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()}),{hasPermission:bn}=Or(),{data:Nt=[],isLoading:Zn}=Je({queryKey:["users"],queryFn:()=>ne.getUsers(),enabled:l&&bn("users:read")}),{data:vr=[],isLoading:hr}=Je({queryKey:["groups"],queryFn:()=>ne.getGroups(),enabled:l&&bn("groups:read")}),wa=ot({mutationFn:ce=>ne.createUser(ce),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(a("settings.toast.userCreated"))},onError:ce=>{o(ce.message,"error")}}),Va=ot({mutationFn:({id:ce,data:Et})=>ne.updateUser(ce,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(a("settings.toast.userUpdated"))},onError:ce=>{o(ce.message,"error")}}),$t=ot({mutationFn:({id:ce,deleteItems:Et})=>ne.deleteUser(ce,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(a("settings.toast.userDeleted")),Lt(null),Mt(null)},onError:ce=>{o(ce.message,"error")}}),xn=ot({mutationFn:ce=>ne.resetUserPassword({user_id:ce}),onSuccess:ce=>{o(ce.message,"success")},onError:ce=>{o(ce.message,"error")}}),Ss=async ce=>{Lt(ce),bt(!0);try{const Et=await ne.getUserItemsCount(ce);Mt(Et)}catch{Mt({archives:0,queue_items:0,library_files:0})}finally{bt(!1)}},Ci=ot({mutationFn:ce=>ne.deleteGroup(ce),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(a("settings.toast.groupDeleted"))},onError:ce=>{o(ce.message,"error")}}),ns=()=>{const ce=Rt?.advanced_auth_enabled||!1;if(!wt.username){o(a("settings.toast.fillRequiredFields"),"error");return}if(ce&&!wt.email){o("Email is required when advanced authentication is enabled","error");return}if(!ce){if(!wt.password){o(a("settings.toast.fillRequiredFields"),"error");return}if(wt.password!==wt.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(wt.password.length<6){o(a("settings.toast.passwordTooShort"),"error");return}}wa.mutate({username:wt.username,password:ce?void 0:wt.password,email:wt.email||void 0,role:wt.role,group_ids:wt.group_ids.length>0?wt.group_ids:void 0})},Tl=ce=>{if(wt.password){if(wt.password!==wt.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(wt.password.length<6){o(a("settings.toast.passwordTooShort"),"error");return}}const Et={username:wt.username||void 0,password:wt.password||void 0,role:wt.role,group_ids:wt.group_ids};Et.password||delete Et.password,Va.mutate({id:ce,data:Et})},rs=ce=>{ft(ce.id),qt({username:ce.username,password:"",email:ce.email||"",confirmPassword:"",role:ce.role,group_ids:ce.groups?.map(Et=>Et.id)||[]}),Le(!0)},si=ce=>{qt(Et=>({...Et,group_ids:Et.group_ids.includes(ce)?Et.group_ids.filter(ia=>ia!==ce):[...Et.group_ids,ce]}))},Sa=ot({mutationFn:ne.applyUpdate,onSuccess:ce=>{ce.is_docker?o(ce.message,"error"):va()}}),[Yr,mr]=w.useState(null),uo=ot({mutationFn:ne.testAllNotificationProviders,onSuccess:ce=>{mr(ce),t.invalidateQueries({queryKey:["notification-providers"]}),ce.failed===0?o(`All ${ce.tested} providers tested successfully!`,"success"):o(`${ce.success}/${ce.tested} providers succeeded`,ce.failed>0?"error":"success")},onError:ce=>{o(`Failed to test providers: ${ce.message}`,"error")}}),qa=ot({mutationFn:async ce=>{if(!Ne)return{success:0,failed:0};const Et=Ne.filter(Gr=>Gr.enabled),ia=await Promise.all(Et.map(async Gr=>{try{return await ne.controlSmartPlug(Gr.id,ce),{success:!0}}catch{return{success:!1}}}));return{success:ia.filter(Gr=>Gr.success).length,failed:ia.filter(Gr=>!Gr.success).length}},onSuccess:(ce,Et)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ce.failed===0?o(`All ${ce.success} plugs turned ${Et}`,"success"):o(`${ce.success} plugs turned ${Et}, ${ce.failed} failed`,"error")},onError:ce=>{o(`Failed: ${ce.message}`,"error")}}),Oa=w.useRef(null),ho=w.useRef(!1),zr=w.useRef(!0);w.useEffect(()=>{if(Ve&&!C){const ce={...Ve,external_url:Ve.external_url||window.location.origin};j(ce),setTimeout(()=>{zr.current=!1},100)}},[Ve,C]);const ma=ot({mutationFn:ne.updateSettings,onSuccess:ce=>{t.setQueryData(["settings"],ce),j(ce),t.invalidateQueries({queryKey:["archiveStats"]}),o(a("settings.toast.settingsSaved"),"success")},onError:ce=>{o(`Failed to save: ${ce.message}`,"error")},onSettled:()=>{ho.current=!1}}),Us=ot({mutationFn:({id:ce,data:Et})=>ne.updatePrinter(ce,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(a("settings.toast.cameraSettingsSaved"),"success")},onError:ce=>{o(`Failed to update printer: ${ce.message}`,"error")}});w.useEffect(()=>{if(!(zr.current||!C||!Ve||!(Ve.auto_archive!==C.auto_archive||Ve.save_thumbnails!==C.save_thumbnails||Ve.capture_finish_photo!==C.capture_finish_photo||Ve.default_filament_cost!==C.default_filament_cost||Ve.currency!==C.currency||Ve.energy_cost_per_kwh!==C.energy_cost_per_kwh||Ve.energy_tracking_mode!==C.energy_tracking_mode||Ve.check_updates!==C.check_updates||(Ve.check_printer_firmware??!0)!==(C.check_printer_firmware??!0)||(Ve.include_beta_updates??!1)!==(C.include_beta_updates??!1)||Ve.notification_language!==C.notification_language||(Ve.bed_cooled_threshold??35)!==(C.bed_cooled_threshold??35)||Ve.ams_humidity_good!==C.ams_humidity_good||Ve.ams_humidity_fair!==C.ams_humidity_fair||Ve.ams_temp_good!==C.ams_temp_good||Ve.ams_temp_fair!==C.ams_temp_fair||Ve.ams_history_retention_days!==C.ams_history_retention_days||Ve.per_printer_mapping_expanded!==C.per_printer_mapping_expanded||Ve.date_format!==C.date_format||Ve.time_format!==C.time_format||Ve.default_printer_id!==C.default_printer_id||Ve.ftp_retry_enabled!==C.ftp_retry_enabled||Ve.ftp_retry_count!==C.ftp_retry_count||Ve.ftp_retry_delay!==C.ftp_retry_delay||Ve.ftp_timeout!==C.ftp_timeout||Ve.mqtt_enabled!==C.mqtt_enabled||Ve.mqtt_broker!==C.mqtt_broker||Ve.mqtt_port!==C.mqtt_port||Ve.mqtt_username!==C.mqtt_username||Ve.mqtt_password!==C.mqtt_password||Ve.mqtt_topic_prefix!==C.mqtt_topic_prefix||Ve.mqtt_use_tls!==C.mqtt_use_tls||Ve.external_url!==C.external_url||Ve.ha_enabled!==C.ha_enabled||Ve.ha_url!==C.ha_url||Ve.ha_token!==C.ha_token||(Ve.library_archive_mode??"ask")!==(C.library_archive_mode??"ask")||Number(Ve.library_disk_warning_gb??5)!==Number(C.library_disk_warning_gb??5)||(Ve.camera_view_mode??"window")!==(C.camera_view_mode??"window")||(Ve.preferred_slicer??"bambu_studio")!==(C.preferred_slicer??"bambu_studio")||Ve.prometheus_enabled!==C.prometheus_enabled||Ve.prometheus_token!==C.prometheus_token))&&!ho.current)return Oa.current&&clearTimeout(Oa.current),Oa.current=setTimeout(()=>{if(ho.current)return;ho.current=!0;const Et={auto_archive:C.auto_archive,save_thumbnails:C.save_thumbnails,capture_finish_photo:C.capture_finish_photo,default_filament_cost:C.default_filament_cost,currency:C.currency,energy_cost_per_kwh:C.energy_cost_per_kwh,energy_tracking_mode:C.energy_tracking_mode,check_updates:C.check_updates,check_printer_firmware:C.check_printer_firmware,include_beta_updates:C.include_beta_updates,notification_language:C.notification_language,bed_cooled_threshold:C.bed_cooled_threshold,ams_humidity_good:C.ams_humidity_good,ams_humidity_fair:C.ams_humidity_fair,ams_temp_good:C.ams_temp_good,ams_temp_fair:C.ams_temp_fair,ams_history_retention_days:C.ams_history_retention_days,per_printer_mapping_expanded:C.per_printer_mapping_expanded,date_format:C.date_format,time_format:C.time_format,default_printer_id:C.default_printer_id,ftp_retry_enabled:C.ftp_retry_enabled,ftp_retry_count:C.ftp_retry_count,ftp_retry_delay:C.ftp_retry_delay,ftp_timeout:C.ftp_timeout,mqtt_enabled:C.mqtt_enabled,mqtt_broker:C.mqtt_broker,mqtt_port:C.mqtt_port,mqtt_username:C.mqtt_username,mqtt_password:C.mqtt_password,mqtt_topic_prefix:C.mqtt_topic_prefix,mqtt_use_tls:C.mqtt_use_tls,external_url:C.external_url,ha_enabled:C.ha_enabled,ha_url:C.ha_url,ha_token:C.ha_token,library_archive_mode:C.library_archive_mode,library_disk_warning_gb:C.library_disk_warning_gb,camera_view_mode:C.camera_view_mode,preferred_slicer:C.preferred_slicer,prometheus_enabled:C.prometheus_enabled,prometheus_token:C.prometheus_token};ma.mutate(Et)},500),()=>{Oa.current&&clearTimeout(Oa.current)}},[C,Ve,ma]);const Bt=w.useCallback((ce,Et)=>{j(ia=>ia?{...ia,[ce]:Et}:null)},[]),Vn=async(ce,Et,ia)=>{if(!Et){o(a("settings.toast.enterCameraUrl"),"error");return}we(Gr=>({...Gr,[ce]:!0})),ii(Gr=>({...Gr,[ce]:null}));try{const Gr=await ne.testExternalCamera(ce,Et,ia);ii(Xc=>({...Xc,[ce]:Gr})),Gr.success?o(a("settings.toast.cameraConnected",{resolution:Gr.resolution||""}),"success"):o(Gr.error||a("settings.toast.connectionFailed"),"error")}catch(Gr){const Xc=Gr instanceof Error?Gr.message:a("settings.toast.testFailed");ii(op=>({...op,[ce]:{success:!1,error:Xc}})),o(Xc,"error")}finally{we(Gr=>({...Gr,[ce]:!1}))}},[Ml,um]=w.useState({}),Kc=w.useRef({}),q0=w.useRef(new Set);w.useEffect(()=>{if(un){const ce={};un.forEach(Et=>{Et.external_camera_url&&!q0.current.has(Et.id)&&(ce[Et.id]=Et.external_camera_url,q0.current.add(Et.id))}),Object.keys(ce).length>0&&um(Et=>({...Et,...ce}))}},[un]);const lx=(ce,Et)=>{um(ia=>({...ia,[ce]:Et})),Kc.current[ce]&&clearTimeout(Kc.current[ce]),Kc.current[ce]=setTimeout(()=>{Us.mutate({id:ce,data:{external_camera_url:Et||null}})},800)},sp=(ce,Et)=>{const ia={};Et.type!==void 0&&(ia.external_camera_type=Et.type||null),Et.enabled!==void 0&&(ia.external_camera_enabled=Et.enabled),Us.mutate({id:ce,data:ia})};return Ot||!C?i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-8",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:a("settings.title")}),i.jsx("p",{className:"text-bambu-gray",children:a("settings.configureBambuddy")})]}),i.jsxs("div",{className:"flex flex-wrap gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>oe("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${me==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:a("settings.tabs.general")}),i.jsxs("button",{onClick:()=>oe("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(fl,{className:"w-4 h-4"}),a("settings.tabs.smartPlugs"),Ne&&Ne.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ne.length})]}),i.jsxs("button",{onClick:()=>oe("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Hg,{className:"w-4 h-4"}),a("settings.tabs.notifications"),At&&At.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:At.length})]}),i.jsxs("button",{onClick:()=>oe("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Ohe,{className:"w-4 h-4"}),a("settings.tabs.filament")]}),i.jsxs("button",{onClick:()=>oe("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Vg,{className:"w-4 h-4"}),a("settings.tabs.network"),i.jsx("span",{className:`w-2 h-2 rounded-full ${sr?.enabled?"bg-green-400":"bg-gray-500"}`})]}),i.jsxs("button",{onClick:()=>oe("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(nl,{className:"w-4 h-4"}),a("settings.tabs.apiKeys"),Dt&&Dt.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Dt.length})]}),i.jsxs("button",{onClick:()=>oe("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(xr,{className:"w-4 h-4"}),a("settings.tabs.virtualPrinter"),i.jsx("span",{className:`w-2 h-2 rounded-full ${mn?"bg-green-400":"bg-gray-500"}`})]}),i.jsxs("button",{onClick:()=>oe("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(hh,{className:"w-4 h-4"}),a("settings.tabs.users"),l&&i.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),i.jsxs("button",{onClick:()=>oe("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Pc,{className:"w-4 h-4"}),a("settings.tabs.backup"),i.jsx("span",{className:`w-2 h-2 rounded-full ${xt?.is_authenticated&&ha?.configured&&ha?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),me==="general"&&i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.general")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(Mh,{className:"w-4 h-4 inline mr-1"}),a("settings.language")]}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:s.language,onChange:ce=>{s.changeLanguage(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:hB.map(ce=>i.jsxs("option",{value:ce.code,children:[ce.nativeName," (",ce.name,")"]},ce.code))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.languageDescription")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.defaultView")}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:$,onChange:ce=>et(ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:pv.map(ce=>i.jsx("option",{value:ce.to,children:a(ce.labelKey)},ce.id))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.defaultViewDescription")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.date_format||"system",onChange:ce=>Bt("date_format",ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"system",children:a("settings.systemDefault")}),i.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),i.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),i.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.time_format||"system",onChange:ce=>Bt("time_format",ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"system",children:a("settings.systemDefault")}),i.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),i.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.default_printer_id??"",onChange:ce=>Bt("default_printer_id",ce.target.value?Number(ce.target.value):null),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"",children:a("settings.noDefaultPrinter")}),un?.map(ce=>i.jsx("option",{value:ce.id,children:ce.name},ce.id))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.preferredSlicer")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.preferred_slicer??"bambu_studio",onChange:ce=>Bt("preferred_slicer",ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"bambu_studio",children:"Bambu Studio"}),i.jsx("option",{value:"orcaslicer",children:"OrcaSlicer"})]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.preferredSlicerDescription")})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.sidebarOrder")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:st,children:[i.jsx(Fo,{className:"w-4 h-4"}),"Reset"]})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(VC,{className:"w-5 h-5"}),"Appearance"]})}),i.jsxs(_t,{className:"space-y-6",children:[i.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&i.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),i.jsxs("select",{value:f,onChange:ce=>{_(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"neutral",children:"Neutral"}),i.jsx("option",{value:"warm",children:"Warm"}),i.jsx("option",{value:"cool",children:"Cool"}),i.jsx("option",{value:"oled",children:"OLED Black"}),i.jsx("option",{value:"slate",children:"Slate Blue"}),i.jsx("option",{value:"forest",children:"Forest Green"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),i.jsxs("select",{value:p,onChange:ce=>{N(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"green",children:"Green"}),i.jsx("option",{value:"teal",children:"Teal"}),i.jsx("option",{value:"blue",children:"Blue"}),i.jsx("option",{value:"orange",children:"Orange"}),i.jsx("option",{value:"purple",children:"Purple"}),i.jsx("option",{value:"red",children:"Red"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),i.jsxs("select",{value:h,onChange:ce=>{y(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"classic",children:"Classic"}),i.jsx("option",{value:"glow",children:"Glow"}),i.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),i.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&i.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),i.jsxs("select",{value:v,onChange:ce=>{A(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"neutral",children:"Neutral"}),i.jsx("option",{value:"warm",children:"Warm"}),i.jsx("option",{value:"cool",children:"Cool"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),i.jsxs("select",{value:g,onChange:ce=>{M(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"green",children:"Green"}),i.jsx("option",{value:"teal",children:"Teal"}),i.jsx("option",{value:"blue",children:"Blue"}),i.jsx("option",{value:"orange",children:"Orange"}),i.jsx("option",{value:"purple",children:"Purple"}),i.jsx("option",{value:"red",children:"Red"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),i.jsxs("select",{value:x,onChange:ce=>{k(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"classic",children:"Classic"}),i.jsx("option",{value:"glow",children:"Glow"}),i.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.archiveSettings")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Auto-archive prints"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.auto_archive,onChange:ce=>Bt("auto_archive",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.saveThumbnails")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.save_thumbnails,onChange:ce=>Bt("save_thumbnails",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.captureFinishPhoto")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.capture_finish_photo,onChange:ce=>Bt("capture_finish_photo",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.capture_finish_photo&&fn&&!fn.installed&&i.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-sm",children:[i.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),i.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",i.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",i.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(kF,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),i.jsxs("select",{value:C.camera_view_mode??"window",onChange:ce=>Bt("camera_view_mode",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",children:[i.jsx("option",{value:"window",children:a("settings.newWindow")}),i.jsx("option",{value:"embedded",children:a("settings.embeddedOverlay")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:a("settings.externalCameras")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Configure external cameras to replace the built-in printer camera. Supports MJPEG streams, RTSP, HTTP snapshots, and USB cameras (V4L2). When enabled, the external camera is used for live view and finish photos."}),un&&un.length>0?i.jsx("div",{className:"space-y-3",children:un.map(ce=>i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-white font-medium text-sm",children:ce.name}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:ce.external_camera_enabled,onChange:Et=>sp(ce.id,{enabled:Et.target.checked}),className:"sr-only peer"}),i.jsx("div",{className:"w-9 h-5 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:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),ce.external_camera_enabled&&i.jsxs("div",{className:"space-y-2 mt-2",children:[i.jsx("input",{type:"text",placeholder:ce.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Ml[ce.id]??ce.external_camera_url??"",onChange:Et=>lx(ce.id,Et.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:ce.external_camera_type||"mjpeg",onChange:Et=>sp(ce.id,{type:Et.target.value}),className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),i.jsx("option",{value:"rtsp",children:"RTSP Stream"}),i.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),i.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>Vn(ce.id,Ml[ce.id]??ce.external_camera_url??"",ce.external_camera_type||"mjpeg"),disabled:De[ce.id]||!(Ml[ce.id]??ce.external_camera_url),children:De[ce.id]?i.jsx(it,{className:"w-4 h-4 animate-spin"}):"Test"})]}),Ar[ce.id]&&i.jsx("div",{className:`text-xs flex items-center gap-1 ${Ar[ce.id]?.success?"text-green-500":"text-red-500"}`,children:Ar[ce.id]?.success?i.jsxs(i.Fragment,{children:[i.jsx(pr,{className:"w-3 h-3"}),"Connected",Ar[ce.id]?.resolution&&` (${Ar[ce.id]?.resolution})`]}):i.jsxs(i.Fragment,{children:[i.jsx(hi,{className:"w-3 h-3"}),Ar[ce.id]?.error||a("settings.toast.connectionFailed")]})})]})]},ce.id))}):i.jsx("p",{className:"text-xs text-bambu-gray italic",children:a("settings.noPrintersConfigured")})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.costTracking")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),i.jsx("select",{value:C.currency,onChange:ce=>Bt("currency",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",children:h$e.map(ce=>i.jsx("option",{value:ce.code,children:ce.label},ce.code))})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:rl(C.currency)}),i.jsx("input",{type:"number",step:"0.01",min:"0",value:C.default_filament_cost,onChange:ce=>Bt("default_filament_cost",parseFloat(ce.target.value)||0),style:{paddingLeft:`${Math.max(2,rl(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:rl(C.currency)}),i.jsx("input",{type:"number",step:"0.001",min:"0",value:C.energy_cost_per_kwh,onChange:ce=>Bt("energy_cost_per_kwh",parseFloat(ce.target.value)||0),style:{paddingLeft:`${Math.max(2,rl(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),i.jsxs("select",{value:C.energy_tracking_mode||"total",onChange:ce=>Bt("energy_tracking_mode",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",children:[i.jsx("option",{value:"print",children:a("settings.printsOnly")}),i.jsx("option",{value:"total",children:a("settings.totalConsumption")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),i.jsxs("select",{value:C.library_archive_mode??"ask",onChange:ce=>Bt("library_archive_mode",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",children:[i.jsx("option",{value:"always",children:a("settings.archiveMode.always")}),i.jsx("option",{value:"never",children:a("settings.archiveMode.never")}),i.jsx("option",{value:"ask",children:a("settings.archiveMode.ask")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:C.library_disk_warning_gb??5,onChange:ce=>Bt("library_disk_warning_gb",parseFloat(ce.target.value)||5),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[i.jsx(cZe,{}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.checkForUpdatesLabel")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.check_updates,onChange:ce=>Bt("check_updates",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.checkPrinterFirmware")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.check_printer_firmware??!0,onChange:ce=>Bt("check_printer_firmware",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:`flex items-center justify-between ${C.check_updates?"":"opacity-50"}`,children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.includeBetaUpdates")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.includeBetaUpdatesDesc")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.include_beta_updates??!1,onChange:ce=>Bt("include_beta_updates",ce.target.checked),disabled:!C.check_updates,className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.currentVersion")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",qr?.version||"..."]})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>Dn(),disabled:aa,children:[aa?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),"Check now"]})]}),pn?.update_available?i.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{children:[i.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",pn.latest_version]}),pn.release_name&&pn.release_name!==pn.latest_version&&i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:pn.release_name})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[pn.release_notes&&i.jsx("button",{onClick:()=>Ie(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),pn.release_url&&i.jsx("a",{href:pn.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:a("settings.viewReleaseOnGitHub"),children:i.jsx(Kr,{className:"w-4 h-4"})})]})]}),Sn?.status==="downloading"||Sn?.status==="installing"?i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),i.jsx("span",{children:Sn.message})]}),i.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Sn.progress}%`}})})]}):Sn?.status==="complete"?i.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:Sn.message}):Sn?.status==="error"?i.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:Sn.error||Sn.message}):pn?.is_docker?i.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),i.jsx("code",{className:"block text-xs bg-bambu-dark p-2 rounded text-bambu-green font-mono",children:"docker compose pull && docker compose up -d"})]}):i.jsxs(Ce,{className:"mt-3",onClick:()=>Sa.mutate(),disabled:Sa.isPending,children:[Sa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ua,{className:"w-4 h-4"}),"Install Update"]})]}):pn?.error?i.jsxs("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:["Failed to check for updates: ",pn.error]}):pn&&!pn.update_available?i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.dataManagement")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.clearNotificationLogs")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.clearNotificationLogsDescription")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>D(!0),children:[i.jsx(Jt,{className:"w-4 h-4"}),a("common.clear")]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.resetUiPreferences")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.resetUiPreferencesDescription")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>he(!0),children:[i.jsx(Jt,{className:"w-4 h-4"}),"Reset"]})]}),i.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.storageUsage","Storage Usage")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.storageUsageDescription","Breakdown of data usage by category")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:We,disabled:Xe||Pe,children:[i.jsx(Cr,{className:`w-4 h-4 ${Xe||Pe?"animate-spin":""}`}),a("common.refresh","Refresh")]})]}),i.jsx("div",{className:"mt-3",children:Be?i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("common.loading","Loading")]}):ge?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-full h-3 bg-bambu-dark rounded-full overflow-hidden flex",children:ge.categories.filter(ce=>ce.bytes>0).map((ce,Et)=>i.jsx("div",{className:`${ZW(ce.key,Et)} h-full`,style:{width:`${ce.percent_of_total}%`},title:`${ce.label}: ${ce.formatted}`},ce.key))}),i.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:ge.categories.filter(ce=>ce.bytes>0).map((ce,Et)=>i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:`w-3 h-3 rounded-full ${ZW(ce.key,Et)}`}),i.jsx("span",{className:"text-bambu-gray",children:ce.label}),i.jsx("span",{className:"text-white",children:ce.formatted}),i.jsxs("span",{className:"text-bambu-gray",children:["(",ce.percent_of_total.toFixed(1),"%)"]})]},ce.key))}),i.jsxs("div",{className:"mt-2 text-xs text-bambu-gray",children:[a("settings.storageUsageTotal","Total"),": ",i.jsx("span",{className:"text-white",children:ge.total_formatted}),ge.scan_errors>0&&i.jsxs("span",{className:"ml-2 text-amber-400",children:[a("settings.storageUsageErrors","Scan errors"),": ",ge.scan_errors]})]}),ge.other_breakdown?.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:a("settings.storageUsageOtherBreakdown","Other breakdown")}),i.jsx("div",{className:"space-y-2",children:ge.other_breakdown.map(ce=>i.jsxs("div",{className:"flex items-center justify-between text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-white",children:ce.label}),i.jsx("span",{className:`px-2 py-0.5 rounded-full border ${ce.kind==="system"?"border-slate-500 text-slate-300":"border-bambu-green text-bambu-green"}`,children:ce.kind==="system"?a("settings.storageUsageSystem","System"):a("settings.storageUsageData","Data")})]}),i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[i.jsx("span",{className:"text-white",children:ce.formatted}),i.jsxs("span",{children:["(",ce.percent_of_total.toFixed(1),"%)"]})]})]},`${ce.bucket}-${ce.kind}`))})]})]}):i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.storageUsageUnavailable","Storage usage data is unavailable")})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Backup & Restore"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>oe("backup"),children:[i.jsx(Pc,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),me==="network"&&C&&i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Mh,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),i.jsx("input",{type:"text",value:C.external_url??"",onChange:ce=>Bt("external_url",ce.target.value),placeholder:"http://192.168.1.100:8000",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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Cr,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableRetry")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.ftp_retry_enabled??!0,onChange:ce=>Bt("ftp_retry_enabled",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.ftp_retry_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_retry_count??3,onChange:ce=>Bt("ftp_retry_count",parseInt(ce.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,4,5,6,7,8,9,10].map(ce=>i.jsxs("option",{value:ce,children:[ce," ",ce===1?"time":"times"]},ce))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_retry_delay??2,onChange:ce=>Bt("ftp_retry_delay",parseInt(ce.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,5,10,15,20,30].map(ce=>i.jsxs("option",{value:ce,children:[ce," ",ce===1?"second":"seconds"]},ce))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_timeout??30,onChange:ce=>Bt("ftp_timeout",parseInt(ce.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[10,15,20,30,45,60,90,120].map(ce=>i.jsxs("option",{value:ce,children:[ce," seconds"]},ce))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Increase for printers with weak WiFi"})]})]})]})]})]}),i.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(l0,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),C.ha_enabled&&Qn&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Qn.success?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:`text-sm ${Qn.success?"text-green-400":"text-red-400"}`,children:Qn.success?"Connected":"Disconnected"})]})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-white",children:a("settings.enableHomeAssistant")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.homeAssistantDescription")}),C.ha_env_managed&&i.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[i.jsx(zm,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-green",children:a("settings.autoEnabledViaEnv")})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.ha_enabled??!1,onChange:ce=>Bt("ha_enabled",ce.target.checked),disabled:C.ha_env_managed,className:"sr-only peer"}),i.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 ${C.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),C.ha_enabled&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Home Assistant URL",C.ha_url_from_env&&i.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:a("settings.environmentManagedLabel")})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",value:C.ha_url??"",onChange:ce=>Bt("ha_url",ce.target.value),placeholder:"http://192.168.1.100:8123",disabled:C.ha_url_from_env,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 ${C.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_url_from_env&&i.jsx(zm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_url_from_env&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.urlFromEnvReadOnly")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Long-Lived Access Token",C.ha_token_from_env&&i.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:a("settings.environmentManagedLabel")})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"password",value:C.ha_token??"",onChange:ce=>Bt("ha_token",ce.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:C.ha_token_from_env,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 ${C.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_token_from_env&&i.jsx(zm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_token_from_env?i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.tokenFromEnvReadOnly")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),C.ha_url&&C.ha_token&&i.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:Pn,onClick:async()=>{dr(!0),tr(null);try{const ce=await ne.testHAConnection(C.ha_url,C.ha_token);tr(ce)}catch(ce){tr({success:!1,message:null,error:ce instanceof Error?ce.message:a("common.unknownError")})}finally{dr(!1)}},children:[Pn?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Vg,{className:"w-4 h-4"}),a("settings.testConnection")]})})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Vg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),sr?.enabled&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${sr.connected?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:`text-sm ${sr.connected?"text-green-400":"text-red-400"}`,children:sr.connected?"Connected":"Disconnected"})]})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableMqtt")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.mqtt_enabled??!1,onChange:ce=>Bt("mqtt_enabled",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.mqtt_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),i.jsx("input",{type:"text",value:C.mqtt_broker??"",onChange:ce=>Bt("mqtt_broker",ce.target.value),placeholder:"mqtt.example.com or 192.168.1.100",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"})]}),i.jsxs("div",{className:"flex items-end gap-4",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),i.jsx("input",{type:"number",min:"1",max:"65535",value:C.mqtt_port??1883,onChange:ce=>Bt("mqtt_port",Math.min(65535,Math.max(1,parseInt(ce.target.value)||1883))),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.mqtt_use_tls??!1,onChange:ce=>{const Et=ce.target.checked;Bt("mqtt_use_tls",Et);const ia=C.mqtt_port??1883;Et&&ia===1883?Bt("mqtt_port",8883):!Et&&ia===8883&&Bt("mqtt_port",1883)},className:"sr-only peer"}),i.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"})]}),i.jsx("span",{className:"text-white text-sm",children:a("settings.useTls")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),i.jsx("input",{type:"text",value:C.mqtt_username??"",onChange:ce=>Bt("mqtt_username",ce.target.value),placeholder:a("settings.leaveEmptyForAnonymous"),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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),i.jsx("input",{type:"password",value:C.mqtt_password??"",onChange:ce=>Bt("mqtt_password",ce.target.value),placeholder:a("settings.leaveEmptyForAnonymous"),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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),i.jsx("input",{type:"text",value:C.mqtt_topic_prefix??"bambuddy",onChange:ce=>Bt("mqtt_topic_prefix",ce.target.value),placeholder:"bambuddy",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"}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",C.mqtt_topic_prefix||"bambuddy","/printers//status, etc."]})]}),sr&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("span",{className:`w-2 h-2 rounded-full ${sr.connected?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:"text-bambu-gray",children:sr.connected?i.jsxs(i.Fragment,{children:[a("settings.mqttConnectedTo")," ",i.jsxs("span",{className:"text-white",children:[sr.broker,":",sr.port]})]}):a("settings.spoolmanDisconnected")})]})})]})]})]})]}),i.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(s3,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",i.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableMetricsEndpoint")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.prometheusDescription")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.prometheus_enabled??!1,onChange:ce=>Bt("prometheus_enabled",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.prometheus_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),i.jsx("input",{type:"password",value:C.prometheus_token??"",onChange:ce=>Bt("prometheus_token",ce.target.value),placeholder:a("settings.leaveEmptyForNoAuth"),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"}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",i.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer "})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm text-white mb-2",children:a("settings.availableMetrics")}),i.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),i.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),Qn&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[Qn.success?i.jsx(pr,{className:"w-8 h-8 text-green-400"}):i.jsx(hi,{className:"w-8 h-8 text-red-400"}),i.jsx("h3",{className:"text-lg font-medium text-white",children:Qn.success?"Connection Successful":"Connection Failed"})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:Qn.success?Qn.message||"Successfully connected to Home Assistant.":Qn.error||"Failed to connect to Home Assistant."}),i.jsx("div",{className:"flex justify-end",children:i.jsx(Ce,{variant:"primary",onClick:()=>tr(null),children:"OK"})})]})}),me==="plugs"&&i.jsxs("div",{className:"max-w-4xl",children:[i.jsxs("div",{className:"flex items-start justify-between mb-6",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(fl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers."})]}),i.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Ne&&Ne.filter(ce=>ce.enabled).length>1&&i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>fe("on"),disabled:qa.isPending,title:a("settings.turnAllPlugsOn"),children:[qa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(hd,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>fe("off"),disabled:qa.isPending,title:a("settings.turnAllPlugsOff"),children:[qa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(GC,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),i.jsxs(Ce,{className:"whitespace-nowrap",onClick:()=>{O(null),E(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Ne&&Ne.length>0&&i.jsxs(vt,{className:"mb-6",children:[i.jsx(In,{children:i.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[i.jsx(Vh,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",at&&i.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),i.jsx(_t,{children:pt?i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(Vh,{className:"w-3 h-3"}),"Current Power"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalPower.toFixed(1),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[pt.reachableCount,"/",pt.totalPlugs," plugs online"]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(na,{className:"w-3 h-3"}),"Today"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalToday.toFixed(3),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalToday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(s3,{className:"w-3 h-3"}),"Yesterday"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalYesterday.toFixed(3),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalYesterday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(Jj,{className:"w-3 h-3"}),"Total"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalLifetime.toFixed(1),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalLifetime*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]})]}):at?null:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),lt?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Ne&&Ne.length>0?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ne.map(ce=>i.jsx(KQe,{plug:ce,onEdit:Et=>{O(Et),E(!0)}},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-12",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(fl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:a("settings.noSmartPlugsTitle")}),i.jsx("p",{className:"text-sm mb-4",children:a("settings.noSmartPlugsDescription")}),i.jsxs(Ce,{onClick:()=>{O(null),E(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addFirstSmartPlug")]})]})})})]}),me==="notifications"&&i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Hg,{className:"w-5 h-5 text-bambu-green"}),a("settings.providers")]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>ae(!0),children:[i.jsx(mv,{className:"w-4 h-4"}),a("settings.log")]}),At&&At.length>0&&i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>{mr(null),uo.mutate()},disabled:uo.isPending,children:[uo.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(WC,{className:"w-4 h-4"}),a("settings.testAll")]}),i.jsxs(Ce,{size:"sm",onClick:()=>{G(null),R(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),"Add"]})]})]}),i.jsx(vt,{className:"mb-4",children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white text-sm font-medium",children:a("settings.notificationLanguage")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.notificationLanguageDescription")})]}),i.jsx("select",{value:C.notification_language||"en",onChange:ce=>Bt("notification_language",ce.target.value),className:"px-2 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:hB.map(ce=>i.jsx("option",{value:ce.code,children:ce.nativeName},ce.code))})]})})}),i.jsx(vt,{className:"mb-4",children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white text-sm font-medium",children:a("settings.bedCooledThreshold")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.bedCooledThresholdDescription")})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"number",min:20,max:80,step:1,value:C.bed_cooled_threshold??35,onChange:ce=>Bt("bed_cooled_threshold",Number(ce.target.value)),className:"w-16 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm text-center focus:outline-none focus:ring-1 focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:"°C"})]})]})})}),Yr&&i.jsx(vt,{className:"mb-4",children:i.jsxs(_t,{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm font-medium text-white",children:a("settings.testResults")}),i.jsx("button",{onClick:()=>mr(null),className:"text-bambu-gray hover:text-white text-xs",children:a("common.dismiss")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[i.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[i.jsx(pr,{className:"w-4 h-4"}),a("settings.testPassedCount",{count:Yr.success})]}),Yr.failed>0&&i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(hi,{className:"w-4 h-4"}),a("settings.testFailedCount",{count:Yr.failed})]})]}),Yr.results.filter(ce=>!ce.success).length>0&&i.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:Yr.results.filter(ce=>!ce.success).map(ce=>i.jsxs("div",{className:"text-xs text-red-400",children:[i.jsxs("span",{className:"font-medium",children:[ce.provider_name,":"]})," ",ce.message]},ce.provider_id))})]})}),Ht?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):At&&At.length>0?i.jsx("div",{className:"space-y-3",children:At.map(ce=>i.jsx(QQe,{provider:ce,onEdit:Et=>{G(Et),R(!0)}},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(Hg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:a("settings.noProvidersTitle")}),i.jsx("p",{className:"text-xs mb-3",children:a("settings.noProvidersDescription")}),i.jsxs(Ce,{size:"sm",onClick:()=>{G(null),R(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addProvider")]})]})})})]}),i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[i.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),a("settings.messageTemplates")]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:a("settings.messageTemplatesDescription")}),jn?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):kn&&kn.length>0?i.jsx("div",{className:"space-y-2",children:[...kn].sort((ce,Et)=>ce.name.localeCompare(Et.name)).map(ce=>i.jsx(vt,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>K(ce),children:i.jsx(_t,{className:"py-2.5 px-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium text-sm truncate",children:ce.name}),i.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ce.title_template})]}),i.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:Et=>{Et.stopPropagation(),K(ce)},children:i.jsx(Jm,{className:"w-4 h-4 text-bambu-gray"})})]})})},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(Ms,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm",children:a("settings.noTemplatesAvailable")})]})})})]})]}),me==="apikeys"&&i.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(nl,{className:"w-5 h-5 text-bambu-green"}),a("settings.apiKeys")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.apiKeysDescription")})]}),i.jsxs(Ce,{size:"sm",onClick:()=>se(!0),className:"flex-shrink-0",children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.createKey")]})]}),Z&&i.jsx(vt,{className:"mb-6 border-bambu-green",children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(pr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:a("settings.apiKeyCreated")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:a("settings.apiKeyCopyWarning")}),i.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[i.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:Z}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(Z);else{const ce=document.createElement("textarea");ce.value=Z,ce.style.position="fixed",ce.style.left="-999999px",document.body.appendChild(ce),ce.select(),document.execCommand("copy"),document.body.removeChild(ce)}o(a("settings.toast.keyCopied"))}catch{o(a("settings.toast.copyFailed"),"error")}},children:i.jsx(Yl,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex gap-2 mt-3",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>{Q(Z),o(a("settings.toast.keyAddedToBrowser"))},children:a("settings.useInApiBrowser")}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>ie(null),children:a("common.dismiss")})]})]})]})})}),_e&&i.jsxs(vt,{className:"mb-6",children:[i.jsx(In,{children:i.jsx("h3",{className:"text-base font-semibold text-white",children:a("settings.createNewApiKey")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.keyName")}),i.jsx("input",{type:"text",value:Oe,onChange:ce=>q(ce.target.value),placeholder:a("settings.keyNamePlaceholder"),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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:a("common.permissions")}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:X.can_read_status,onChange:ce=>de(Et=>({...Et,can_read_status:ce.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.readStatus")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.readStatusDescription")})]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:X.can_queue,onChange:ce=>de(Et=>({...Et,can_queue:ce.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.manageQueue")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.manageQueueDescription")})]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:X.can_control_printer,onChange:ce=>de(Et=>({...Et,can_control_printer:ce.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.controlPrinter")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.controlPrinterDescription")})]})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[i.jsxs(Ce,{onClick:()=>an.mutate({name:Oe||a("settings.unnamedKey"),...X}),disabled:an.isPending,children:[an.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Xn,{className:"w-4 h-4"}),a("settings.createKey")]}),i.jsx(Ce,{variant:"secondary",onClick:()=>se(!1),children:a("common.cancel")})]})]})]}),Pt?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Dt&&Dt.length>0?i.jsx("div",{className:"space-y-3",children:Dt.map(ce=>i.jsx(vt,{children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(nl,{className:`w-5 h-5 ${ce.enabled?"text-bambu-green":"text-bambu-gray"}`}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:ce.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[ce.key_prefix,"••••••••",ce.last_used&&` · ${a("settings.lastUsed")}: ${cb(ce.last_used)}`]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex gap-1 text-xs",children:[ce.can_read_status&&i.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:a("settings.read")}),ce.can_queue&&i.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:a("queue.title")}),ce.can_control_printer&&i.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:a("settings.control")})]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>Fe(ce.id),children:i.jsx(Jt,{className:"w-4 h-4 text-red-400"})})]})]})})},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-12",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(nl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:a("settings.apiKeysEmptyTitle")}),i.jsx("p",{className:"text-sm mb-4",children:a("settings.apiKeysEmptyDescription")}),i.jsxs(Ce,{onClick:()=>se(!0),children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.createFirstKey")]})]})})}),i.jsxs(vt,{className:"mt-6",children:[i.jsx(In,{children:i.jsx("h3",{className:"text-base font-semibold text-white",children:a("settings.webhookEndpoints")})}),i.jsxs(_t,{className:"space-y-3 text-sm",children:[i.jsx("p",{className:"text-bambu-gray",children:a("settings.webhookApiKeyHint")}),i.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-blue-400",children:"GET"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.getAllStatus")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-blue-400",children:"GET"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.getSpecificStatus")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-green-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.addToQueue")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-orange-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.pausePrint")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-orange-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.resumePrint")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-red-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.stopPrint")]})]})]})]})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"mb-6",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Mh,{className:"w-5 h-5 text-bambu-green"}),a("settings.apiBrowser")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.apiBrowserDescription")})]}),i.jsx(vt,{className:"mb-4",children:i.jsxs(_t,{className:"py-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:a("settings.apiKeyForTesting")}),i.jsx("input",{type:"text",value:pe,onChange:ce=>Q(ce.target.value),placeholder:a("settings.apiKeyPlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:a("settings.apiKeyHint")})]})}),i.jsx(wZe,{apiKey:pe})]})]}),me==="virtual-printer"&&i.jsx(hZe,{}),me==="filament"&&C&&i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[i.jsxs("div",{className:"lg:w-1/3 space-y-6",children:[i.jsx(iZe,{}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.amsDisplayThresholds")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.amsThresholdsDescription")}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(wF,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"font-medium",children:a("settings.humidity")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.goodGreen")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_good??40,onChange:ce=>Bt("ams_humidity_good",parseInt(ce.target.value)||40),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"}),i.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.fairOrange")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_fair??60,onChange:ce=>Bt("ams_humidity_fair",parseInt(ce.target.value)||60),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"}),i.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.aboveFairBad")})]}),i.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(XC,{className:"w-4 h-4 text-orange-400"}),i.jsx("span",{className:"font-medium",children:a("settings.temperature")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.goodBlue")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_good??28,onChange:ce=>Bt("ams_temp_good",parseFloat(ce.target.value)||28),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"}),i.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.fairOrange")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_fair??35,onChange:ce=>Bt("ams_temp_fair",parseFloat(ce.target.value)||35),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"}),i.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.aboveFairHot")})]}),i.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(Pc,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"font-medium",children:a("settings.historyRetention")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.keepSensorHistory")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"1",max:"365",value:C.ams_history_retention_days??30,onChange:ce=>Bt("ams_history_retention_days",parseInt(ce.target.value)||30),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:a("common.days")})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.historyRetentionDescription")})]}),i.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(xr,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"font-medium",children:a("settings.printModal")})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-white",children:a("settings.expandCustomMapping")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:a("settings.expandCustomMappingDescription")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.per_printer_mapping_expanded??!1,onChange:ce=>Bt("per_printer_mapping_expanded",ce.target.checked),className:"sr-only peer"}),i.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"})]})]})]})]})]})]}),i.jsxs("div",{className:"lg:w-2/3 space-y-6",children:[i.jsx(sZe,{}),i.jsx(oZe,{})]})]})}),le!==null&&i.jsx(gn,{title:a("settings.deleteApiKeyTitle"),message:a("settings.deleteApiKeyMessage"),confirmText:a("settings.deleteKey"),variant:"danger",onConfirm:()=>{Zt.mutate(le),Fe(null)},onCancel:()=>Fe(null)}),P&&i.jsx(XQe,{plug:B,onClose:()=>{E(!1),O(null)}}),U&&i.jsx(ZQe,{provider:V,onClose:()=>{R(!1),G(null)}}),z&&i.jsx(JQe,{template:z,onClose:()=>K(null)}),Y&&i.jsx(nZe,{onClose:()=>ae(!1)}),L&&i.jsx(gn,{title:a("settings.clearNotificationLogs"),message:a("settings.clearLogsMessage"),confirmText:a("settings.clearLogs"),variant:"warning",onConfirm:async()=>{D(!1);try{const ce=await ne.clearNotificationLogs(30);o(ce.message,"success")}catch{o(a("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>D(!1)}),H&&i.jsx(gn,{title:a("settings.resetUiPreferences"),message:a("settings.resetUiPreferencesMessage"),confirmText:a("settings.resetPreferences"),variant:"default",onConfirm:()=>{he(!1),localStorage.clear(),o(a("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>he(!1)}),be&&i.jsx(gn,{title:`Turn All Plugs ${be==="on"?"On":"Off"}`,message:`This will turn ${be==="on"?"ON":"OFF"} all ${Ne?.filter(ce=>ce.enabled).length||0} enabled smart plugs. ${be==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${be==="on"?"On":"Off"}`,variant:be==="off"?"danger":"warning",onConfirm:()=>{const ce=be;fe(null),qa.mutate(ce)},onCancel:()=>fe(null)}),ze&&pn?.release_notes&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Ie(!1),children:i.jsxs(vt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ce=>ce.stopPropagation(),children:[i.jsxs(In,{className:"flex flex-row items-center justify-between shrink-0",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",pn.latest_version]}),pn.release_name&&pn.release_name!==pn.latest_version&&i.jsx("p",{className:"text-sm text-bambu-gray",children:pn.release_name})]}),i.jsx("button",{onClick:()=>Ie(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsx(_t,{className:"overflow-y-auto flex-1",children:i.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:pn.release_notes})}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[pn.release_url&&i.jsx("a",{href:pn.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:i.jsxs(Ce,{variant:"secondary",className:"w-full",children:[i.jsx(Kr,{className:"w-4 h-4"}),"View on GitHub"]})}),i.jsx(Ce,{onClick:()=>Ie(!1),className:"flex-1",children:"Close"})]})]})}),me==="users"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex gap-1 border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>ue("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${je==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(hh,{className:"w-4 h-4"}),a("settings.tabs.users")]}),i.jsxs("button",{onClick:()=>ue("email"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${je==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(fv,{className:"w-4 h-4"}),a("settings.tabs.emailAuth")||"Email Authentication",Rt?.advanced_auth_enabled&&i.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]})]}),je==="users"&&i.jsxs(i.Fragment,{children:[i.jsx(vt,{children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?i.jsx(zm,{className:"w-5 h-5 text-green-400"}):i.jsx(I_,{className:"w-5 h-5 text-gray-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-white font-medium",children:a("settings.authentication")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&i.jsxs(Ce,{variant:"secondary",onClick:()=>tt(!0),children:[i.jsx(I_,{className:"w-4 h-4"}),a("common.disable")]}):i.jsxs(Ce,{onClick:()=>e("/setup"),children:[i.jsx(zm,{className:"w-4 h-4"}),a("common.enable")]})]})})}),Rt?.advanced_auth_enabled&&i.jsx(vt,{className:"border-blue-500/30 bg-blue-500/5",children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:i.jsx(fv,{className:"w-5 h-5 text-blue-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-white font-medium",children:a("settings.email.advancedAuthEnabled")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&i.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"space-y-6",children:[c&&i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(hh,{className:"w-5 h-5 text-bambu-green"}),a("settings.currentUser")]}),i.jsxs(Ce,{size:"sm",variant:"ghost",onClick:()=>Se(!0),children:[i.jsx(nl,{className:"w-4 h-4"}),a("settings.changePassword")]})]})}),i.jsx(_t,{children:i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&i.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:a("settings.admin")}),c.groups?.map(ce=>i.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${ce.name==="Administrators"?"bg-purple-500/20 text-purple-300":ce.name==="Operators"?"bg-blue-500/20 text-blue-300":ce.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:ce.name},ce.id))]})]})})})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(hh,{className:"w-5 h-5 text-bambu-green"}),a("settings.users")]}),bn("users:create")&&i.jsxs(Ce,{size:"sm",onClick:()=>{Ge(!0),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addUser")]})]})}),i.jsx(_t,{children:Zn?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Nt.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8",children:a("settings.noUsersFound")}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Nt.map(ce=>i.jsxs("div",{className:"py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-white font-medium truncate",children:ce.username}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[ce.is_admin&&i.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:a("settings.admin")}),ce.groups?.map(Et=>i.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${Et.name==="Administrators"?"bg-purple-500/20 text-purple-300":Et.name==="Operators"?"bg-blue-500/20 text-blue-300":Et.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:Et.name},Et.id))]})]}),i.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[bn("users:update")&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>rs(ce),children:i.jsx(Jm,{className:"w-4 h-4"})}),bn("users:delete")&&ce.id!==c?.id&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>Ss(ce.id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},ce.id))})})]})]}),i.jsx("div",{children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(i3,{className:"w-5 h-5 text-bambu-green"}),a("settings.groups")]}),bn("groups:create")&&i.jsxs(Ce,{size:"sm",onClick:()=>e("/groups/new"),children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addGroup")]})]})}),i.jsx(_t,{children:hr?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):vr.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8",children:a("settings.noGroupsFound")}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:vr.map(ce=>i.jsxs("div",{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(i3,{className:`w-4 h-4 ${ce.name==="Administrators"?"text-purple-400":ce.name==="Operators"?"text-blue-400":ce.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),i.jsx("span",{className:"text-white font-medium",children:ce.name}),ce.is_system&&i.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:a("settings.system")})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[bn("groups:update")&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>e(`/groups/${ce.id}/edit`),children:i.jsx(Jm,{className:"w-4 h-4"})}),bn("groups:delete")&&!ce.is_system&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>yr(ce.id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:ce.description||a("settings.noDescription")}),i.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[i.jsx("span",{children:a("settings.userCount",{count:ce.user_count})}),i.jsx("span",{children:a("settings.permissionCount",{count:ce.permissions.length})})]})]},ce.id))})})]})})]}),!l&&i.jsx(vt,{children:i.jsx(_t,{className:"py-6",children:i.jsxs("div",{className:"text-center",children:[i.jsx(I_,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:a("settings.authDisabledTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:a("settings.authDisabledMessage")}),i.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature1")})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature2")})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature3")})]})]}),i.jsxs(Ce,{onClick:()=>e("/setup"),children:[i.jsx(zm,{className:"w-4 h-4"}),a("settings.enableAuthentication")]})]})})})]}),je==="email"&&i.jsx("div",{className:"max-w-2xl",children:i.jsx(bZe,{})})]}),Te&&!Rt?.advanced_auth_enabled&&i.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(hh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.createUser")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.username")}),i.jsx("input",{type:"text",value:wt.username,onChange:ce=>qt({...wt,username:ce.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:a("settings.enterUsername"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.password")}),i.jsx("input",{type:"password",value:wt.password,onChange:ce=>qt({...wt,password:ce.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:a("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.confirmPassword")}),i.jsx("input",{type:"password",value:wt.confirmPassword,onChange:ce=>qt({...wt,confirmPassword:ce.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${wt.confirmPassword&&wt.password!==wt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),wt.confirmPassword&&wt.password!==wt.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),i.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:[vr.map(ce=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:wt.group_ids.includes(ce.id),onChange:()=>si(ce.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:ce.name}),ce.is_system&&i.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},ce.id)),vr.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.noGroupsAvailable")})]})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),i.jsx(Ce,{onClick:ns,disabled:wa.isPending||!wt.username||!wt.password||wt.password!==wt.confirmPassword||wt.password.length<6,children:wa.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Xn,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),Te&&Rt?.advanced_auth_enabled&&i.jsx(aZe,{formData:wt,setFormData:qt,groups:vr,onClose:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:ns,isCreating:wa.isPending,isCreateButtonDisabled:wa.isPending||!wt.username||!wt.email}),Re&&Ke!==null&&i.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Jm,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.editUser")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("settings.username")," ",Rt?.advanced_auth_enabled&&i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"text",value:wt.username,onChange:ce=>qt({...wt,username:ce.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:a("settings.enterUsername"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("users.form.email")||"Email"," ",Rt?.advanced_auth_enabled?i.jsx("span",{className:"text-red-400",children:"*"}):i.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("users.form.optional")||"optional",")"]})]}),i.jsx("input",{type:"email",value:wt.email,onChange:ce=>qt({...wt,email:ce.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:a("users.form.emailPlaceholder")||"user@example.com",required:Rt?.advanced_auth_enabled})]}),!Rt?.advanced_auth_enabled&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("users.form.password")||"Password"," ",i.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),i.jsx("input",{type:"password",value:wt.password,onChange:ce=>qt({...wt,password:ce.target.value,confirmPassword:""}),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:a("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),wt.password&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.confirmPassword")}),i.jsx("input",{type:"password",value:wt.confirmPassword,onChange:ce=>qt({...wt,confirmPassword:ce.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${wt.confirmPassword&&wt.password!==wt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),wt.confirmPassword&&wt.password!==wt.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]})]}),Rt?.advanced_auth_enabled&&i.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>Ke&&xn.mutate(Ke),disabled:xn.isPending||!wt.email,className:"w-full",children:xn.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("users.form.resettingPassword")||"Resetting Password..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Fo,{className:"w-4 h-4"}),a("users.form.resetPassword")||"Reset Password"]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("users.form.groups")||"Groups"}),i.jsx("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:vr.map(ce=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:wt.group_ids.includes(ce.id),onChange:()=>si(ce.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:ce.name}),ce.is_system&&i.jsxs("span",{className:"text-xs text-yellow-400",children:["(",a("users.system")||"System",")"]})]},ce.id))})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a("users.modal.cancel")||"Cancel"}),i.jsx(Ce,{onClick:()=>Tl(Ke),disabled:Va.isPending||!wt.username||Rt?.advanced_auth_enabled&&!wt.email||!!(!Rt?.advanced_auth_enabled&&wt.password&&(wt.password!==wt.confirmPassword||wt.password.length<6)),children:Va.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("users.modal.saving")||"Saving..."]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),a("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),kt!==null&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{Lt(null),Mt(null)},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[i.jsx(Jt,{className:"w-5 h-5"}),i.jsx("h3",{className:"text-lg font-semibold",children:a("settings.deleteUserTitle")})]})}),i.jsx(_t,{className:"space-y-4",children:Ue?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):Kt&&Kt.archives+Kt.queue_items+Kt.library_files>0?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-white",children:a("settings.userHasCreated")}),i.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[Kt.archives>0&&i.jsxs("li",{children:[Kt.archives," archive",Kt.archives!==1?"s":""]}),Kt.queue_items>0&&i.jsxs("li",{children:[Kt.queue_items," queue item",Kt.queue_items!==1?"s":""]}),Kt.library_files>0&&i.jsxs("li",{children:[Kt.library_files," library file",Kt.library_files!==1?"s":""]})]}),i.jsx("p",{className:"text-bambu-gray text-sm",children:a("settings.userItemsQuestion")}),i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(Ce,{variant:"danger",onClick:()=>$t.mutate({id:kt,deleteItems:!0}),disabled:$t.isPending,className:"justify-center",children:"Delete user AND their items"}),i.jsx(Ce,{variant:"secondary",onClick:()=>$t.mutate({id:kt,deleteItems:!1}),disabled:$t.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),i.jsx(Ce,{variant:"ghost",onClick:()=>{Lt(null),Mt(null)},disabled:$t.isPending,className:"justify-center",children:"Cancel"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-white",children:a("settings.deleteUserConfirm")}),i.jsx("p",{className:"text-bambu-gray text-sm",children:a("settings.actionCannotBeUndone")}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(Ce,{variant:"ghost",onClick:()=>{Lt(null),Mt(null)},disabled:$t.isPending,children:"Cancel"}),i.jsx(Ce,{variant:"danger",onClick:()=>$t.mutate({id:kt,deleteItems:!1}),disabled:$t.isPending,children:"Delete User"})]})]})})]})}),Cn!==null&&i.jsx(gn,{title:a("settings.deleteGroupTitle"),message:a("settings.deleteGroupMessage"),confirmText:a("settings.deleteGroup"),variant:"danger",onConfirm:()=>{Ci.mutate(Cn),yr(null)},onCancel:()=>yr(null)}),me==="backup"&&i.jsx(fZe,{}),qe&&i.jsx(gn,{title:a("settings.disableAuthenticationTitle"),message:a("settings.disableAuthenticationMessage"),confirmText:a("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ne.disableAuth(),o(a("settings.toast.authDisabled"),"success"),await u(),tt(!1),window.location.href="/"}catch(ce){const Et=ce instanceof Error?ce.message:a("settings.toast.authDisableFailed");o(Et,"error")}},onCancel:()=>tt(!1)}),Ee&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(nl,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.changePassword")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),i.jsx("input",{type:"password",value:Me.currentPassword,onChange:ce=>xe({...Me,currentPassword:ce.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:a("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),i.jsx("input",{type:"password",value:Me.newPassword,onChange:ce=>xe({...Me,newPassword:ce.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:a("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),i.jsx("input",{type:"password",value:Me.confirmPassword,onChange:ce=>xe({...Me,confirmPassword:ce.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${Me.confirmPassword&&Me.newPassword!==Me.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Me.confirmPassword&&Me.newPassword!==Me.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),i.jsx(Ce,{onClick:async()=>{if(Me.newPassword!==Me.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(Me.newPassword.length<6){o(a("settings.toast.passwordTooShort"),"error");return}He(!0);try{await ne.changePassword(Me.currentPassword,Me.newPassword),o(a("settings.toast.passwordChanged"),"success"),Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ce){const Et=ce instanceof Error?ce.message:"Failed to change password";o(Et,"error")}finally{He(!1)}},disabled:ve||!Me.currentPassword||!Me.newPassword||Me.newPassword!==Me.confirmPassword||Me.newPassword.length<6,children:ve?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(nl,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const Rie=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},CZe=t=>t.startsWith("HH")?"HF":"S",kZe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},Fie=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const r of e)if(t.startsWith(r))return t.slice(r.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function Nj({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:a,onToggleSelect:s,note:o}){const l=CZe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&s?s():e()};return i.jsxs("div",{className:"flex items-center gap-2",children:[r&&i.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:a?i.jsx(so,{className:"w-4 h-4 text-bambu-green"}):i.jsx(vl,{className:"w-4 h-4"})}),i.jsxs("button",{onClick:u,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${a?"ring-1 ring-bambu-green":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:Rie(t.k_value)}),i.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&i.jsx("span",{title:"Has note",children:i.jsx(uX,{className:"w-3 h-3 text-yellow-500"})}),i.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&i.jsxs("div",{className:"text-xs mt-0.5 truncate text-yellow-500/70",title:o,children:["Note: ",o.length>50?o.substring(0,50)+"...":o]})]}),!r&&n&&i.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:i.jsx(Yl,{className:"w-4 h-4"})})]})}function Cj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],builtinFilaments:a=[],isDualNozzle:s=!1,initialNote:o="",initialNoteKey:l=null,onClose:c,onSave:u,onSaveNote:d,hasPermission:h}){const{t:f}=Ut(),{showToast:p}=cn(),[x,v]=w.useState(t?.name||""),[g,y]=w.useState(t?.k_value?Rie(t.k_value):"0.020"),[_,N]=w.useState(t?.filament_id||""),[k,A]=w.useState(t?.nozzle_id?kZe(t.nozzle_id):"HH00"),[M,C]=w.useState(t?.nozzle_diameter||n),[j,P]=w.useState(t?[t.extruder_id]:s?[0,1]:[0]),[E,B]=w.useState(!1),[O,U]=w.useState({current:0,total:0}),[R,V]=w.useState(o),G=Br.useMemo(()=>{const ee=new Map;for(const ye of a)ee.set(ye.filament_id,ye.name);const J=new Map;for(const ye of r)if(ye.filament_id&&!J.has(ye.filament_id)){const te=ee.get(ye.filament_id)||Fie(ye.name||"");J.set(ye.filament_id,{id:ye.filament_id,name:te||ye.filament_id})}return Array.from(J.values()).sort((ye,me)=>ye.name.localeCompare(me.name))},[r,a]),z=ot({mutationFn:ee=>(console.log("[KProfile] Calling API..."),ne.setKProfile(e,ee)),onSuccess:ee=>{if(console.log("[KProfile] Save success:",ee),p(f("kProfiles.toast.profileSaved")),d&&R!==o){let J;R===""&&l?J=l:t&&t.slot_id>0?J=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:J=`name_${x}_${_}`,d(J,R)}B(!0),setTimeout(()=>{B(!1),u()},2500)},onError:ee=>{console.error("[KProfile] Save error:",ee),p(ee.message,"error"),B(!1)}}),K=ot({mutationFn:ee=>(console.log("[KProfile] Deleting profile..."),ne.deleteKProfile(e,ee)),onSuccess:ee=>{console.log("[KProfile] Delete success:",ee),p(f("kProfiles.toast.profileDeleted")),B(!0),setTimeout(()=>{B(!1),c()},4e3)},onError:ee=>{console.error("[KProfile] Delete error:",ee),p(ee.message,"error"),B(!1)}}),[Y,ae]=w.useState(!1),$=()=>{t&&K.mutate({slot_id:t.slot_id,extruder_id:t.extruder_id,nozzle_id:t.nozzle_id,nozzle_diameter:t.nozzle_diameter,filament_id:t.filament_id,setting_id:t.setting_id})},W=async ee=>{if(ee.preventDefault(),s&&!t&&j.length===0){p(f("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const J=parseFloat(g).toFixed(6),ye=`${k}-${M}`;if(t||j.length===1){const te={name:x,k_value:J,filament_id:_,nozzle_id:ye,nozzle_diameter:M,extruder_id:t?t.extruder_id:j[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",te),z.mutate(te);return}B(!0),U({current:1,total:j.length});const me=j.map(te=>({name:x,k_value:J,filament_id:_,nozzle_id:ye,nozzle_diameter:M,extruder_id:te,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${me.length} profiles in batch:`,me);try{if(await ne.setKProfilesBatch(e,me),p(f("kProfiles.toast.profilesSaved",{count:j.length})),d&&R){const te=`name_${x}_${_}`;d(te,R)}}catch(te){console.error("[KProfile] Failed to save batch:",te),p(f("kProfiles.toast.failedToSaveBatch"),"error"),B(!1),U({current:0,total:0});return}U({current:j.length,total:j.length}),setTimeout(()=>{B(!1),U({current:0,total:0}),u()},3e3)};return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[i.jsxs(vt,{className:"w-full max-w-md relative",children:[E&&i.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),i.jsx("p",{className:"text-white font-medium",children:O.total>1?f("kProfiles.modal.savingExtruder",{current:O.current,total:O.total}):f("kProfiles.modal.syncing")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:f("kProfiles.modal.pleaseWait")})]}),i.jsxs(_t,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:f(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),i.jsx("button",{onClick:c,className:"text-bambu-gray hover:text-white transition-colors",disabled:E,children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:W,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.profileName")}),i.jsx("input",{type:"text",value:x,onChange:ee=>v(ee.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:f("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.kValue")}),i.jsx("input",{type:"text",inputMode:"decimal",value:g,onChange:ee=>{const J=ee.target.value;(J===""||/^\d*\.?\d*$/.test(J))&&y(J)},onBlur:ee=>{const J=parseFloat(ee.target.value);isNaN(J)||y((Math.trunc(J*1e3)/1e3).toFixed(3))},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 font-mono",placeholder:f("kProfiles.modal.kValuePlaceholder"),required:!0}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.kValueHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.filament")}),i.jsxs("select",{value:_,onChange:ee=>{const J=ee.target.value;if(N(J),!t&&J&&!x){const ye=G.find(me=>me.id===J);ye&&v(`${k==="HH00"?"HF":"S"} ${ye.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,required:!t,children:[i.jsx("option",{value:"",children:f("kProfiles.modal.selectFilament")}),t?.filament_id&&i.jsx("option",{value:t.filament_id,children:G.find(ee=>ee.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&G.map(ee=>i.jsx("option",{value:ee.id,children:ee.name},ee.id))]}),!t&&G.length===0&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.noFilamentsHelp")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.flowType")}),i.jsxs("select",{value:k,onChange:ee=>{const J=ee.target.value;if(A(J),!t&&_&&!x){const ye=G.find(me=>me.id===_);ye&&v(`${J==="HS00"?"HF":"S"} ${ye.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[i.jsx("option",{value:"HH00",children:f("kProfiles.modal.highFlow")}),i.jsx("option",{value:"HS00",children:f("kProfiles.modal.standard")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.nozzleSize")}),i.jsxs("select",{value:M,onChange:ee=>C(ee.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[i.jsx("option",{value:"0.2",children:"0.2mm"}),i.jsx("option",{value:"0.4",children:"0.4mm"}),i.jsx("option",{value:"0.6",children:"0.6mm"}),i.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),s&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?i.jsx("div",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white opacity-60",children:t.extruder_id===1?f("kProfiles.modal.left"):f("kProfiles.modal.right")}):i.jsxs("div",{className:"flex gap-4",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:j.includes(1),onChange:ee=>{ee.target.checked?P([...j,1]):P(j.filter(J=>J!==1))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),i.jsx("span",{className:"text-white",children:f("kProfiles.modal.left")})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:j.includes(0),onChange:ee=>{ee.target.checked?P([...j,0]):P(j.filter(J=>J!==0))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),i.jsx("span",{className:"text-white",children:f("kProfiles.modal.right")})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.notes")}),i.jsx("textarea",{value:R,onChange:ee=>V(ee.target.value),placeholder:f("kProfiles.modal.notesPlaceholder"),rows:2,className:"w-full px-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 resize-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.notesHelp")})]}),i.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>ae(!0),disabled:K.isPending||E||!h("kprofiles:delete"),title:h("kprofiles:delete")?void 0:f("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:K.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"})}),i.jsx(Ce,{type:"button",variant:"secondary",onClick:c,disabled:E,className:"flex-1",children:f("common.cancel")}),i.jsxs(Ce,{type:"submit",disabled:z.isPending||E||!h(t?"kprofiles:update":"kprofiles:create"),title:h(t?"kprofiles:update":"kprofiles:create")?void 0:f(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[z.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(BC,{className:"w-4 h-4"}),f("common.save")]})]})]})]})]}),Y&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:i.jsx(vt,{className:"w-full max-w-sm",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx(Jt,{className:"w-5 h-5 text-red-500"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:f("kProfiles.deleteConfirm.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:f("kProfiles.deleteConfirm.cannotUndo")})]})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:f("kProfiles.deleteConfirm.message",{name:t?.name})}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>ae(!1),className:"flex-1",children:f("common.cancel")}),i.jsxs(Ce,{onClick:()=>{ae(!1),$()},disabled:K.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[K.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),f("common.delete")]})]})]})})})]})}const F_={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function AZe(){const{t}=Ut(),{showToast:e}=cn(),{hasPermission:n}=Or(),[r,a]=w.useState(null),[s,o]=w.useState(()=>localStorage.getItem(F_.NOZZLE_DIAMETER)||"0.4"),[l,c]=w.useState(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,g]=w.useState("all"),[y,_]=w.useState("all"),[N,k]=w.useState(()=>localStorage.getItem(F_.SORT_OPTION)||"name"),[A,M]=w.useState(!1),[C,j]=w.useState(new Set),[P,E]=w.useState(!1),[B,O]=w.useState(!1),U=w.useCallback(D=>`${D.slot_id}_${D.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(F_.NOZZLE_DIAMETER,s)},[s]),w.useEffect(()=>{localStorage.setItem(F_.SORT_OPTION,N)},[N]);const{data:R,isLoading:V}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:G,isLoading:z,isFetching:K,error:Y,refetch:ae}=Je({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const D=await ne.getKProfiles(r,s);return console.log("[KProfiles] Received profiles:",D?.profiles?.length||0,"profiles"),D},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:$}=Je({queryKey:["kprofiles",r,"0.4"],queryFn:()=>ne.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:W}=Je({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),staleTime:3e5}),{data:ee}=Je({queryKey:["filamentIdMap"],queryFn:()=>ne.getFilamentIdMap(),staleTime:3e5}),{data:J,refetch:ye}=Je({queryKey:["kprofile-notes",r],queryFn:()=>ne.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),me=Y?.message?.includes("not connected");w.useEffect(()=>{if(!r&&R&&R.length>0){const D=R.find(H=>H.is_active);D&&a(D.id)}},[r,R]),w.useEffect(()=>{if(r){const D=setTimeout(()=>{ae()},150);return()=>clearTimeout(D)}},[r,s]);const te=R?.filter(D=>D.is_active)||[],je=Br.useMemo(()=>{const D=new Map;if(W)for(const H of W)D.set(H.filament_id,H.name);if(ee)for(const[H,he]of Object.entries(ee))D.has(H)||D.set(H,he);return D},[W,ee]),ue=Br.useMemo(()=>Array.from(je.entries()).map(([D,H])=>({filament_id:D,name:H})),[je]),oe=Br.useCallback(D=>je.get(D.filament_id)||Fie(D.name),[je]),_e=Br.useMemo(()=>G?.profiles?G.profiles.filter(H=>{const he=p.toLowerCase(),be=!he||H.name.toLowerCase().includes(he)||H.filament_id.toLowerCase().includes(he),fe=v==="all"||v==="left"&&H.extruder_id===1||v==="right"&&H.extruder_id===0,ze=y==="all"||y==="hf"&&H.nozzle_id.startsWith("HH")||y==="s"&&H.nozzle_id.startsWith("HS");return be&&fe&&ze}).sort((H,he)=>{switch(N){case"k_value":return parseFloat(H.k_value)-parseFloat(he.k_value);case"filament":return oe(H).localeCompare(oe(he));default:return H.name.localeCompare(he.name)}}):[],[G?.profiles,p,v,y,N,oe]),se=R?.find(D=>D.id===r),Oe=se?.nozzle_count===2;w.useEffect(()=>{const D=H=>{H.target instanceof HTMLInputElement||H.target instanceof HTMLTextAreaElement||H.target instanceof HTMLSelectElement||l||u||h||(H.key==="r"||H.key==="R"?(H.preventDefault(),ae()):H.key==="n"||H.key==="N"?(H.preventDefault(),d(!0)):H.key==="Escape"&&A&&(H.preventDefault(),M(!1),j(new Set)))};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[l,u,h,A,ae]);const q=w.useCallback(()=>{if(!G?.profiles||G.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const D={version:1,exported_at:new Date().toISOString(),printer:se?.name||"Unknown",nozzle_diameter:s,profiles:G.profiles.map(fe=>({name:fe.name,k_value:fe.k_value,filament_id:fe.filament_id,nozzle_id:fe.nozzle_id,nozzle_diameter:fe.nozzle_diameter,extruder_id:fe.extruder_id}))},H=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),he=URL.createObjectURL(H),be=document.createElement("a");be.href=he,be.download=`kprofiles_${se?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(be),be.click(),document.body.removeChild(be),URL.revokeObjectURL(he),e(t("kProfiles.toast.exportedProfiles",{count:G.profiles.length}))},[G?.profiles,se,s,e,t]),X=w.useCallback(()=>{const D=document.createElement("input");D.type="file",D.accept=".json",D.onchange=async H=>{const he=H.target.files?.[0];if(he)try{const be=await he.text(),fe=JSON.parse(be);if(!fe.profiles||!Array.isArray(fe.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let ze=0;for(const Ie of fe.profiles)if(!(!Ie.name||!Ie.k_value||!Ie.filament_id))try{await ne.setKProfile(r,{name:Ie.name,k_value:parseFloat(Ie.k_value).toFixed(6),filament_id:Ie.filament_id,nozzle_id:Ie.nozzle_id||`HH00-${s}`,nozzle_diameter:Ie.nozzle_diameter||s,extruder_id:Ie.extruder_id??0,slot_id:0}),ze++,await new Promise(qe=>setTimeout(qe,500))}catch(qe){console.error("Failed to import profile:",Ie.name,qe)}e(t("kProfiles.toast.importedProfiles",{count:ze,total:fe.profiles.length})),ae()}catch(be){console.error("Import error:",be),e(t("kProfiles.toast.failedToParseImport"),"error")}},D.click()},[r,s,e,ae,t]),de=w.useCallback(D=>{j(H=>{const he=new Set(H);return he.has(D)?he.delete(D):he.add(D),he})},[]),Z=w.useCallback(()=>{j(new Set(_e.map(D=>U(D))))},[_e,U]),ie=w.useCallback(()=>{C.size!==0&&E(!0)},[C.size]),le=w.useCallback(async()=>{const D=_e.filter(he=>C.has(U(he)));O(!0);let H=0;for(const he of D)try{await ne.deleteKProfile(r,{slot_id:he.slot_id,extruder_id:he.extruder_id,nozzle_id:he.nozzle_id,nozzle_diameter:he.nozzle_diameter,filament_id:he.filament_id,setting_id:he.setting_id}),H++,await new Promise(be=>setTimeout(be,300))}catch(be){console.error("Failed to delete profile:",he.name,be)}e(t("kProfiles.toast.profilesDeleted",{count:H})),O(!1),E(!1),M(!1),j(new Set),ae()},[r,C,_e,e,ae,U,t]),Fe=w.useCallback(D=>{const H=[];return D.setting_id&&H.push(D.setting_id),H.push(`slot_${D.slot_id}_${D.filament_id}_${D.extruder_id}`),H.push(`name_${D.name}_${D.filament_id}`),H},[]),pe=w.useCallback(async(D,H)=>{if(r)try{await ne.setKProfileNote(r,D,H),ye()}catch(he){console.error("Failed to save note:",he),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,ye,e,t]),Q=w.useCallback(D=>{if(!J?.notes)return{note:"",key:null};const H=Fe(D);for(const he of H)if(J.notes[he])return{note:J.notes[he],key:he};return{note:"",key:null}},[J,Fe]),L=w.useCallback(D=>Q(D).note,[Q]);return V?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!R||R.length===0?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(Ba,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):te.length===0?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(xr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):i.jsxs(i.Fragment,{children:[K&&!z&&i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[i.jsx(it,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),i.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),i.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1 min-w-48",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),i.jsx("select",{value:r||"",onChange:D=>a(parseInt(D.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:te.map(D=>i.jsx("option",{value:D.id,children:D.name},D.id))})]}),i.jsxs("div",{className:"w-32",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),i.jsxs("select",{value:s,onChange:D=>o(D.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:[i.jsx("option",{value:"0.2",children:"0.2mm"}),i.jsx("option",{value:"0.4",children:"0.4mm"}),i.jsx("option",{value:"0.6",children:"0.6mm"}),i.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),i.jsxs("div",{className:"flex items-end gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:()=>ae(),disabled:K||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[i.jsx(Cr,{className:`w-4 h-4 ${K?"animate-spin":""}`}),t("kProfiles.refresh")]}),i.jsxs(Ce,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[i.jsx(Xn,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),i.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[i.jsxs("div",{className:"flex-1 min-w-48 relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:p,onChange:D=>x(D.target.value),placeholder:t("kProfiles.searchPlaceholder"),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"})]}),Oe&&i.jsx("div",{className:"w-36",children:i.jsxs("select",{value:v,onChange:D=>g(D.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:[i.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),i.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),i.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),i.jsx("div",{className:"w-32",children:i.jsxs("select",{value:y,onChange:D=>_(D.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:[i.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),i.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),i.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),i.jsx("div",{className:"w-32",children:i.jsxs("select",{value:N,onChange:D=>k(D.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:[i.jsx("option",{value:"name",children:t("kProfiles.sortName")}),i.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),i.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[i.jsxs(Ce,{variant:"secondary",onClick:q,disabled:!G?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[i.jsx(ua,{className:"w-4 h-4"}),t("kProfiles.export")]}),i.jsxs(Ce,{variant:"secondary",onClick:X,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[i.jsx(Ra,{className:"w-4 h-4"}),t("kProfiles.import")]}),i.jsx("div",{className:"flex-1"}),A?i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",onClick:Z,children:[i.jsx(so,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),i.jsxs(Ce,{variant:"secondary",onClick:ie,disabled:C.size===0||!n("kprofiles:delete"),className:"text-red-500 hover:bg-red-500/10",title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[i.jsx(Jt,{className:"w-4 h-4"}),t("kProfiles.delete")," (",C.size,")"]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>{M(!1),j(new Set)},children:[i.jsx(Ft,{className:"w-4 h-4"}),t("common.cancel")]})]}):i.jsxs(Ce,{variant:"secondary",onClick:()=>M(!0),disabled:!_e.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[i.jsx(so,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),z?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):me?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(Pf,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),i.jsxs(Ce,{variant:"secondary",onClick:()=>ae(),children:[i.jsx(Cr,{className:"w-4 h-4"}),t("common.refresh")]})]})}):_e.length>0?Oe?i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),i.jsx("div",{className:"space-y-1",children:_e.filter(D=>D.extruder_id===1).map(D=>i.jsx(Nj,{profile:D,onEdit:()=>c(D),onCopy:()=>f(D),selectionMode:A,isSelected:C.has(U(D)),onToggleSelect:()=>de(U(D)),note:L(D)},U(D)))})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),i.jsx("div",{className:"space-y-1",children:_e.filter(D=>D.extruder_id===0).map(D=>i.jsx(Nj,{profile:D,onEdit:()=>c(D),onCopy:()=>f(D),selectionMode:A,isSelected:C.has(U(D)),onToggleSelect:()=>de(U(D)),note:L(D)},U(D)))})]})]}):i.jsx("div",{className:"space-y-1",children:_e.map(D=>i.jsx(Nj,{profile:D,onEdit:()=>c(D),onCopy:()=>f(D),selectionMode:A,isSelected:C.has(U(D)),onToggleSelect:()=>de(U(D)),note:L(D)},U(D)))}):p||v!=="all"||y!=="all"?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(kr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(BC,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),i.jsxs(Ce,{onClick:()=>d(!0),children:[i.jsx(Xn,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:D,key:H}=Q(l);return i.jsx(Cj,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:$?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Oe,initialNote:D,initialNoteKey:H,onSaveNote:pe,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),ae()},onSave:()=>{c(null),ae()}})})(),u&&r&&i.jsx(Cj,{printerId:r,nozzleDiameter:s,existingProfiles:$?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Oe,onSaveNote:pe,hasPermission:n,onClose:()=>{d(!1),ae()},onSave:()=>{d(!1),ae()}}),h&&r&&i.jsx(Cj,{printerId:r,nozzleDiameter:s,existingProfiles:$?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Oe,onSaveNote:pe,hasPermission:n,profile:{...h,slot_id:0,name:`${h.name} (Copy)`},onClose:()=>{f(null),ae()},onSave:()=>{f(null),ae()}}),P&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-sm",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx(Jt,{className:"w-5 h-5 text-red-500"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:C.size})}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>E(!1),disabled:B,className:"flex-1",children:t("common.cancel")}),i.jsxs(Ce,{onClick:le,disabled:B,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[B?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const Lie=["PLA","PETG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],TZe={PLA:"E8E8E8",PETG:"4A90D9",ABS:"E67E22",ASA:"D35400",TPU:"9B59B6",PC:"BDC3C7",PA:"2ECC71",NYLON:"2ECC71",PVA:"F1C40F",HIPS:"95A5A6",PP:"ECF0F1",PET:"3498DB"};function MZe(t){const e=t.toUpperCase();for(const n of Lie)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function PZe(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of Lie){const a=n.indexOf(r);if(a>0){const s=e.slice(0,a).trim();if(s&&s.length>1)return s}}return null}function kj({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:a}=Ut(),{hasPermission:s}=Or(),o=t.filament_type||MZe(t.name),l=t.filament_vendor||PZe(t.name);let c=null,u=!1;if(t.default_filament_colour)try{const d=JSON.parse(t.default_filament_colour),h=Array.isArray(d)?d[0]:d;typeof h=="string"&&/^#?[0-9a-fA-F]{6,8}$/.test(h.replace("#",""))&&(c=h.replace("#","").slice(0,6),u=!0)}catch{const d=t.default_filament_colour;/^#?[0-9a-fA-F]{6,8}$/.test(d.replace("#",""))&&(c=d.replace("#","").slice(0,6),u=!0)}return!c&&o&&(c=TZe[o.toUpperCase()]||null),i.jsx(vt,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:i.jsxs(_t,{className:"p-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&i.jsx("div",{className:`w-4 h-4 rounded-full border border-white/20 flex-shrink-0 ${!u&&!c?"opacity-25":u?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),i.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&i.jsx("span",{className:"text-xs text-bambu-gray",children:l}),i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:a("profiles.localProfiles.badge")})]})]}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&i.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:a("profiles.localProfiles.delete"),children:i.jsx(Jt,{className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?i.jsx(yl,{className:"w-3.5 h-3.5"}):i.jsx(Un,{className:"w-3.5 h-3.5"})})]})]}),r&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.filamentType")}),i.jsx("span",{className:"text-white",children:o})]}),l&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.vendor")}),i.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.nozzleTemp")}),i.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.cost")}),i.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.density")}),i.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.pressureAdvance")}),i.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.compatiblePrinters")}),i.jsx("span",{className:"text-white truncate ml-2",children:(()=>{try{return JSON.parse(t.compatible_printers).join(", ")}catch{return t.compatible_printers}})()})]}),t.inherits&&t.inherits!==t.name&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.inheritsFrom")}),i.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.source")}),i.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function EZe(){const{t}=Ut(),{hasPermission:e}=Or(),n=tn(),{showToast:r}=cn(),[a,s]=w.useState(""),[o,l]=w.useState(null),[c,u]=w.useState(!1),[d,h]=w.useState(null),{data:f,isLoading:p}=Je({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets()}),x=ot({mutationFn:async C=>{const j=[];for(const P of Array.from(C)){const E=new FormData;E.append("file",P),j.push(await ne.importLocalPresets(E))}return j},onSuccess:C=>{n.invalidateQueries({queryKey:["localPresets"]});let j=0,P=0,E=0;for(const B of C)j+=B.imported,P+=B.skipped,E+=B.errors.length;j>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:j})),P>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:P}),"warning"),E>0&&r(t("profiles.localProfiles.toast.importError",{count:E}),"error")},onError:C=>{r(C.message,"error")}}),v=ot({mutationFn:C=>ne.deleteLocalPreset(C),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),h(null),r(t("profiles.localProfiles.toast.deleted"))}}),g=w.useCallback(C=>{!C||C.length===0||x.mutate(C)},[x]),y=w.useCallback(C=>{C.preventDefault(),u(!1),g(C.dataTransfer.files)},[g]),_=w.useCallback(C=>{if(!a)return C;const j=a.toLowerCase();return C.filter(P=>P.name.toLowerCase().includes(j)||P.filament_type?.toLowerCase().includes(j)||P.filament_vendor?.toLowerCase().includes(j))},[a]),N=w.useMemo(()=>_(f?.filament||[]),[f?.filament,_]),k=w.useMemo(()=>_(f?.printer||[]),[f?.printer,_]),A=w.useMemo(()=>_(f?.process||[]),[f?.process,_]),M=N.length+k.length+A.length;return p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&i.jsxs("div",{onDragOver:C=>{C.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:y,className:`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsx("input",{type:"file",accept:".json,.zip,.orca_filament,.bbscfg,.bbsflmt",multiple:!0,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",onChange:C=>g(C.target.files)}),x.isPending?i.jsxs("div",{className:"flex items-center justify-center gap-2",children:[i.jsx(it,{className:"w-5 h-5 text-bambu-green animate-spin"}),i.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),M>0&&i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:a,onChange:C=>s(C.target.value),placeholder:t("profiles.localProfiles.search"),className:"w-full pl-9 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),M===0&&!p&&i.jsxs("div",{className:"text-center py-12",children:[i.jsx(Ub,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),i.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),M>0&&i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[N.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(IC,{className:"w-4 h-4 text-bambu-green"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:N.map(C=>i.jsx(kj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),A.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(mi,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",A.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:A.map(C=>i.jsx(kj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),k.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(ed,{className:"w-4 h-4 text-orange-400"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",k.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:k.map(C=>i.jsx(kj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]})]}),d!==null&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(Ba,{className:"w-5 h-5 text-red-400"}),i.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>h(null),children:t("profiles.localProfiles.cancel")}),i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>v.mutate(d),disabled:v.isPending,children:[v.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function s4(t,e){const n=`${t} ${e||""}`,r=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),a=r?r[1].trim():null,s=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=s?(s[1]||s[2])+"mm":null,l=n.match(/(\d+\.?\d*)mm\s*(?:Standard|Fine|Extra Fine|Draft|Quality)?/i),c=l?l[1]+"mm":null,u=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),d=u?u[1].toUpperCase():null;return{printer:a,nozzle:o,layerHeight:c,filamentType:d}}function r0(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function jZe({onSuccess:t,t:e}){const{showToast:n}=cn(),[r,a]=w.useState("email"),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),[p,x]=w.useState("global"),[v,g]=w.useState(null),[y,_]=w.useState(null),N=ot({mutationFn:()=>ne.cloudLogin(s,l,p),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):j.needs_verification?(g(j.verification_type||"email"),_(j.tfa_key||null),j.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),a("code")):n(j.message,"error")},onError:j=>n(j.message,"error")}),k=ot({mutationFn:()=>ne.cloudVerify(s,u,y||void 0),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):n(j.message,"error")},onError:j=>n(j.message,"error")}),A=ot({mutationFn:()=>ne.cloudSetToken(h),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:j=>n(j.message,"error")}),M=j=>{j.preventDefault(),r==="email"?N.mutate():r==="code"?k.mutate():r==="token"&&A.mutate()},C=N.isPending||k.isPending||A.isPending;return i.jsx(vt,{className:"max-w-md mx-auto",children:i.jsxs(_t,{children:[i.jsxs("div",{className:"text-center mb-6",children:[i.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:i.jsx(zb,{className:"w-6 h-6 text-bambu-green"})}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),i.jsxs("form",{onSubmit:M,className:"space-y-4",children:[r==="email"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),i.jsx("input",{type:"email",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"your@email.com",required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),i.jsx("input",{type:"password",value:l,onChange:j=>c(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"••••••••",required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),i.jsxs("select",{value:p,onChange:j=>x(j.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:[i.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),i.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(v==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:v==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),i.jsx("input",{type:"text",value:u,onChange:j=>d(j.target.value.replace(/\D/g,"").slice(0,6)),className:"w-full px-3 py-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:border-bambu-green focus:outline-none",placeholder:"000000",maxLength:6,required:!0})]}),r==="token"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),i.jsx("textarea",{value:h,onChange:j=>f(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none resize-none",placeholder:"eyJ...",rows:4,required:!0})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r==="code"&&i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>a("email"),className:"flex-1",children:e("profiles.login.back")}),i.jsxs(Ce,{type:"submit",disabled:C,className:"flex-1",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(EB,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&i.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("button",{type:"button",onClick:()=>a("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[i.jsx(nl,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&i.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("button",{type:"button",onClick:()=>a("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[i.jsx(EB,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function Ag({label:t,value:e,options:n,onChange:r}){const[a,s]=w.useState(!1),o=n.find(l=>l.value===e);return i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>s(!a),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white hover:border-bambu-gray-dark transition-colors",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),i.jsx("span",{children:o?.label||"All"}),i.jsx(Un,{className:`w-4 h-4 text-bambu-gray transition-transform ${a?"rotate-180":""}`})]}),a&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),i.jsx("div",{className:"absolute top-full left-0 mt-1 min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 py-1 max-h-60 overflow-y-auto",children:n.map(l=>i.jsxs("button",{onClick:()=>{r(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center justify-between hover:bg-bambu-dark-tertiary transition-colors ${e===l.value?"text-bambu-green":"text-white"}`,children:[i.jsx("span",{children:l.label}),l.count!==void 0&&i.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function DZe(){const[t,e]=w.useState(!1);w.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?i.jsx("button",{onClick:n,className:"fixed bottom-6 right-6 p-3 bg-bambu-green hover:bg-bambu-green-light text-white rounded-full shadow-lg shadow-bambu-green/25 transition-all z-40","aria-label":"Scroll to top",children:i.jsx(Af,{className:"w-5 h-5"})}):null}function Aj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:a,compareIndex:s,compareDisabled:o,t:l}){const c=s4(t.name),u=r0(t.setting_id);return i.jsxs("div",{className:"flex items-center gap-2 group",children:[i.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${a?"bg-blue-500/20 border border-blue-500/50":o?"bg-bambu-dark/50 opacity-40 cursor-not-allowed":"bg-bambu-dark hover:bg-bambu-dark-tertiary"} ${r&&!o?"cursor-pointer":""}`,children:i.jsxs("div",{className:"flex items-center gap-2",children:[a&&s!==void 0&&i.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-blue-500 text-white text-xs flex items-center justify-center font-medium",children:s+1}),!a&&u&&i.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),i.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),i.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:l("profiles.presets.duplicate"),children:i.jsx(Yl,{className:"w-4 h-4"})})]})}function eF(t,e=0){const n=" ".repeat(e);if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){if(t.includes("\\n")||t.includes(` +`);X=ie.pop()||"";for(const le of ie)if(le.startsWith("data: "))try{const Fe=JSON.parse(le.slice(6));Fe.type==="progress"?O({fetched:Fe.total_fetched,total:Fe.total_available}):Fe.type==="complete"?Fe.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:Fe.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:Fe.added,skipped:Fe.skipped}),"success"):Fe.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${Fe.error}`,"error")}catch{}}await z()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{E(!1),O(null)}},je=()=>{const oe=n.map(({manufacturer:q,color_name:X,hex_color:de,material:Z})=>({manufacturer:q,color_name:X,hex_color:de,material:Z})),_e=new Blob([JSON.stringify(oe,null,2)],{type:"application/json"}),se=URL.createObjectURL(_e),Oe=document.createElement("a");Oe.href=se,Oe.download="color-catalog.json",document.body.appendChild(Oe),Oe.click(),document.body.removeChild(Oe),URL.revokeObjectURL(se),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},ue=async oe=>{const _e=oe.target.files?.[0];if(_e){try{const se=await _e.text(),Oe=JSON.parse(se);if(!Array.isArray(Oe))throw new Error("Invalid format");let q=0,X=0;for(const de of Oe){if(!de.manufacturer||!de.color_name||!de.hex_color){X++;continue}if(n.some(ie=>ie.manufacturer.toLowerCase()===de.manufacturer.toLowerCase()&&ie.color_name.toLowerCase()===de.color_name.toLowerCase()&&(ie.material||"").toLowerCase()===(de.material||"").toLowerCase())){X++;continue}try{const ie=await ne.addColorEntry({manufacturer:de.manufacturer,color_name:de.color_name,hex_color:de.hex_color,material:de.material||null});r(le=>[...le,ie].sort((Fe,pe)=>Fe.manufacturer.localeCompare(pe.manufacturer)||(Fe.material||"").localeCompare(pe.material||"")||Fe.color_name.localeCompare(pe.color_name))),q++}catch{X++}}e(t("settings.colorCatalog.imported",{added:q,skipped:X}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}d.current&&(d.current.value="")}};return i.jsxs(vt,{children:[i.jsxs(In,{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(VC,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsxs("button",{onClick:je,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:[i.jsx(ua,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),i.jsxs("button",{onClick:()=>d.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:[i.jsx(Ra,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),i.jsx("input",{ref:d,type:"file",accept:".json",className:"hidden",onChange:ue}),i.jsxs("button",{onClick:te,disabled:P,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:[P?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(zb,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:P?B?`${Math.min(B.fetched,B.total)} / ${B.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),i.jsxs("button",{onClick:()=>G(!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:[i.jsx(Fo,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),i.jsxs("button",{onClick:()=>f(!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:[i.jsx(Xn,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),i.jsxs("div",{className:"flex gap-2 flex-wrap",children:[i.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.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:oe=>l(oe.target.value)})]}),i.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:oe=>u(oe.target.value),children:[i.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),K.map(oe=>i.jsx("option",{value:oe,children:oe},oe))]})]}),h&&i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),i.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[i.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:oe=>g(oe.target.value)}),i.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:y,onChange:oe=>_(oe.target.value)}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:oe=>k(oe.target.value)}),i.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:N,onChange:oe=>k(oe.target.value)})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.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:A,onChange:oe=>M(oe.target.value)}),i.jsxs("button",{onClick:$,disabled:C,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:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ra,{className:"w-4 h-4"}),t("common.add")]}),i.jsx("button",{onClick:()=>{f(!1),ae()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:i.jsx(Ft,{className:"w-4 h-4"})})]})]})]}),(o||c)&&i.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:Y.length,total:n.length})}),a?i.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[i.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):i.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:i.jsxs("tr",{children:[i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),i.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),i.jsx("th",{className:"px-3 py-2 w-16"})]})}),i.jsx("tbody",{children:Y.length===0?i.jsx("tr",{children:i.jsx("td",{colSpan:6,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):Y.map(oe=>i.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:p===oe.id?i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-3 py-2",children:i.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:_e=>k(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:_e=>g(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:A,onChange:_e=>M(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:y,onChange:_e=>_(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.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:_e=>k(_e.target.value)})}),i.jsx("td",{className:"px-3 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>J(oe.id),disabled:C,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ra,{className:"w-4 h-4"})}),i.jsx("button",{onClick:ee,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(Ft,{className:"w-4 h-4"})})]})})]}):i.jsxs(i.Fragment,{children:[i.jsx("td",{className:"px-3 py-2",children:i.jsx("div",{className:"w-8 h-8 rounded border border-bambu-dark-tertiary",style:{backgroundColor:oe.hex_color},title:oe.hex_color})}),i.jsx("td",{className:"px-3 py-2 text-white",children:oe.manufacturer}),i.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:oe.material||"-"}),i.jsx("td",{className:"px-3 py-2 text-white",children:oe.color_name}),i.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:oe.hex_color}),i.jsx("td",{className:"px-3 py-2",children:i.jsxs("div",{className:"flex justify-end gap-1",children:[i.jsx("button",{onClick:()=>W(oe),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>R(oe),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]})},oe.id))})]})})]}),U&&i.jsx(gn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${U.manufacturer} - ${U.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:ye,onCancel:()=>R(null)}),V&&i.jsx(gn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:me,onCancel:()=>G(!1)})]})}function lZe({link:t,onClose:e}){const{t:n}=Ut(),r=tn(),a=!!t,s=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.url||""),[d,h]=w.useState(t?.icon||"link"),[f,p]=w.useState(t?.open_in_new_tab||!1),[x,v]=w.useState(!!t?.custom_icon),[g,y]=w.useState(t?.custom_icon?ne.getExternalLinkIconUrl(t.id):null),[_,N]=w.useState(null),[k,A]=w.useState(null);w.useEffect(()=>{const U=R=>{R.key==="Escape"&&e()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[e]);const M=ot({mutationFn:async U=>{const R=await ne.createExternalLink(U);return _?await ne.uploadExternalLinkIcon(R.id,_):R},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{A(U.message)}}),C=ot({mutationFn:async U=>{let R=await ne.updateExternalLink(t.id,U);return _?R=await ne.uploadExternalLinkIcon(t.id,_):!x&&t?.custom_icon&&(R=await ne.deleteExternalLinkIcon(t.id)),R},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{A(U.message)}}),j=U=>{const R=U.target.files?.[0];if(R){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(R.type)){A("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(R.size>1024*1024){A("Image file must be less than 1MB");return}N(R),v(!0);const G=new FileReader;G.onload=z=>{y(z.target?.result)},G.readAsDataURL(R)}},P=()=>{N(null),y(null),v(!1),s.current&&(s.current.value="")},E=U=>{if(U.preventDefault(),A(null),!o.trim()){A("Name is required");return}if(!c.trim()){A("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){A("URL must start with http:// or https://");return}const R={name:o.trim(),url:c.trim(),icon:d,open_in_new_tab:f};a?C.mutate(R):M.mutate(R)},B=M.isPending||C.isPending,O=QC(d);return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:U=>U.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:x&&g?i.jsx("img",{src:g,alt:"",className:"w-5 h-5 rounded"}):i.jsx(O,{className:"w-5 h-5"})}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a?"Edit Link":"Add External Link"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:E,className:"p-6 space-y-4",children:[k&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:k}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),i.jsx("input",{type:"text",value:o,onChange:U=>l(U.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),i.jsx("input",{type:"text",value:c,onChange:U=>u(U.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"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),i.jsx("button",{type:"button",onClick:()=>p(!f),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${f?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${f?"translate-x-6":"translate-x-1"}`})})]}),i.jsxs("div",{className:"space-y-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),i.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),i.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:j}),x&&g?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("img",{src:g,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:P,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:i.jsx(Jt,{className:"w-4 h-4"})})]}):i.jsxs(Ce,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[i.jsx(Ra,{className:"w-4 h-4"}),"Upload"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!x&&i.jsxs("div",{children:[i.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),i.jsx(nge,{value:d,onChange:h})]})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),i.jsxs(Ce,{type:"submit",disabled:B,className:"flex-1",children:[B?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ps,{className:"w-4 h-4"}),a?"Save":"Add"]})]})]})]})})}function cZe(){const{t}=Ut(),e=tn(),[n,r]=w.useState(!1),[a,s]=w.useState(null),[o,l]=w.useState(null),[c,u]=w.useState(null),{data:d,isLoading:h}=Je({queryKey:["external-links"],queryFn:ne.getExternalLinks}),f=ot({mutationFn:N=>ne.deleteExternalLink(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),p=ot({mutationFn:N=>ne.reorderExternalLinks(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),x=(N,k)=>{u(k),N.dataTransfer.effectAllowed="move"},v=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},g=(N,k)=>{if(N.preventDefault(),c===null||c===k||!d)return;const A=d.map(P=>P.id),M=A.indexOf(c),C=A.indexOf(k);if(M===-1||C===-1)return;const j=[...A];j.splice(M,1),j.splice(C,0,c),p.mutate(j),u(null)},y=N=>{l(N)},_=()=>{o&&(f.mutate(o.id),l(null))};return i.jsxs(i.Fragment,{children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Eh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),i.jsxs(Ce,{size:"sm",onClick:()=>r(!0),children:[i.jsx(Xn,{className:"w-4 h-4"}),"Add Link"]})]})}),i.jsxs(_t,{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),h?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):d&&d.length>0?i.jsx("div",{className:"space-y-2",children:d.map(N=>{const k=QC(N.icon);return i.jsxs("div",{draggable:!0,onDragStart:A=>x(A,N.id),onDragOver:v,onDrop:A=>g(A,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===N.id?"opacity-50":""}`,children:[i.jsx(Ph,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:i.jsx(k,{className:"w-4 h-4"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-white font-medium truncate",children:N.name}),i.jsx(Kr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),i.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[i.jsx("button",{onClick:()=>s(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>y(N),disabled:f.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:i.jsx(Jt,{className:"w-4 h-4"})})]})]},N.id)})}):i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(Eh,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:t("externalLinks.noLinksConfigured")}),i.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||a)&&i.jsx(lZe,{link:a,onClose:()=>{r(!1),s(null)}}),o&&i.jsx(gn,{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 _j={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function uZe({printer:t,models:e}){const{t:n}=Ut(),r=tn(),{showToast:a}=cn(),[s,o]=w.useState(!0),[l,c]=w.useState(t.enabled),[u,d]=w.useState(t.name),[h,f]=w.useState(""),[p,x]=w.useState(t.mode==="queue"?"review":t.mode),[v,g]=w.useState(t.target_printer_id),[y,_]=w.useState(t.bind_ip||""),[N,k]=w.useState(t.remote_interface_ip||""),[A,M]=w.useState(t.model||""),[C,j]=w.useState(!1),[P,E]=w.useState(null),[B,O]=w.useState(!1);w.useEffect(()=>{P||(c(t.enabled),x(t.mode==="queue"?"review":t.mode),d(t.name),g(t.target_printer_id),_(t.bind_ip||""),k(t.remote_interface_ip||""),M(t.model||""))},[t,P]);const{data:U}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:R}=Je({queryKey:["network-interfaces"],queryFn:()=>ne.getNetworkInterfaces().then(te=>te.interfaces)}),V=ot({mutationFn:te=>w1.update(t.id,te),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),a(n("virtualPrinter.toast.updated")),E(null)},onError:te=>{a(te.message||n("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),x(t.mode==="queue"?"review":t.mode),g(t.target_printer_id),_(t.bind_ip||""),E(null)}}),G=ot({mutationFn:()=>w1.remove(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),a(n("virtualPrinter.toast.deleted")),O(!1)},onError:te=>{a(te.message||n("virtualPrinter.toast.failedToDelete"),"error"),O(!1)}}),z=te=>{te.stopPropagation();const je=!l;if(je){if(!y){a(n("virtualPrinter.toast.bindIpRequired"),"error");return}if(p==="proxy"){if(!v){a(n("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!h&&!t.access_code_set){a(n("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(je),E("toggle"),V.mutate({enabled:je})},K=()=>{u.trim()&&(E("name"),V.mutate({name:u.trim()}))},Y=()=>{if(!h){a(n("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(h.length!==8){a(n("virtualPrinter.toast.accessCodeLength"),"error");return}E("accessCode"),V.mutate({access_code:h}),f("")},ae=te=>{x(te),E("mode"),V.mutate({mode:te})},$=te=>{M(te),E("model"),V.mutate({model:te})},W=te=>{g(te),E("targetPrinter"),V.mutate({target_printer_id:te})},ee=te=>{k(te),E("remoteInterface"),V.mutate({remote_interface_ip:te})},J=t.status?.running||!1,ye=n(`virtualPrinter.mode.${_j[p]||"archive"}`),me=U?.find(te=>te.id===v)?.name;return i.jsxs(i.Fragment,{children:[i.jsxs(vt,{children:[i.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[i.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?i.jsx(Un,{className:"w-4 h-4"}):i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${J?"bg-green-400 animate-pulse":"bg-gray-500"}`}),i.jsx("span",{className:"text-white font-medium truncate",children:t.name}),i.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:ye}),t.model_name&&i.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),me&&i.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[p==="proxy"&&i.jsx(Yj,{className:"w-3 h-3 inline mr-1"}),me]}),y&&i.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:y}),N&&i.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:N}),i.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:te=>te.stopPropagation(),children:i.jsx("button",{onClick:z,disabled:P==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${P==="toggle"?"opacity-50":""}`,children:i.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&&i.jsxs(_t,{className:"pt-0 space-y-4",children:[i.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"text",value:u,onChange:te=>d(te.target.value),onBlur:K,onKeyDown:te=>te.key==="Enter"&&K(),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"}),i.jsx("span",{className:"text-xs text-bambu-gray font-mono",children:t.serial}),i.jsx("button",{onClick:()=>O(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.mode.title")}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(te=>i.jsxs("button",{onClick:()=>ae(te),disabled:P==="mode",className:`p-2 rounded-lg border text-left transition-colors ${p===te?te==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[te==="proxy"&&i.jsx(Yj,{className:"w-3 h-3"}),n(`virtualPrinter.mode.${_j[te]}`)]}),i.jsx("div",{className:"text-[10px] text-bambu-gray",children:n(`virtualPrinter.mode.${_j[te]}Desc`)})]},te))})]}),p!=="proxy"&&i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.model.title")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:n("virtualPrinter.model.description")}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:A,onChange:te=>$(te.target.value),disabled:P==="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(([te,je])=>i.jsxs("option",{value:te,children:[je," (",te,")"]},te))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),p==="proxy"&&i.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("virtualPrinter.proxy.accessCodeHint")})]})}),p!=="proxy"&&i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.accessCode.title")}),t.access_code_set?i.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[i.jsx(ra,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.isSet")]}):i.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[i.jsx(Tn,{className:"w-3 h-3"}),n("virtualPrinter.accessCode.notSet")]})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:C?"text":"password",value:h,onChange:te=>f(te.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"}),i.jsx("button",{onClick:()=>j(!C),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:C?i.jsx(o0,{className:"w-4 h-4"}):i.jsx(Ql,{className:"w-4 h-4"})})]}),i.jsx(Ce,{onClick:Y,disabled:!h||P==="accessCode",variant:"primary",children:P==="accessCode"?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("common.save")})]}),h&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i.jsx("span",{className:h.length===8?"text-green-400":"text-yellow-400",children:n("virtualPrinter.accessCode.charCount",{count:h.length})})})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-2",children:n("virtualPrinter.targetPrinter.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:v??"",onChange:te=>{const je=parseInt(te.target.value,10);isNaN(je)||W(je)},disabled:P==="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:[i.jsx("option",{value:"",children:n("virtualPrinter.targetPrinter.placeholder")}),U?.map(te=>i.jsxs("option",{value:te.id,children:[te.name," (",te.ip_address,")"]},te.id))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("div",{className:"text-white text-sm font-medium mb-1",children:n("virtualPrinter.bindIp.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:y,onChange:te=>{_(te.target.value),E("bindIp"),V.mutate({bind_ip:te.target.value})},disabled:P==="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:[i.jsx("option",{value:"",children:n("virtualPrinter.bindIp.placeholder")}),R?.map(te=>i.jsxs("option",{value:te.ip,children:[te.name," (",te.ip,")",te.is_alias?" [alias]":""," - ",te.subnet]},te.ip))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("virtualPrinter.bindIp.hint")})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx("div",{className:"text-white text-sm font-medium",children:n("virtualPrinter.remoteInterface.title")}),N?i.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:i.jsx(ra,{className:"w-3 h-3"})}):i.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:n("virtualPrinter.remoteInterface.optional"),children:i.jsx(Zs,{className:"w-3 h-3"})})]}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:N,onChange:te=>ee(te.target.value),disabled:P==="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:[i.jsx("option",{value:"",children:n("virtualPrinter.remoteInterface.placeholder")}),R?.map(te=>i.jsxs("option",{value:te.ip,children:[te.name," (",te.ip,") - ",te.subnet]},te.ip))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),B&&i.jsx(gn,{title:n("virtualPrinter.deleteConfirm.title"),message:n("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:n("common.delete"),isLoading:G.isPending,onConfirm:()=>G.mutate(),onCancel:()=>O(!1)})]})}const XW={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function dZe({onClose:t}){const{t:e}=Ut(),n=tn(),{showToast:r}=cn(),[a,s]=w.useState(""),[o,l]=w.useState("immediate"),[c,u]=w.useState(null),{data:d}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),h=ot({mutationFn:()=>w1.create({name:a.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:f=>{r(f.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:i.jsx(vt,{className:"w-full max-w-md",onClick:f=>f.stopPropagation(),children:i.jsxs(_t,{className:"p-6 space-y-4",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),i.jsx("input",{type:"text",value:a,onChange:f=>s(f.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})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),i.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(f=>i.jsxs("button",{onClick:()=>l(f),className:`p-2 rounded-lg border text-left transition-colors ${o===f?f==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[f==="proxy"&&i.jsx(Yj,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${XW[f]}`)]}),i.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${XW[f]}Desc`)})]},f))})]}),o==="proxy"&&i.jsxs("div",{children:[i.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:c??"",onChange:f=>{const p=parseInt(f.target.value,10);u(isNaN(p)?null:p)},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:[i.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),d?.map(f=>i.jsxs("option",{value:f.id,children:[f.name," (",f.ip_address,")"]},f.id))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",disabled:h.isPending,children:e("common.cancel")}),i.jsx(Ce,{variant:"primary",onClick:()=>h.mutate(),className:"flex-1",disabled:h.isPending,children:h.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function hZe(){const{t}=Ut(),[e,n]=w.useState(!1),{data:r,isLoading:a}=Je({queryKey:["virtual-printers"],queryFn:w1.list,refetchInterval:1e4});if(a)return i.jsx(vt,{children:i.jsx(_t,{className:"py-8 flex justify-center",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const s=r?.printers||[],o=r?.models||{};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-4 gap-4 items-stretch",children:[i.jsx(vt,{className:"border-l-4 border-l-yellow-500",children:i.jsx(_t,{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs",children:[i.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),i.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:[i.jsx(Kr,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),i.jsx(vt,{className:"lg:col-span-3",children:i.jsx(_t,{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-xs text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),i.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[i.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),i.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),i.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(xr,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",s.length,")"]})]}),i.jsxs(Ce,{variant:"primary",onClick:()=>n(!0),children:[i.jsx(Xn,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),s.length===0?i.jsx(vt,{children:i.jsxs(_t,{className:"py-8 text-center",children:[i.jsx(xr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),i.jsxs(Ce,{variant:"primary",onClick:()=>n(!0),children:[i.jsx(Xn,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:s.map(l=>i.jsx(uZe,{printer:l,models:o},l.id))}),e&&i.jsx(dZe,{onClose:()=>n(!1)})]})}function YW({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:i.jsx(pr,{className:"w-3 h-3"}),failed:i.jsx(hi,{className:"w-3 h-3"}),skipped:i.jsx(NF,{className:"w-3 h-3"}),running:i.jsx(it,{className:"w-3 h-3 animate-spin"})};return i.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 mZe(t){return t?new Date(t).toLocaleString():"-"}function fZe(){const t=tn(),{showToast:e}=cn(),{t:n}=Ut(),[r,a]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[u,d]=w.useState(!1),[h,f]=w.useState("daily"),[p,x]=w.useState(!0),[v,g]=w.useState(!0),[y,_]=w.useState(!1),[N,k]=w.useState(!0),[A,M]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState(""),[B,O]=w.useState(!1),[U,R]=w.useState(null),[V,G]=w.useState(null),z=w.useRef(null);w.useEffect(()=>{if(A||C){const L=D=>(D.preventDefault(),D.returnValue="A backup operation is in progress. Are you sure you want to leave?",D.returnValue);return window.addEventListener("beforeunload",L),()=>window.removeEventListener("beforeunload",L)}},[A,C]);const[K,Y]=w.useState(!1),[ae,$]=w.useState(null),W=w.useRef(null),ee=w.useRef(!1),{data:J,isLoading:ye}=Je({queryKey:["github-backup-config"],queryFn:ne.getGitHubBackupConfig}),{data:me}=Je({queryKey:["github-backup-status"],queryFn:ne.getGitHubBackupStatus,refetchInterval:Q=>Q.state.data?.is_running?500:1e4}),{data:te}=Je({queryKey:["github-backup-logs"],queryFn:()=>ne.getGitHubBackupLogs(20)}),{data:je}=Je({queryKey:["cloud-status"],queryFn:ne.getCloudStatus}),{data:ue}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),oe=yF({queries:(ue??[]).map(Q=>({queryKey:["printerStatus",Q.id],queryFn:()=>ne.getPrinterStatus(Q.id),staleTime:1e4,refetchInterval:3e4}))}),_e=(ue??[]).map((Q,L)=>({printer:Q,connected:oe[L]?.data?.connected??!1})),se=_e.length,Oe=_e.filter(Q=>Q.connected).length,q=se>0&&Oe===0,X=Oe>0&&Oe{J&&(a(J.repository_url),c(J.branch),d(J.schedule_enabled),f(J.schedule_type),x(J.backup_kprofiles),g(J.backup_cloud_profiles),_(J.backup_settings),k(J.enabled),o(""),setTimeout(()=>{ee.current=!0},100))},[J]);const de=w.useCallback(async(Q=!1)=>{if(J?.has_token)try{Q&&s?(await ne.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),o(""),e("Token updated")):(await ne.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(L){e(`Failed to save: ${L.message}`,"error")}},[J?.has_token,r,s,l,u,h,p,v,y,N,t,e]);w.useEffect(()=>{if(!(!ee.current||!J?.has_token))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{de(!1)},500),()=>{W.current&&clearTimeout(W.current)}},[r,l,u,h,p,v,y,N,de,J?.has_token]),w.useEffect(()=>{if(!(!ee.current||!J?.has_token||!s))return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{de(!0)},1e3),()=>{W.current&&clearTimeout(W.current)}},[s,de,J?.has_token]);const Z=ot({mutationFn:Q=>ne.saveGitHubBackupConfig(Q),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),o(""),ee.current=!0},onError:Q=>{e(`Failed to save: ${Q.message}`,"error")}}),ie=ot({mutationFn:ne.triggerGitHubBackup,onSuccess:Q=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),Q.success?Q.files_changed>0?e(`Backup complete - ${Q.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${Q.message}`,"error")},onError:Q=>{e(`Backup failed: ${Q.message}`,"error")}}),le=ot({mutationFn:()=>ne.clearGitHubBackupLogs(0),onSuccess:Q=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${Q.deleted} logs`)},onError:Q=>{e(`Failed to clear logs: ${Q.message}`,"error")}}),Fe=async()=>{Y(!0),$(null);try{let Q;if(s){if(!r){e("Enter repository URL","error"),Y(!1);return}Q=await ne.testGitHubConnection(r,s)}else if(J?.has_token)Q=await ne.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),Y(!1);return}$({success:Q.success,message:Q.message})}catch(Q){$({success:!1,message:Q.message})}finally{Y(!1)}},pe=()=>{if(!r){e("Repository URL is required","error");return}if(!s){e("Access token is required","error");return}Z.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N})};return ye?i.jsx("div",{className:"flex items-center justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"space-y-6",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(e3,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),J&&je?.is_authenticated&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),i.jsx(On,{checked:N,onChange:k})]})]})}),i.jsx(_t,{className:"space-y-4",children:je?.is_authenticated?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),i.jsx("input",{type:"text",value:r,onChange:Q=>{a(Q.target.value),$(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"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",J?.has_token&&i.jsx("span",{className:"text-green-400",children:"(saved)"})]}),i.jsx("input",{type:"password",value:s,onChange:Q=>{o(Q.target.value),$(null)},placeholder:J?.has_token?"Enter new token to update":"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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),i.jsx("input",{type:"text",value:l,onChange:Q=>c(Q.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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),i.jsxs("select",{value:u?h:"disabled",onChange:Q=>{Q.target.value==="disabled"?d(!1):(d(!0),f(Q.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:[i.jsx("option",{value:"disabled",children:"Manual only"}),i.jsx("option",{value:"hourly",children:"Hourly"}),i.jsx("option",{value:"daily",children:"Daily"}),i.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:`flex items-start gap-2 ${q?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[i.jsx("input",{type:"checkbox",checked:p,onChange:Q=>x(Q.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:q}),i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`text-sm ${q?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),q&&i.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:[i.jsx(Tn,{className:"w-3 h-3"}),"No printers connected"]}),X&&i.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:[i.jsx(Tn,{className:"w-3 h-3"}),Oe,"/",se," connected"]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:v,onChange:Q=>g(Q.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:!je?.is_authenticated}),i.jsxs("div",{children:[i.jsx("span",{className:`text-sm ${je?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),i.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:y,onChange:Q=>_(Q.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"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white text-sm",children:"App Settings"}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (complete database)"})]})]})]})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[me?.configured&&i.jsxs("div",{className:"flex items-center justify-between text-sm",children:[i.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:me.last_backup_at?i.jsxs(i.Fragment,{children:[i.jsxs("span",{children:["Last backup: ",gv(me.last_backup_at,"system",n)]}),i.jsx(YW,{status:me.last_backup_status})]}):i.jsx("span",{children:"No backups yet"})}),me.next_scheduled_run&&i.jsxs("span",{className:"text-bambu-gray",children:[i.jsx(Gn,{className:"w-3 h-3 inline mr-1"}),"Next: ",gv(me.next_scheduled_run,"system",n)]})]}),ae&&i.jsxs("div",{className:`text-sm flex items-center gap-1 ${ae.success?"text-green-400":"text-red-400"}`,children:[ae.success?i.jsx(pr,{className:"w-4 h-4"}):i.jsx(hi,{className:"w-4 h-4"}),ae.message]}),i.jsx("div",{className:"flex flex-wrap items-center gap-2",children:me?.configured?i.jsx(i.Fragment,{children:ie.isPending||me.is_running?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),i.jsx("span",{className:"text-sm",children:me.progress||"Starting backup..."})]}):i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"primary",size:"sm",onClick:()=>ie.mutate(),disabled:!J?.enabled,children:[i.jsx(io,{className:"w-4 h-4"}),"Backup Now"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Fe,disabled:K,children:[K?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),"Test"]})]})}):i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"primary",size:"sm",onClick:pe,disabled:Z.isPending||!r||!s,children:[Z.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(pr,{className:"w-4 h-4"}),"Enable Backup"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Fe,disabled:K||!r||!s,children:[K?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):i.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),te&&te.length>0&&i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(mv,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>le.mutate(),disabled:le.isPending,children:[i.jsx(Jt,{className:"w-4 h-4"}),"Clear"]})]})}),i.jsx(_t,{children:i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full text-sm",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),i.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),i.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),i.jsx("tbody",{children:te.slice(0,10).map(Q=>i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[i.jsx("td",{className:"py-2 px-2 text-white",children:mZe(Q.started_at)}),i.jsx("td",{className:"py-2 px-2",children:i.jsx(YW,{status:Q.status})}),i.jsx("td",{className:"py-2 px-2",children:Q.commit_sha?i.jsxs("a",{href:`${J?.repository_url}/commit/${Q.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[Q.commit_sha.substring(0,7),i.jsx(Kr,{className:"w-3 h-3"})]}):i.jsx("span",{className:"text-bambu-gray",children:"-"})})]},Q.id))})]})})})]})]}),i.jsx("div",{className:"space-y-6",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pc,{className:"w-5 h-5 text-gray-400"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files."}),i.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Download Backup"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:A||C,onClick:async()=>{M(!0),E("Preparing backup...");try{E("Creating backup archive... This may take a while for large archives.");const{blob:Q,filename:L}=await ne.exportBackup();E("Downloading backup file...");const D=URL.createObjectURL(Q),H=document.createElement("a");H.href=D,H.download=L,H.click(),URL.revokeObjectURL(D),e("Backup downloaded successfully")}catch(Q){e(`Failed to create backup: ${Q instanceof Error?Q.message:"Unknown error"}`,"error")}finally{M(!1),E("")}},children:[i.jsx(ua,{className:"w-4 h-4"}),"Download"]})]}),i.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),i.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),i.jsx("input",{ref:z,type:"file",accept:".zip",className:"hidden",onChange:Q=>{const L=Q.target.files?.[0];L&&(R(L),O(!0)),Q.target.value=""}}),i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:C||A,onClick:()=>z.current?.click(),children:[i.jsx(Ra,{className:"w-4 h-4"}),"Restore"]})]}),V&&i.jsx("div",{className:`p-3 rounded-lg ${V.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[V.success?i.jsx(pr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):i.jsx(hi,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:V.success?"text-green-200":"text-red-200",children:[V.message,V.success&&i.jsx("div",{className:"mt-2",children:i.jsxs(Ce,{size:"sm",onClick:()=>window.location.reload(),children:[i.jsx(Fo,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),i.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-yellow-200",children:[i.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",i.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),B&&U&&i.jsx(gn,{title:"Restore Backup",message:`Are you sure you want to restore from "${U.name}"? This will completely replace your current database and all files. The application will need to be restarted after restore.`,confirmText:"Restore Backup",variant:"danger",onConfirm:async()=>{O(!1),j(!0),G(null);try{E("Uploading backup file...");const Q=await ne.importBackup(U);G(Q),Q.success?e("Backup restored. Please restart Bambuddy.","success"):e(Q.message,"error")}catch(Q){const L=Q instanceof Error?Q.message:"Failed to restore backup";G({success:!1,message:L}),e(L,"error")}finally{j(!1),E(""),R(null)}},onCancel:()=>{O(!1),R(null)}}),(A||C)&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:i.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:[i.jsx("div",{className:"flex justify-center mb-4",children:i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),i.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),i.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:A?"Creating Backup":"Restoring Backup"}),i.jsx("p",{className:"text-bambu-gray mb-4",children:P||(A?"Preparing...":"Processing...")}),i.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:i.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}const pZe={starttls:587,ssl:465,none:25},gZe={587:"starttls",465:"ssl",25:"none"};function bZe(){const{t}=Ut(),{showToast:e}=cn(),n=tn(),[r,a]=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}=Je({queryKey:["smtpSettings"],queryFn:()=>ne.getSMTPSettings()}),{data:u}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()});w.useEffect(()=>{l&&a({...l,smtp_password:""})},[l]);const d=M=>{a({...r,smtp_security:M,smtp_port:pZe[M]})},h=M=>{const C=gZe[M];a({...r,smtp_port:M,...C?{smtp_security:C}:{}})},f=M=>{a({...r,smtp_auth_enabled:M,...M?{}:{smtp_username:"",smtp_password:""}})},p=ot({mutationFn:M=>ne.saveSMTPSettings(M),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:M=>{e(M.message,"error")}}),x=ot({mutationFn:M=>ne.testSMTP(M),onSuccess:M=>{e(M.message,M.success?"success":"error")},onError:M=>{e(M.message,"error")}}),v=ot({mutationFn:M=>M?ne.enableAdvancedAuth():ne.disableAdvancedAuth(),onSuccess:M=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(M.message,"success")},onError:M=>{e(M.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}p.mutate(r)},y=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.smtpServerAndEmail"),"error");return}if(r.smtp_auth_enabled&&(!r.smtp_username||!r.smtp_password)){e(t("settings.email.errors.usernamePasswordRequired"),"error");return}x.mutate({smtp_host:r.smtp_host,smtp_port:r.smtp_port,smtp_username:r.smtp_username,smtp_password:r.smtp_password,smtp_security:r.smtp_security,smtp_auth_enabled:r.smtp_auth_enabled,smtp_from_email:r.smtp_from_email,test_recipient:s})},_=()=>{if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}v.mutate(!u?.advanced_auth_enabled)};if(c)return i.jsx("div",{className:"flex items-center justify-center p-12",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})});const N=u?.advanced_auth_enabled??!1,k="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",A="w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";return i.jsxs("div",{className:"space-y-6",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),i.jsx(Ce,{onClick:_,disabled:v.isPending,variant:N?"danger":"primary",children:N?i.jsxs(i.Fragment,{children:[i.jsx(I_,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):i.jsxs(i.Fragment,{children:[i.jsx(zm,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),i.jsx(_t,{children:i.jsx("div",{className:"space-y-4",children:N?i.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(pr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),i.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[i.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),i.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),i.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),i.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):i.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Tn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),i.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),i.jsx("div",{className:N?"":"opacity-50 pointer-events-none",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),i.jsx(_t,{children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.authentication")||"Authentication"}),i.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:M=>f(M.target.value==="true"),className:k,children:[i.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),i.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),i.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:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.username")||"Username"}),i.jsx("input",{type:"text",value:r.smtp_username||"",onChange:M=>a({...r,smtp_username:M.target.value}),placeholder:"your.email@gmail.com",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?k:A})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.password")||"Password"}),i.jsx("input",{type:"password",value:r.smtp_password||"",onChange:M=>a({...r,smtp_password:M.target.value}),placeholder:l?"••••••••":"App password",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?k:A})]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),i.jsx("input",{type:"text",value:r.smtp_host,onChange:M=>a({...r,smtp_host:M.target.value}),placeholder:"smtp.gmail.com",className:k})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.smtpPort")||"SMTP Port"}),i.jsx("input",{type:"number",value:r.smtp_port,onChange:M=>h(parseInt(M.target.value)||587),placeholder:"587",className:k})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.security")||"Security"}),i.jsxs("select",{value:r.smtp_security,onChange:M=>d(M.target.value),className:k,children:[i.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),i.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),i.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.fromEmail")||"From Email"," *"]}),i.jsx("input",{type:"email",value:r.smtp_from_email,onChange:M=>a({...r,smtp_from_email:M.target.value}),placeholder:"your@email.com",className:k})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.fromName")||"From Name"}),i.jsx("input",{type:"text",value:r.smtp_from_name,onChange:M=>a({...r,smtp_from_name:M.target.value}),placeholder:"BamBuddy",className:k})]})]}),i.jsx("div",{className:"flex gap-2",children:i.jsx(Ce,{onClick:g,disabled:p.isPending,className:"flex-1",children:p.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),i.jsx("div",{className:N?"":"opacity-50 pointer-events-none",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),i.jsx(_t,{children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.testRecipient")||"Test Recipient Email"}),i.jsx("input",{type:"email",value:s,onChange:M=>o(M.target.value),placeholder:"test@example.com",className:k})]}),i.jsx(Ce,{onClick:y,disabled:x.isPending,variant:"secondary",children:x.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):i.jsxs(i.Fragment,{children:[i.jsx(WC,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})}const xZe={get:"bg-blue-500/20 text-blue-400 border-blue-500/30",post:"bg-green-500/20 text-green-400 border-green-500/30",put:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",patch:"bg-orange-500/20 text-orange-400 border-orange-500/30",delete:"bg-red-500/20 text-red-400 border-red-500/30"};function yZe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const a of n)r=r[a];return r}function Ly(t,e,n=0){if(n>5)return"...";if(e.$ref)return Ly(t,yZe(t,e.$ref),n+1);if(e.allOf){const r={};for(const a of e.allOf){const s=Ly(t,a,n+1);typeof s=="object"&&s!==null&&Object.assign(r,s)}return r}if(e.example!==void 0)return e.example;if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:"string";case"integer":case"number":return 0;case"boolean":return!1;case"array":return e.items?[Ly(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[a,s]of Object.entries(e.properties))r[a]=Ly(t,s,n+1);return r}return{};default:return null}}function vZe({path:t,method:e,spec:n,schema:r,apiKey:a}){const[s,o]=w.useState(!1),[l,c]=w.useState({}),[u,d]=w.useState(""),[h,f]=w.useState(null),[p,x]=w.useState(!1),[v,g]=w.useState(!1);w.useEffect(()=>{if(s&&n.parameters){const j={};for(const P of n.parameters)P.schema?.default!==void 0&&(j[P.name]=String(P.schema.default));c(P=>({...j,...P}))}},[s,n.parameters]),w.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!u){const j=n.requestBody.content["application/json"].schema,P=Ly(r,j);d(JSON.stringify(P,null,2))}},[s,n.requestBody,r,u]);const _=(()=>{const j=[];for(const P of n.parameters||[])if(P.in==="path"||P.required){const E=l[P.name];(E===void 0||E==="")&&j.push(P.name)}return j})(),N=async()=>{if(_.length>0){f({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${_.join(", ")}`,duration:0});return}x(!0),f(null);try{let j=t;const P=new URLSearchParams;for(const ae of n.parameters||[]){const $=l[ae.name];$!==void 0&&$!==""&&(ae.in==="path"?j=j.replace(`{${ae.name}}`,encodeURIComponent($)):ae.in==="query"&&P.append(ae.name,$))}const E=P.toString(),B=`${j}${E?`?${E}`:""}`,O={"Content-Type":"application/json"};a&&(O["X-API-Key"]=a);const U={method:e.toUpperCase(),headers:O};["post","put","patch"].includes(e)&&u&&(U.body=u);const R=performance.now(),V=await fetch(B,U),G=Math.round(performance.now()-R),z={};V.headers.forEach((ae,$)=>{z[$]=ae});let K;V.headers.get("content-type")?.includes("application/json")?K=await V.json():K=await V.text(),f({status:V.status,statusText:V.statusText,headers:z,body:K,duration:G})}catch(j){f({status:0,statusText:"Network Error",headers:{},body:j instanceof Error?j.message:"Unknown error",duration:0})}finally{x(!1)}},k=async()=>{if(h){const j=typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2);try{await navigator.clipboard.writeText(j),g(!0),setTimeout(()=>g(!1),2e3)}catch{const P=document.createElement("textarea");P.value=j,P.style.position="fixed",P.style.left="-999999px",document.body.appendChild(P),P.select(),document.execCommand("copy"),document.body.removeChild(P),g(!0),setTimeout(()=>g(!1),2e3)}}},A=(n.parameters||[]).filter(j=>j.in==="path"),M=(n.parameters||[]).filter(j=>j.in==="query"),C=["post","put","patch"].includes(e)&&n.requestBody;return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[s?i.jsx(Un,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${xZe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),i.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&i.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&i.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),A.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),i.jsx("div",{className:"space-y-2",children:A.map(j=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&i.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),i.jsx("input",{type:"text",value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),M.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),i.jsx("div",{className:"space-y-2",children:M.map(j=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&i.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),j.schema?.enum?i.jsxs("select",{value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:"-- Select --"}),j.schema.enum.map(P=>i.jsx("option",{value:P,children:P},P))]}):i.jsx("input",{type:"text",value:l[j.name]||"",onChange:P=>c(E=>({...E,[j.name]:P.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),C&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),i.jsx("textarea",{value:u,onChange:j=>d(j.target.value),rows:8,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono focus:border-bambu-green focus:outline-none resize-y",placeholder:"JSON request body..."})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{onClick:N,disabled:p,children:[p?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(io,{className:"w-4 h-4"}),"Execute"]}),_.length>0&&i.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[i.jsx(Ba,{className:"w-3 h-3"}),"Fill in: ",_.join(", ")]})]}),h&&i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",i.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${h.status>=200&&h.status<300?"bg-green-500/20 text-green-400":h.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[h.status," ",h.statusText]}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[h.duration,"ms"]})]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:k,children:v?i.jsx(pr,{className:"w-3 h-3 text-green-400"}):i.jsx(Yl,{className:"w-3 h-3"})})]}),i.jsx("pre",{className:"p-3 bg-bambu-dark rounded-lg text-sm font-mono text-white overflow-auto max-h-96 border border-bambu-dark-tertiary",children:typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2)})]})]})]})}function wZe({apiKey:t=""}){const[e,n]=w.useState(null),[r,a]=w.useState(!0),[s,o]=w.useState(null),[l,c]=w.useState(new Set),[u,d]=w.useState("");if(w.useEffect(()=>{async function g(){try{const y=await fetch("/openapi.json");if(!y.ok)throw new Error("Failed to fetch OpenAPI schema");const _=await y.json();n(_)}catch(y){o(y instanceof Error?y.message:"Unknown error")}finally{a(!1)}}g()},[]),r)return i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return i.jsx(vt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-red-400",children:[i.jsx(Ba,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),i.jsx("p",{children:"Failed to load API schema"}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const h={};for(const[g,y]of Object.entries(e.paths))for(const[_,N]of Object.entries(y)){if(_==="parameters")continue;const k=N.tags||["Other"];for(const A of k)h[A]||(h[A]=[]),h[A].push({path:g,method:_,spec:N})}const f=Object.entries(h).map(([g,y])=>{if(!u)return{tag:g,endpoints:y};const _=y.filter(({path:N,method:k,spec:A})=>{const M=u.toLowerCase();return N.toLowerCase().includes(M)||k.toLowerCase().includes(M)||(A.summary?.toLowerCase()||"").includes(M)||(A.description?.toLowerCase()||"").includes(M)});return{tag:g,endpoints:_}}).filter(({endpoints:g})=>g.length>0).sort((g,y)=>g.tag.localeCompare(y.tag)),p=g=>{c(y=>{const _=new Set(y);return _.has(g)?_.delete(g):_.add(g),_})},x=()=>{c(new Set(f.map(g=>g.tag)))},v=()=>{c(new Set)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsx("div",{className:"flex-1",children:i.jsx("input",{type:"text",value:u,onChange:g=>d(g.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:v,children:"Collapse All"}),i.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[i.jsx(Kr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[f.reduce((g,y)=>g+y.endpoints.length,0)," endpoints in ",f.length," categories"]}),i.jsx("div",{className:"space-y-3",children:f.map(({tag:g,endpoints:y})=>i.jsxs(vt,{children:[i.jsx("button",{onClick:()=>p(g),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:i.jsxs("div",{className:"flex items-center gap-2",children:[l.has(g)?i.jsx(Un,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(pi,{className:"w-5 h-5 text-bambu-gray"}),i.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:g.replace(/-/g," ")}),i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:y.length})]})}),l.has(g)&&i.jsx(_t,{className:"pt-0 space-y-2",children:y.map(({path:_,method:N,spec:k})=>i.jsx(vZe,{path:_,method:N,spec:k,schema:e,apiKey:t},`${N}-${_}`))})]},g))})]})}const SZe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"],_Ze={database:"bg-blue-600",library_files:"bg-green-500",library_thumbnails:"bg-teal-500",library_other:"bg-emerald-700",archive_timelapses:"bg-red-500",archive_thumbnails:"bg-amber-500",archive_files:"bg-sky-500",virtual_printer_uploads:"bg-purple-500",virtual_printer_upload_cache:"bg-fuchsia-500",virtual_printer_certs:"bg-violet-500",virtual_printer_other:"bg-purple-700",downloads:"bg-cyan-500",plate_calibration:"bg-lime-500",logs:"bg-orange-500",other_data:"bg-yellow-500"},QW=["bg-blue-500","bg-green-500","bg-yellow-500","bg-red-500","bg-orange-500","bg-teal-500","bg-cyan-500","bg-purple-500"],ZW=(t,e)=>_Ze[t]||QW[e%QW.length];function NZe(){const t=tn(),e=rc(),[n,r]=dF(),{t:a,i18n:s}=Ut(),{showToast:o}=cn(),{authEnabled:l,user:c,refreshAuth:u}=Or(),{mode:d,darkStyle:h,darkBackground:f,darkAccent:p,lightStyle:x,lightBackground:v,lightAccent:g,setDarkStyle:y,setDarkBackground:_,setDarkAccent:N,setLightStyle:k,setLightBackground:A,setLightAccent:M}=Jf(),[C,j]=w.useState(null),[P,E]=w.useState(!1),[B,O]=w.useState(null),[U,R]=w.useState(!1),[V,G]=w.useState(null),[z,K]=w.useState(null),[Y,ae]=w.useState(!1),[$,W]=w.useState(yX()),ee=n.get("tab"),J=ee==="email",ye=J?"users":ee&&SZe.includes(ee)?ee:"general",[me,te]=w.useState(ye),[je,ue]=w.useState(J?"email":"users"),oe=ce=>{te(ce),ce==="users"&&ue("users"),ce==="general"?n.delete("tab"):n.set("tab",ce),r(n,{replace:!0})},[_e,se]=w.useState(!1),[Oe,q]=w.useState(""),[X,de]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[Z,ie]=w.useState(null),[le,Fe]=w.useState(null),[pe,Q]=w.useState(""),[L,D]=w.useState(!1),[H,he]=w.useState(!1),[be,fe]=w.useState(null),[ze,Ie]=w.useState(!1),[qe,tt]=w.useState(!1),[Ee,Se]=w.useState(!1),[Me,xe]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[ve,He]=w.useState(!1),[Pe,nt]=w.useState(!1),[Te,Ge]=w.useState(!1),[Re,Le]=w.useState(!1),[Ke,ft]=w.useState(null),[kt,Lt]=w.useState(null),[Kt,Mt]=w.useState(null),[Ue,bt]=w.useState(!1),[wt,qt]=w.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[Cn,yr]=w.useState(null),[Qn,tr]=w.useState(null),[Pn,dr]=w.useState(!1),[Ar,ii]=w.useState({}),[De,we]=w.useState({}),et=ce=>{W(ce),cge(ce),o(a("settings.toast.settingsSaved"),"success")},st=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:Ve,isLoading:Ot}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:ge,isLoading:Be,isFetching:Xe}=Je({queryKey:["storage-usage"],queryFn:()=>ne.getStorageUsage(),enabled:me==="general",staleTime:1/0,refetchInterval:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),We=async()=>{nt(!0);try{const ce=await ne.getStorageUsage({refresh:!0});t.setQueryData(["storage-usage"],ce)}catch(ce){const Et=ce instanceof Error?ce.message:"Failed to refresh storage usage";o(Et,"error")}finally{nt(!1)}},{data:Ne,isLoading:lt}=Je({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:pt,isLoading:at}=Je({queryKey:["smart-plugs-energy",Ne?.map(ce=>ce.id)],queryFn:async()=>{if(!Ne||Ne.length===0)return null;const ce=await Promise.all(Ne.filter(mo=>mo.enabled).map(async mo=>{try{const _s=await ne.getSmartPlugStatus(mo.id);return{plug:mo,status:_s}}catch{return{plug:mo,status:null}}}));let Et=0,ia=0,Gr=0,Xc=0,op=0;for(const{plug:mo,status:_s}of ce){const kA=mo.plug_type==="mqtt"&&_s?.energy?.power!=null;(_s?.reachable||kA)&&_s?.energy&&(op++,_s.energy?.power!=null&&(Et+=_s.energy.power),_s.energy?.today!=null&&(ia+=_s.energy.today),_s.energy?.yesterday!=null&&(Gr+=_s.energy.yesterday),_s.energy?.total!=null&&(Xc+=_s.energy.total))}return{totalPower:Et,totalToday:ia,totalYesterday:Gr,totalLifetime:Xc,reachableCount:op,totalPlugs:Ne.filter(mo=>mo.enabled).length}},enabled:me==="plugs"&&!!Ne&&Ne.length>0,refetchInterval:me==="plugs"?1e4:!1}),{data:At,isLoading:Ht}=Je({queryKey:["notification-providers"],queryFn:ne.getNotificationProviders}),{data:Dt,isLoading:Pt}=Je({queryKey:["api-keys"],queryFn:ne.getAPIKeys}),an=ot({mutationFn:ce=>ne.createAPIKey(ce),onSuccess:ce=>{ie(ce.key||null),se(!1),q(""),t.invalidateQueries({queryKey:["api-keys"]}),o(a("settings.toast.apiKeyCreated"))},onError:ce=>{o(`Failed to create API key: ${ce.message}`,"error")}}),Zt=ot({mutationFn:ce=>ne.deleteAPIKey(ce),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(a("settings.toast.apiKeyDeleted"))},onError:ce=>{o(`Failed to delete API key: ${ce.message}`,"error")}}),{data:un}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:kn,isLoading:jn}=Je({queryKey:["notification-templates"],queryFn:ne.getNotificationTemplates}),{data:Xt}=Je({queryKey:["virtual-printer-settings"],queryFn:Qpe.getSettings,refetchInterval:1e4}),mn=Xt?.status?.running??!1,{data:fn}=Je({queryKey:["ffmpeg-status"],queryFn:ne.checkFfmpeg}),{data:qr}=Je({queryKey:["version"],queryFn:ne.getVersion}),{data:pn,refetch:Dn,isRefetching:aa}=Je({queryKey:["updateCheck"],queryFn:ne.checkForUpdates,enabled:Ve?.check_updates!==!1,staleTime:300*1e3}),{data:Sn,refetch:va}=Je({queryKey:["updateStatus"],queryFn:ne.getUpdateStatus,refetchInterval:ce=>{const Et=ce.state.data;return Et?.status==="downloading"||Et?.status==="installing"?1e3:!1}}),{data:sr}=Je({queryKey:["mqtt-status"],queryFn:ne.getMQTTStatus,refetchInterval:me==="network"?5e3:!1}),{data:ha}=Je({queryKey:["github-backup-status"],queryFn:ne.getGitHubBackupStatus}),{data:xt}=Je({queryKey:["cloud-status"],queryFn:ne.getCloudStatus}),{data:Rt={advanced_auth_enabled:!1,smtp_configured:!1}}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()}),{hasPermission:bn}=Or(),{data:Nt=[],isLoading:Zn}=Je({queryKey:["users"],queryFn:()=>ne.getUsers(),enabled:l&&bn("users:read")}),{data:vr=[],isLoading:hr}=Je({queryKey:["groups"],queryFn:()=>ne.getGroups(),enabled:l&&bn("groups:read")}),wa=ot({mutationFn:ce=>ne.createUser(ce),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(a("settings.toast.userCreated"))},onError:ce=>{o(ce.message,"error")}}),Va=ot({mutationFn:({id:ce,data:Et})=>ne.updateUser(ce,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(a("settings.toast.userUpdated"))},onError:ce=>{o(ce.message,"error")}}),$t=ot({mutationFn:({id:ce,deleteItems:Et})=>ne.deleteUser(ce,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(a("settings.toast.userDeleted")),Lt(null),Mt(null)},onError:ce=>{o(ce.message,"error")}}),xn=ot({mutationFn:ce=>ne.resetUserPassword({user_id:ce}),onSuccess:ce=>{o(ce.message,"success")},onError:ce=>{o(ce.message,"error")}}),Ss=async ce=>{Lt(ce),bt(!0);try{const Et=await ne.getUserItemsCount(ce);Mt(Et)}catch{Mt({archives:0,queue_items:0,library_files:0})}finally{bt(!1)}},Ci=ot({mutationFn:ce=>ne.deleteGroup(ce),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(a("settings.toast.groupDeleted"))},onError:ce=>{o(ce.message,"error")}}),ns=()=>{const ce=Rt?.advanced_auth_enabled||!1;if(!wt.username){o(a("settings.toast.fillRequiredFields"),"error");return}if(ce&&!wt.email){o("Email is required when advanced authentication is enabled","error");return}if(!ce){if(!wt.password){o(a("settings.toast.fillRequiredFields"),"error");return}if(wt.password!==wt.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(wt.password.length<6){o(a("settings.toast.passwordTooShort"),"error");return}}wa.mutate({username:wt.username,password:ce?void 0:wt.password,email:wt.email||void 0,role:wt.role,group_ids:wt.group_ids.length>0?wt.group_ids:void 0})},Tl=ce=>{if(wt.password){if(wt.password!==wt.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(wt.password.length<6){o(a("settings.toast.passwordTooShort"),"error");return}}const Et={username:wt.username||void 0,password:wt.password||void 0,role:wt.role,group_ids:wt.group_ids};Et.password||delete Et.password,Va.mutate({id:ce,data:Et})},rs=ce=>{ft(ce.id),qt({username:ce.username,password:"",email:ce.email||"",confirmPassword:"",role:ce.role,group_ids:ce.groups?.map(Et=>Et.id)||[]}),Le(!0)},si=ce=>{qt(Et=>({...Et,group_ids:Et.group_ids.includes(ce)?Et.group_ids.filter(ia=>ia!==ce):[...Et.group_ids,ce]}))},Sa=ot({mutationFn:ne.applyUpdate,onSuccess:ce=>{ce.is_docker?o(ce.message,"error"):va()}}),[Yr,mr]=w.useState(null),uo=ot({mutationFn:ne.testAllNotificationProviders,onSuccess:ce=>{mr(ce),t.invalidateQueries({queryKey:["notification-providers"]}),ce.failed===0?o(`All ${ce.tested} providers tested successfully!`,"success"):o(`${ce.success}/${ce.tested} providers succeeded`,ce.failed>0?"error":"success")},onError:ce=>{o(`Failed to test providers: ${ce.message}`,"error")}}),qa=ot({mutationFn:async ce=>{if(!Ne)return{success:0,failed:0};const Et=Ne.filter(Gr=>Gr.enabled),ia=await Promise.all(Et.map(async Gr=>{try{return await ne.controlSmartPlug(Gr.id,ce),{success:!0}}catch{return{success:!1}}}));return{success:ia.filter(Gr=>Gr.success).length,failed:ia.filter(Gr=>!Gr.success).length}},onSuccess:(ce,Et)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ce.failed===0?o(`All ${ce.success} plugs turned ${Et}`,"success"):o(`${ce.success} plugs turned ${Et}, ${ce.failed} failed`,"error")},onError:ce=>{o(`Failed: ${ce.message}`,"error")}}),Oa=w.useRef(null),ho=w.useRef(!1),zr=w.useRef(!0);w.useEffect(()=>{if(Ve&&!C){const ce={...Ve,external_url:Ve.external_url||window.location.origin};j(ce),setTimeout(()=>{zr.current=!1},100)}},[Ve,C]);const ma=ot({mutationFn:ne.updateSettings,onSuccess:ce=>{t.setQueryData(["settings"],ce),j(ce),t.invalidateQueries({queryKey:["archiveStats"]}),o(a("settings.toast.settingsSaved"),"success")},onError:ce=>{o(`Failed to save: ${ce.message}`,"error")},onSettled:()=>{ho.current=!1}}),Us=ot({mutationFn:({id:ce,data:Et})=>ne.updatePrinter(ce,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(a("settings.toast.cameraSettingsSaved"),"success")},onError:ce=>{o(`Failed to update printer: ${ce.message}`,"error")}});w.useEffect(()=>{if(!(zr.current||!C||!Ve||!(Ve.auto_archive!==C.auto_archive||Ve.save_thumbnails!==C.save_thumbnails||Ve.capture_finish_photo!==C.capture_finish_photo||Ve.default_filament_cost!==C.default_filament_cost||Ve.currency!==C.currency||Ve.energy_cost_per_kwh!==C.energy_cost_per_kwh||Ve.energy_tracking_mode!==C.energy_tracking_mode||Ve.check_updates!==C.check_updates||(Ve.check_printer_firmware??!0)!==(C.check_printer_firmware??!0)||(Ve.include_beta_updates??!1)!==(C.include_beta_updates??!1)||Ve.notification_language!==C.notification_language||(Ve.bed_cooled_threshold??35)!==(C.bed_cooled_threshold??35)||Ve.ams_humidity_good!==C.ams_humidity_good||Ve.ams_humidity_fair!==C.ams_humidity_fair||Ve.ams_temp_good!==C.ams_temp_good||Ve.ams_temp_fair!==C.ams_temp_fair||Ve.ams_history_retention_days!==C.ams_history_retention_days||Ve.per_printer_mapping_expanded!==C.per_printer_mapping_expanded||Ve.date_format!==C.date_format||Ve.time_format!==C.time_format||Ve.default_printer_id!==C.default_printer_id||Ve.ftp_retry_enabled!==C.ftp_retry_enabled||Ve.ftp_retry_count!==C.ftp_retry_count||Ve.ftp_retry_delay!==C.ftp_retry_delay||Ve.ftp_timeout!==C.ftp_timeout||Ve.mqtt_enabled!==C.mqtt_enabled||Ve.mqtt_broker!==C.mqtt_broker||Ve.mqtt_port!==C.mqtt_port||Ve.mqtt_username!==C.mqtt_username||Ve.mqtt_password!==C.mqtt_password||Ve.mqtt_topic_prefix!==C.mqtt_topic_prefix||Ve.mqtt_use_tls!==C.mqtt_use_tls||Ve.external_url!==C.external_url||Ve.ha_enabled!==C.ha_enabled||Ve.ha_url!==C.ha_url||Ve.ha_token!==C.ha_token||(Ve.library_archive_mode??"ask")!==(C.library_archive_mode??"ask")||Number(Ve.library_disk_warning_gb??5)!==Number(C.library_disk_warning_gb??5)||(Ve.camera_view_mode??"window")!==(C.camera_view_mode??"window")||(Ve.preferred_slicer??"bambu_studio")!==(C.preferred_slicer??"bambu_studio")||Ve.prometheus_enabled!==C.prometheus_enabled||Ve.prometheus_token!==C.prometheus_token))&&!ho.current)return Oa.current&&clearTimeout(Oa.current),Oa.current=setTimeout(()=>{if(ho.current)return;ho.current=!0;const Et={auto_archive:C.auto_archive,save_thumbnails:C.save_thumbnails,capture_finish_photo:C.capture_finish_photo,default_filament_cost:C.default_filament_cost,currency:C.currency,energy_cost_per_kwh:C.energy_cost_per_kwh,energy_tracking_mode:C.energy_tracking_mode,check_updates:C.check_updates,check_printer_firmware:C.check_printer_firmware,include_beta_updates:C.include_beta_updates,notification_language:C.notification_language,bed_cooled_threshold:C.bed_cooled_threshold,ams_humidity_good:C.ams_humidity_good,ams_humidity_fair:C.ams_humidity_fair,ams_temp_good:C.ams_temp_good,ams_temp_fair:C.ams_temp_fair,ams_history_retention_days:C.ams_history_retention_days,per_printer_mapping_expanded:C.per_printer_mapping_expanded,date_format:C.date_format,time_format:C.time_format,default_printer_id:C.default_printer_id,ftp_retry_enabled:C.ftp_retry_enabled,ftp_retry_count:C.ftp_retry_count,ftp_retry_delay:C.ftp_retry_delay,ftp_timeout:C.ftp_timeout,mqtt_enabled:C.mqtt_enabled,mqtt_broker:C.mqtt_broker,mqtt_port:C.mqtt_port,mqtt_username:C.mqtt_username,mqtt_password:C.mqtt_password,mqtt_topic_prefix:C.mqtt_topic_prefix,mqtt_use_tls:C.mqtt_use_tls,external_url:C.external_url,ha_enabled:C.ha_enabled,ha_url:C.ha_url,ha_token:C.ha_token,library_archive_mode:C.library_archive_mode,library_disk_warning_gb:C.library_disk_warning_gb,camera_view_mode:C.camera_view_mode,preferred_slicer:C.preferred_slicer,prometheus_enabled:C.prometheus_enabled,prometheus_token:C.prometheus_token};ma.mutate(Et)},500),()=>{Oa.current&&clearTimeout(Oa.current)}},[C,Ve,ma]);const Bt=w.useCallback((ce,Et)=>{j(ia=>ia?{...ia,[ce]:Et}:null)},[]),Vn=async(ce,Et,ia)=>{if(!Et){o(a("settings.toast.enterCameraUrl"),"error");return}we(Gr=>({...Gr,[ce]:!0})),ii(Gr=>({...Gr,[ce]:null}));try{const Gr=await ne.testExternalCamera(ce,Et,ia);ii(Xc=>({...Xc,[ce]:Gr})),Gr.success?o(a("settings.toast.cameraConnected",{resolution:Gr.resolution||""}),"success"):o(Gr.error||a("settings.toast.connectionFailed"),"error")}catch(Gr){const Xc=Gr instanceof Error?Gr.message:a("settings.toast.testFailed");ii(op=>({...op,[ce]:{success:!1,error:Xc}})),o(Xc,"error")}finally{we(Gr=>({...Gr,[ce]:!1}))}},[Ml,um]=w.useState({}),Kc=w.useRef({}),q0=w.useRef(new Set);w.useEffect(()=>{if(un){const ce={};un.forEach(Et=>{Et.external_camera_url&&!q0.current.has(Et.id)&&(ce[Et.id]=Et.external_camera_url,q0.current.add(Et.id))}),Object.keys(ce).length>0&&um(Et=>({...Et,...ce}))}},[un]);const lx=(ce,Et)=>{um(ia=>({...ia,[ce]:Et})),Kc.current[ce]&&clearTimeout(Kc.current[ce]),Kc.current[ce]=setTimeout(()=>{Us.mutate({id:ce,data:{external_camera_url:Et||null}})},800)},sp=(ce,Et)=>{const ia={};Et.type!==void 0&&(ia.external_camera_type=Et.type||null),Et.enabled!==void 0&&(ia.external_camera_enabled=Et.enabled),Us.mutate({id:ce,data:ia})};return Ot||!C?i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-8",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:a("settings.title")}),i.jsx("p",{className:"text-bambu-gray",children:a("settings.configureBambuddy")})]}),i.jsxs("div",{className:"flex flex-wrap gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>oe("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${me==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:a("settings.tabs.general")}),i.jsxs("button",{onClick:()=>oe("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(fl,{className:"w-4 h-4"}),a("settings.tabs.smartPlugs"),Ne&&Ne.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ne.length})]}),i.jsxs("button",{onClick:()=>oe("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Hg,{className:"w-4 h-4"}),a("settings.tabs.notifications"),At&&At.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:At.length})]}),i.jsxs("button",{onClick:()=>oe("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Ohe,{className:"w-4 h-4"}),a("settings.tabs.filament")]}),i.jsxs("button",{onClick:()=>oe("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Vg,{className:"w-4 h-4"}),a("settings.tabs.network"),i.jsx("span",{className:`w-2 h-2 rounded-full ${sr?.enabled?"bg-green-400":"bg-gray-500"}`})]}),i.jsxs("button",{onClick:()=>oe("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(nl,{className:"w-4 h-4"}),a("settings.tabs.apiKeys"),Dt&&Dt.length>0&&i.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Dt.length})]}),i.jsxs("button",{onClick:()=>oe("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(xr,{className:"w-4 h-4"}),a("settings.tabs.virtualPrinter"),i.jsx("span",{className:`w-2 h-2 rounded-full ${mn?"bg-green-400":"bg-gray-500"}`})]}),i.jsxs("button",{onClick:()=>oe("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(hh,{className:"w-4 h-4"}),a("settings.tabs.users"),l&&i.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),i.jsxs("button",{onClick:()=>oe("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${me==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(Pc,{className:"w-4 h-4"}),a("settings.tabs.backup"),i.jsx("span",{className:`w-2 h-2 rounded-full ${xt?.is_authenticated&&ha?.configured&&ha?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),me==="general"&&i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.general")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(Mh,{className:"w-4 h-4 inline mr-1"}),a("settings.language")]}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:s.language,onChange:ce=>{s.changeLanguage(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:hB.map(ce=>i.jsxs("option",{value:ce.code,children:[ce.nativeName," (",ce.name,")"]},ce.code))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.languageDescription")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.defaultView")}),i.jsxs("div",{className:"relative",children:[i.jsx("select",{value:$,onChange:ce=>et(ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:pv.map(ce=>i.jsx("option",{value:ce.to,children:a(ce.labelKey)},ce.id))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.defaultViewDescription")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.date_format||"system",onChange:ce=>Bt("date_format",ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"system",children:a("settings.systemDefault")}),i.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),i.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),i.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.time_format||"system",onChange:ce=>Bt("time_format",ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"system",children:a("settings.systemDefault")}),i.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),i.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.default_printer_id??"",onChange:ce=>Bt("default_printer_id",ce.target.value?Number(ce.target.value):null),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"",children:a("settings.noDefaultPrinter")}),un?.map(ce=>i.jsx("option",{value:ce.id,children:ce.name},ce.id))]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.preferredSlicer")}),i.jsxs("div",{className:"relative",children:[i.jsxs("select",{value:C.preferred_slicer??"bambu_studio",onChange:ce=>Bt("preferred_slicer",ce.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[i.jsx("option",{value:"bambu_studio",children:"Bambu Studio"}),i.jsx("option",{value:"orcaslicer",children:"OrcaSlicer"})]}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.preferredSlicerDescription")})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.sidebarOrder")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:st,children:[i.jsx(Fo,{className:"w-4 h-4"}),"Reset"]})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(VC,{className:"w-5 h-5"}),"Appearance"]})}),i.jsxs(_t,{className:"space-y-6",children:[i.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&i.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),i.jsxs("select",{value:f,onChange:ce=>{_(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"neutral",children:"Neutral"}),i.jsx("option",{value:"warm",children:"Warm"}),i.jsx("option",{value:"cool",children:"Cool"}),i.jsx("option",{value:"oled",children:"OLED Black"}),i.jsx("option",{value:"slate",children:"Slate Blue"}),i.jsx("option",{value:"forest",children:"Forest Green"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),i.jsxs("select",{value:p,onChange:ce=>{N(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"green",children:"Green"}),i.jsx("option",{value:"teal",children:"Teal"}),i.jsx("option",{value:"blue",children:"Blue"}),i.jsx("option",{value:"orange",children:"Orange"}),i.jsx("option",{value:"purple",children:"Purple"}),i.jsx("option",{value:"red",children:"Red"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),i.jsxs("select",{value:h,onChange:ce=>{y(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"classic",children:"Classic"}),i.jsx("option",{value:"glow",children:"Glow"}),i.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),i.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&i.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),i.jsxs("select",{value:v,onChange:ce=>{A(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"neutral",children:"Neutral"}),i.jsx("option",{value:"warm",children:"Warm"}),i.jsx("option",{value:"cool",children:"Cool"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),i.jsxs("select",{value:g,onChange:ce=>{M(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"green",children:"Green"}),i.jsx("option",{value:"teal",children:"Teal"}),i.jsx("option",{value:"blue",children:"Blue"}),i.jsx("option",{value:"orange",children:"Orange"}),i.jsx("option",{value:"purple",children:"Purple"}),i.jsx("option",{value:"red",children:"Red"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),i.jsxs("select",{value:x,onChange:ce=>{k(ce.target.value),o(a("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"classic",children:"Classic"}),i.jsx("option",{value:"glow",children:"Glow"}),i.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.archiveSettings")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Auto-archive prints"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.auto_archive,onChange:ce=>Bt("auto_archive",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.saveThumbnails")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.save_thumbnails,onChange:ce=>Bt("save_thumbnails",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.captureFinishPhoto")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.capture_finish_photo,onChange:ce=>Bt("capture_finish_photo",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.capture_finish_photo&&fn&&!fn.installed&&i.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"text-sm",children:[i.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),i.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",i.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",i.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(kF,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),i.jsxs("select",{value:C.camera_view_mode??"window",onChange:ce=>Bt("camera_view_mode",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",children:[i.jsx("option",{value:"window",children:a("settings.newWindow")}),i.jsx("option",{value:"embedded",children:a("settings.embeddedOverlay")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:a("settings.externalCameras")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Configure external cameras to replace the built-in printer camera. Supports MJPEG streams, RTSP, HTTP snapshots, and USB cameras (V4L2). When enabled, the external camera is used for live view and finish photos."}),un&&un.length>0?i.jsx("div",{className:"space-y-3",children:un.map(ce=>i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-white font-medium text-sm",children:ce.name}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:ce.external_camera_enabled,onChange:Et=>sp(ce.id,{enabled:Et.target.checked}),className:"sr-only peer"}),i.jsx("div",{className:"w-9 h-5 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:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),ce.external_camera_enabled&&i.jsxs("div",{className:"space-y-2 mt-2",children:[i.jsx("input",{type:"text",placeholder:ce.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Ml[ce.id]??ce.external_camera_url??"",onChange:Et=>lx(ce.id,Et.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:ce.external_camera_type||"mjpeg",onChange:Et=>sp(ce.id,{type:Et.target.value}),className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),i.jsx("option",{value:"rtsp",children:"RTSP Stream"}),i.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),i.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>Vn(ce.id,Ml[ce.id]??ce.external_camera_url??"",ce.external_camera_type||"mjpeg"),disabled:De[ce.id]||!(Ml[ce.id]??ce.external_camera_url),children:De[ce.id]?i.jsx(it,{className:"w-4 h-4 animate-spin"}):"Test"})]}),Ar[ce.id]&&i.jsx("div",{className:`text-xs flex items-center gap-1 ${Ar[ce.id]?.success?"text-green-500":"text-red-500"}`,children:Ar[ce.id]?.success?i.jsxs(i.Fragment,{children:[i.jsx(pr,{className:"w-3 h-3"}),"Connected",Ar[ce.id]?.resolution&&` (${Ar[ce.id]?.resolution})`]}):i.jsxs(i.Fragment,{children:[i.jsx(hi,{className:"w-3 h-3"}),Ar[ce.id]?.error||a("settings.toast.connectionFailed")]})})]})]},ce.id))}):i.jsx("p",{className:"text-xs text-bambu-gray italic",children:a("settings.noPrintersConfigured")})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.costTracking")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),i.jsx("select",{value:C.currency,onChange:ce=>Bt("currency",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",children:h$e.map(ce=>i.jsx("option",{value:ce.code,children:ce.label},ce.code))})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:rl(C.currency)}),i.jsx("input",{type:"number",step:"0.01",min:"0",value:C.default_filament_cost,onChange:ce=>Bt("default_filament_cost",parseFloat(ce.target.value)||0),style:{paddingLeft:`${Math.max(2,rl(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),i.jsxs("div",{className:"relative",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:rl(C.currency)}),i.jsx("input",{type:"number",step:"0.001",min:"0",value:C.energy_cost_per_kwh,onChange:ce=>Bt("energy_cost_per_kwh",parseFloat(ce.target.value)||0),style:{paddingLeft:`${Math.max(2,rl(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),i.jsxs("select",{value:C.energy_tracking_mode||"total",onChange:ce=>Bt("energy_tracking_mode",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",children:[i.jsx("option",{value:"print",children:a("settings.printsOnly")}),i.jsx("option",{value:"total",children:a("settings.totalConsumption")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),i.jsxs("select",{value:C.library_archive_mode??"ask",onChange:ce=>Bt("library_archive_mode",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",children:[i.jsx("option",{value:"always",children:a("settings.archiveMode.always")}),i.jsx("option",{value:"never",children:a("settings.archiveMode.never")}),i.jsx("option",{value:"ask",children:a("settings.archiveMode.ask")})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:C.library_disk_warning_gb??5,onChange:ce=>Bt("library_disk_warning_gb",parseFloat(ce.target.value)||5),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),i.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[i.jsx(cZe,{}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.checkForUpdatesLabel")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.check_updates,onChange:ce=>Bt("check_updates",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.checkPrinterFirmware")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.check_printer_firmware??!0,onChange:ce=>Bt("check_printer_firmware",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:`flex items-center justify-between ${C.check_updates?"":"opacity-50"}`,children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.includeBetaUpdates")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.includeBetaUpdatesDesc")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.include_beta_updates??!1,onChange:ce=>Bt("include_beta_updates",ce.target.checked),disabled:!C.check_updates,className:"sr-only peer"}),i.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"})]})]}),i.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.currentVersion")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",qr?.version||"..."]})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>Dn(),disabled:aa,children:[aa?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Cr,{className:"w-4 h-4"}),"Check now"]})]}),pn?.update_available?i.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{children:[i.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",pn.latest_version]}),pn.release_name&&pn.release_name!==pn.latest_version&&i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:pn.release_name})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[pn.release_notes&&i.jsx("button",{onClick:()=>Ie(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),pn.release_url&&i.jsx("a",{href:pn.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:a("settings.viewReleaseOnGitHub"),children:i.jsx(Kr,{className:"w-4 h-4"})})]})]}),Sn?.status==="downloading"||Sn?.status==="installing"?i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),i.jsx("span",{children:Sn.message})]}),i.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Sn.progress}%`}})})]}):Sn?.status==="complete"?i.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:Sn.message}):Sn?.status==="error"?i.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:Sn.error||Sn.message}):pn?.is_docker?i.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),i.jsx("code",{className:"block text-xs bg-bambu-dark p-2 rounded text-bambu-green font-mono",children:"docker compose pull && docker compose up -d"})]}):i.jsxs(Ce,{className:"mt-3",onClick:()=>Sa.mutate(),disabled:Sa.isPending,children:[Sa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(ua,{className:"w-4 h-4"}),"Install Update"]})]}):pn?.error?i.jsxs("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:["Failed to check for updates: ",pn.error]}):pn&&!pn.update_available?i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.dataManagement")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.clearNotificationLogs")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.clearNotificationLogsDescription")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>D(!0),children:[i.jsx(Jt,{className:"w-4 h-4"}),a("common.clear")]})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.resetUiPreferences")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.resetUiPreferencesDescription")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>he(!0),children:[i.jsx(Jt,{className:"w-4 h-4"}),"Reset"]})]}),i.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.storageUsage","Storage Usage")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.storageUsageDescription","Breakdown of data usage by category")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:We,disabled:Xe||Pe,children:[i.jsx(Cr,{className:`w-4 h-4 ${Xe||Pe?"animate-spin":""}`}),a("common.refresh","Refresh")]})]}),i.jsx("div",{className:"mt-3",children:Be?i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("common.loading","Loading")]}):ge?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-full h-3 bg-bambu-dark rounded-full overflow-hidden flex",children:ge.categories.filter(ce=>ce.bytes>0).map((ce,Et)=>i.jsx("div",{className:`${ZW(ce.key,Et)} h-full`,style:{width:`${ce.percent_of_total}%`},title:`${ce.label}: ${ce.formatted}`},ce.key))}),i.jsx("div",{className:"mt-3 flex flex-wrap gap-3",children:ge.categories.filter(ce=>ce.bytes>0).map((ce,Et)=>i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:`w-3 h-3 rounded-full ${ZW(ce.key,Et)}`}),i.jsx("span",{className:"text-bambu-gray",children:ce.label}),i.jsx("span",{className:"text-white",children:ce.formatted}),i.jsxs("span",{className:"text-bambu-gray",children:["(",ce.percent_of_total.toFixed(1),"%)"]})]},ce.key))}),i.jsxs("div",{className:"mt-2 text-xs text-bambu-gray",children:[a("settings.storageUsageTotal","Total"),": ",i.jsx("span",{className:"text-white",children:ge.total_formatted}),ge.scan_errors>0&&i.jsxs("span",{className:"ml-2 text-amber-400",children:[a("settings.storageUsageErrors","Scan errors"),": ",ge.scan_errors]})]}),ge.other_breakdown?.length>0&&i.jsxs("div",{className:"mt-4",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:a("settings.storageUsageOtherBreakdown","Other breakdown")}),i.jsx("div",{className:"space-y-2",children:ge.other_breakdown.map(ce=>i.jsxs("div",{className:"flex items-center justify-between text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-white",children:ce.label}),i.jsx("span",{className:`px-2 py-0.5 rounded-full border ${ce.kind==="system"?"border-slate-500 text-slate-300":"border-bambu-green text-bambu-green"}`,children:ce.kind==="system"?a("settings.storageUsageSystem","System"):a("settings.storageUsageData","Data")})]}),i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[i.jsx("span",{className:"text-white",children:ce.formatted}),i.jsxs("span",{children:["(",ce.percent_of_total.toFixed(1),"%)"]})]})]},`${ce.bucket}-${ce.kind}`))})]})]}):i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.storageUsageUnavailable","Storage usage data is unavailable")})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:"Backup & Restore"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>oe("backup"),children:[i.jsx(Pc,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),me==="network"&&C&&i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Mh,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),i.jsx("input",{type:"text",value:C.external_url??"",onChange:ce=>Bt("external_url",ce.target.value),placeholder:"http://192.168.1.100:8000",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"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Cr,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableRetry")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.ftp_retry_enabled??!0,onChange:ce=>Bt("ftp_retry_enabled",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.ftp_retry_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_retry_count??3,onChange:ce=>Bt("ftp_retry_count",parseInt(ce.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,4,5,6,7,8,9,10].map(ce=>i.jsxs("option",{value:ce,children:[ce," ",ce===1?"time":"times"]},ce))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_retry_delay??2,onChange:ce=>Bt("ftp_retry_delay",parseInt(ce.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,5,10,15,20,30].map(ce=>i.jsxs("option",{value:ce,children:[ce," ",ce===1?"second":"seconds"]},ce))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),i.jsxs("div",{className:"relative w-44",children:[i.jsx("select",{value:C.ftp_timeout??30,onChange:ce=>Bt("ftp_timeout",parseInt(ce.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[10,15,20,30,45,60,90,120].map(ce=>i.jsxs("option",{value:ce,children:[ce," seconds"]},ce))}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Increase for printers with weak WiFi"})]})]})]})]})]}),i.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(l0,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),C.ha_enabled&&Qn&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${Qn.success?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:`text-sm ${Qn.success?"text-green-400":"text-red-400"}`,children:Qn.success?"Connected":"Disconnected"})]})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-white",children:a("settings.enableHomeAssistant")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.homeAssistantDescription")}),C.ha_env_managed&&i.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[i.jsx(zm,{className:"w-3 h-3 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-green",children:a("settings.autoEnabledViaEnv")})]})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.ha_enabled??!1,onChange:ce=>Bt("ha_enabled",ce.target.checked),disabled:C.ha_env_managed,className:"sr-only peer"}),i.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 ${C.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),C.ha_enabled&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Home Assistant URL",C.ha_url_from_env&&i.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:a("settings.environmentManagedLabel")})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",value:C.ha_url??"",onChange:ce=>Bt("ha_url",ce.target.value),placeholder:"http://192.168.1.100:8123",disabled:C.ha_url_from_env,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 ${C.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_url_from_env&&i.jsx(zm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_url_from_env&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.urlFromEnvReadOnly")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Long-Lived Access Token",C.ha_token_from_env&&i.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:a("settings.environmentManagedLabel")})]}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"password",value:C.ha_token??"",onChange:ce=>Bt("ha_token",ce.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:C.ha_token_from_env,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 ${C.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_token_from_env&&i.jsx(zm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_token_from_env?i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("settings.tokenFromEnvReadOnly")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),C.ha_url&&C.ha_token&&i.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:i.jsxs(Ce,{variant:"secondary",size:"sm",disabled:Pn,onClick:async()=>{dr(!0),tr(null);try{const ce=await ne.testHAConnection(C.ha_url,C.ha_token);tr(ce)}catch(ce){tr({success:!1,message:null,error:ce instanceof Error?ce.message:a("common.unknownError")})}finally{dr(!1)}},children:[Pn?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Vg,{className:"w-4 h-4"}),a("settings.testConnection")]})})]})]})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Vg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),sr?.enabled&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${sr.connected?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:`text-sm ${sr.connected?"text-green-400":"text-red-400"}`,children:sr.connected?"Connected":"Disconnected"})]})]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems."}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableMqtt")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.mqtt_enabled??!1,onChange:ce=>Bt("mqtt_enabled",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.mqtt_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),i.jsx("input",{type:"text",value:C.mqtt_broker??"",onChange:ce=>Bt("mqtt_broker",ce.target.value),placeholder:"mqtt.example.com or 192.168.1.100",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"})]}),i.jsxs("div",{className:"flex items-end gap-4",children:[i.jsxs("div",{className:"flex-1",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),i.jsx("input",{type:"number",min:"1",max:"65535",value:C.mqtt_port??1883,onChange:ce=>Bt("mqtt_port",Math.min(65535,Math.max(1,parseInt(ce.target.value)||1883))),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.mqtt_use_tls??!1,onChange:ce=>{const Et=ce.target.checked;Bt("mqtt_use_tls",Et);const ia=C.mqtt_port??1883;Et&&ia===1883?Bt("mqtt_port",8883):!Et&&ia===8883&&Bt("mqtt_port",1883)},className:"sr-only peer"}),i.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"})]}),i.jsx("span",{className:"text-white text-sm",children:a("settings.useTls")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),i.jsx("input",{type:"text",value:C.mqtt_username??"",onChange:ce=>Bt("mqtt_username",ce.target.value),placeholder:a("settings.leaveEmptyForAnonymous"),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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),i.jsx("input",{type:"password",value:C.mqtt_password??"",onChange:ce=>Bt("mqtt_password",ce.target.value),placeholder:a("settings.leaveEmptyForAnonymous"),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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),i.jsx("input",{type:"text",value:C.mqtt_topic_prefix??"bambuddy",onChange:ce=>Bt("mqtt_topic_prefix",ce.target.value),placeholder:"bambuddy",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"}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",C.mqtt_topic_prefix||"bambuddy","/printers//status, etc."]})]}),sr&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx("span",{className:`w-2 h-2 rounded-full ${sr.connected?"bg-green-400":"bg-red-400"}`}),i.jsx("span",{className:"text-bambu-gray",children:sr.connected?i.jsxs(i.Fragment,{children:[a("settings.mqttConnectedTo")," ",i.jsxs("span",{className:"text-white",children:[sr.broker,":",sr.port]})]}):a("settings.spoolmanDisconnected")})]})})]})]})]})]}),i.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(s3,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",i.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white",children:a("settings.enableMetricsEndpoint")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.prometheusDescription")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.prometheus_enabled??!1,onChange:ce=>Bt("prometheus_enabled",ce.target.checked),className:"sr-only peer"}),i.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"})]})]}),C.prometheus_enabled&&i.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),i.jsx("input",{type:"password",value:C.prometheus_token??"",onChange:ce=>Bt("prometheus_token",ce.target.value),placeholder:a("settings.leaveEmptyForNoAuth"),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"}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",i.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer "})]})]}),i.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm text-white mb-2",children:a("settings.availableMetrics")}),i.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),i.jsxs("p",{children:[i.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),i.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),Qn&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[Qn.success?i.jsx(pr,{className:"w-8 h-8 text-green-400"}):i.jsx(hi,{className:"w-8 h-8 text-red-400"}),i.jsx("h3",{className:"text-lg font-medium text-white",children:Qn.success?"Connection Successful":"Connection Failed"})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:Qn.success?Qn.message||"Successfully connected to Home Assistant.":Qn.error||"Failed to connect to Home Assistant."}),i.jsx("div",{className:"flex justify-end",children:i.jsx(Ce,{variant:"primary",onClick:()=>tr(null),children:"OK"})})]})}),me==="plugs"&&i.jsxs("div",{className:"max-w-4xl",children:[i.jsxs("div",{className:"flex items-start justify-between mb-6",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(fl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers."})]}),i.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Ne&&Ne.filter(ce=>ce.enabled).length>1&&i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>fe("on"),disabled:qa.isPending,title:a("settings.turnAllPlugsOn"),children:[qa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(hd,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),i.jsxs(Ce,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>fe("off"),disabled:qa.isPending,title:a("settings.turnAllPlugsOff"),children:[qa.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(GC,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),i.jsxs(Ce,{className:"whitespace-nowrap",onClick:()=>{O(null),E(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Ne&&Ne.length>0&&i.jsxs(vt,{className:"mb-6",children:[i.jsx(In,{children:i.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[i.jsx(Vh,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",at&&i.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),i.jsx(_t,{children:pt?i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(Vh,{className:"w-3 h-3"}),"Current Power"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalPower.toFixed(1),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[pt.reachableCount,"/",pt.totalPlugs," plugs online"]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(na,{className:"w-3 h-3"}),"Today"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalToday.toFixed(3),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalToday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(s3,{className:"w-3 h-3"}),"Yesterday"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalYesterday.toFixed(3),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalYesterday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[i.jsx(Jj,{className:"w-3 h-3"}),"Total"]}),i.jsxs("div",{className:"text-xl font-bold text-white",children:[pt.totalLifetime.toFixed(1),i.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(pt.totalLifetime*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",rl(C?.currency||"USD")]})]})]}):at?null:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),lt?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Ne&&Ne.length>0?i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ne.map(ce=>i.jsx(KQe,{plug:ce,onEdit:Et=>{O(Et),E(!0)}},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-12",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(fl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:a("settings.noSmartPlugsTitle")}),i.jsx("p",{className:"text-sm mb-4",children:a("settings.noSmartPlugsDescription")}),i.jsxs(Ce,{onClick:()=>{O(null),E(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addFirstSmartPlug")]})]})})})]}),me==="notifications"&&i.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Hg,{className:"w-5 h-5 text-bambu-green"}),a("settings.providers")]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>ae(!0),children:[i.jsx(mv,{className:"w-4 h-4"}),a("settings.log")]}),At&&At.length>0&&i.jsxs(Ce,{size:"sm",variant:"secondary",onClick:()=>{mr(null),uo.mutate()},disabled:uo.isPending,children:[uo.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(WC,{className:"w-4 h-4"}),a("settings.testAll")]}),i.jsxs(Ce,{size:"sm",onClick:()=>{G(null),R(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),"Add"]})]})]}),i.jsx(vt,{className:"mb-4",children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white text-sm font-medium",children:a("settings.notificationLanguage")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.notificationLanguageDescription")})]}),i.jsx("select",{value:C.notification_language||"en",onChange:ce=>Bt("notification_language",ce.target.value),className:"px-2 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:hB.map(ce=>i.jsx("option",{value:ce.code,children:ce.nativeName},ce.code))})]})})}),i.jsx(vt,{className:"mb-4",children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-white text-sm font-medium",children:a("settings.bedCooledThreshold")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.bedCooledThresholdDescription")})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("input",{type:"number",min:20,max:80,step:1,value:C.bed_cooled_threshold??35,onChange:ce=>Bt("bed_cooled_threshold",Number(ce.target.value)),className:"w-16 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm text-center focus:outline-none focus:ring-1 focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:"°C"})]})]})})}),Yr&&i.jsx(vt,{className:"mb-4",children:i.jsxs(_t,{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm font-medium text-white",children:a("settings.testResults")}),i.jsx("button",{onClick:()=>mr(null),className:"text-bambu-gray hover:text-white text-xs",children:a("common.dismiss")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[i.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[i.jsx(pr,{className:"w-4 h-4"}),a("settings.testPassedCount",{count:Yr.success})]}),Yr.failed>0&&i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(hi,{className:"w-4 h-4"}),a("settings.testFailedCount",{count:Yr.failed})]})]}),Yr.results.filter(ce=>!ce.success).length>0&&i.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:Yr.results.filter(ce=>!ce.success).map(ce=>i.jsxs("div",{className:"text-xs text-red-400",children:[i.jsxs("span",{className:"font-medium",children:[ce.provider_name,":"]})," ",ce.message]},ce.provider_id))})]})}),Ht?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):At&&At.length>0?i.jsx("div",{className:"space-y-3",children:At.map(ce=>i.jsx(QQe,{provider:ce,onEdit:Et=>{G(Et),R(!0)}},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(Hg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:a("settings.noProvidersTitle")}),i.jsx("p",{className:"text-xs mb-3",children:a("settings.noProvidersDescription")}),i.jsxs(Ce,{size:"sm",onClick:()=>{G(null),R(!0)},children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addProvider")]})]})})})]}),i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[i.jsx(Ms,{className:"w-5 h-5 text-bambu-green"}),a("settings.messageTemplates")]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:a("settings.messageTemplatesDescription")}),jn?i.jsx("div",{className:"flex justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):kn&&kn.length>0?i.jsx("div",{className:"space-y-2",children:[...kn].sort((ce,Et)=>ce.name.localeCompare(Et.name)).map(ce=>i.jsx(vt,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>K(ce),children:i.jsx(_t,{className:"py-2.5 px-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium text-sm truncate",children:ce.name}),i.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ce.title_template})]}),i.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:Et=>{Et.stopPropagation(),K(ce)},children:i.jsx(Jm,{className:"w-4 h-4 text-bambu-gray"})})]})})},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-8",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(Ms,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),i.jsx("p",{className:"text-sm",children:a("settings.noTemplatesAvailable")})]})})})]})]}),me==="apikeys"&&i.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(nl,{className:"w-5 h-5 text-bambu-green"}),a("settings.apiKeys")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.apiKeysDescription")})]}),i.jsxs(Ce,{size:"sm",onClick:()=>se(!0),className:"flex-shrink-0",children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.createKey")]})]}),Z&&i.jsx(vt,{className:"mb-6 border-bambu-green",children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(pr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:a("settings.apiKeyCreated")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:a("settings.apiKeyCopyWarning")}),i.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[i.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:Z}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(Z);else{const ce=document.createElement("textarea");ce.value=Z,ce.style.position="fixed",ce.style.left="-999999px",document.body.appendChild(ce),ce.select(),document.execCommand("copy"),document.body.removeChild(ce)}o(a("settings.toast.keyCopied"))}catch{o(a("settings.toast.copyFailed"),"error")}},children:i.jsx(Yl,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex gap-2 mt-3",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>{Q(Z),o(a("settings.toast.keyAddedToBrowser"))},children:a("settings.useInApiBrowser")}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>ie(null),children:a("common.dismiss")})]})]})]})})}),_e&&i.jsxs(vt,{className:"mb-6",children:[i.jsx(In,{children:i.jsx("h3",{className:"text-base font-semibold text-white",children:a("settings.createNewApiKey")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.keyName")}),i.jsx("input",{type:"text",value:Oe,onChange:ce=>q(ce.target.value),placeholder:a("settings.keyNamePlaceholder"),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"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:a("common.permissions")}),i.jsxs("div",{className:"space-y-2",children:[i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:X.can_read_status,onChange:ce=>de(Et=>({...Et,can_read_status:ce.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.readStatus")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.readStatusDescription")})]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:X.can_queue,onChange:ce=>de(Et=>({...Et,can_queue:ce.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.manageQueue")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.manageQueueDescription")})]})]}),i.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:X.can_control_printer,onChange:ce=>de(Et=>({...Et,can_control_printer:ce.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),i.jsxs("div",{children:[i.jsx("span",{className:"text-white",children:a("settings.controlPrinter")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.controlPrinterDescription")})]})]})]})]}),i.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[i.jsxs(Ce,{onClick:()=>an.mutate({name:Oe||a("settings.unnamedKey"),...X}),disabled:an.isPending,children:[an.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Xn,{className:"w-4 h-4"}),a("settings.createKey")]}),i.jsx(Ce,{variant:"secondary",onClick:()=>se(!1),children:a("common.cancel")})]})]})]}),Pt?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Dt&&Dt.length>0?i.jsx("div",{className:"space-y-3",children:Dt.map(ce=>i.jsx(vt,{children:i.jsx(_t,{className:"py-3",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(nl,{className:`w-5 h-5 ${ce.enabled?"text-bambu-green":"text-bambu-gray"}`}),i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium",children:ce.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[ce.key_prefix,"••••••••",ce.last_used&&` · ${a("settings.lastUsed")}: ${cb(ce.last_used)}`]})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex gap-1 text-xs",children:[ce.can_read_status&&i.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:a("settings.read")}),ce.can_queue&&i.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:a("queue.title")}),ce.can_control_printer&&i.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:a("settings.control")})]}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>Fe(ce.id),children:i.jsx(Jt,{className:"w-4 h-4 text-red-400"})})]})]})})},ce.id))}):i.jsx(vt,{children:i.jsx(_t,{className:"py-12",children:i.jsxs("div",{className:"text-center text-bambu-gray",children:[i.jsx(nl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:a("settings.apiKeysEmptyTitle")}),i.jsx("p",{className:"text-sm mb-4",children:a("settings.apiKeysEmptyDescription")}),i.jsxs(Ce,{onClick:()=>se(!0),children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.createFirstKey")]})]})})}),i.jsxs(vt,{className:"mt-6",children:[i.jsx(In,{children:i.jsx("h3",{className:"text-base font-semibold text-white",children:a("settings.webhookEndpoints")})}),i.jsxs(_t,{className:"space-y-3 text-sm",children:[i.jsx("p",{className:"text-bambu-gray",children:a("settings.webhookApiKeyHint")}),i.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-blue-400",children:"GET"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.getAllStatus")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-blue-400",children:"GET"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.getSpecificStatus")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-green-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.addToQueue")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-orange-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.pausePrint")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-orange-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.resumePrint")]})]}),i.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[i.jsx("span",{className:"text-red-400",children:"POST"})," ",i.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),i.jsxs("span",{className:"text-bambu-gray",children:[" - ",a("settings.webhook.stopPrint")]})]})]})]})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"mb-6",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Mh,{className:"w-5 h-5 text-bambu-green"}),a("settings.apiBrowser")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.apiBrowserDescription")})]}),i.jsx(vt,{className:"mb-4",children:i.jsxs(_t,{className:"py-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:a("settings.apiKeyForTesting")}),i.jsx("input",{type:"text",value:pe,onChange:ce=>Q(ce.target.value),placeholder:a("settings.apiKeyPlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm focus:border-bambu-green focus:outline-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:a("settings.apiKeyHint")})]})}),i.jsx(wZe,{apiKey:pe})]})]}),me==="virtual-printer"&&i.jsx(hZe,{}),me==="filament"&&C&&i.jsx(i.Fragment,{children:i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[i.jsxs("div",{className:"lg:w-1/3 space-y-6",children:[i.jsx(iZe,{}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.amsDisplayThresholds")})}),i.jsxs(_t,{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.amsThresholdsDescription")}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(wF,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"font-medium",children:a("settings.humidity")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.goodGreen")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_good??40,onChange:ce=>Bt("ams_humidity_good",parseInt(ce.target.value)||40),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"}),i.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.fairOrange")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_fair??60,onChange:ce=>Bt("ams_humidity_fair",parseInt(ce.target.value)||60),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"}),i.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.aboveFairBad")})]}),i.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(XC,{className:"w-4 h-4 text-orange-400"}),i.jsx("span",{className:"font-medium",children:a("settings.temperature")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.goodBlue")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_good??28,onChange:ce=>Bt("ams_temp_good",parseFloat(ce.target.value)||28),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"}),i.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("settings.fairOrange")," ≤"]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_fair??35,onChange:ce=>Bt("ams_temp_fair",parseFloat(ce.target.value)||35),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"}),i.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.aboveFairHot")})]}),i.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(Pc,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"font-medium",children:a("settings.historyRetention")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("settings.keepSensorHistory")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",min:"1",max:"365",value:C.ams_history_retention_days??30,onChange:ce=>Bt("ams_history_retention_days",parseInt(ce.target.value)||30),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),i.jsx("span",{className:"text-bambu-gray",children:a("common.days")})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:a("settings.historyRetentionDescription")})]}),i.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-white",children:[i.jsx(xr,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"font-medium",children:a("settings.printModal")})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-white",children:a("settings.expandCustomMapping")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:a("settings.expandCustomMappingDescription")})]}),i.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:C.per_printer_mapping_expanded??!1,onChange:ce=>Bt("per_printer_mapping_expanded",ce.target.checked),className:"sr-only peer"}),i.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"})]})]})]})]})]})]}),i.jsxs("div",{className:"lg:w-2/3 space-y-6",children:[i.jsx(sZe,{}),i.jsx(oZe,{})]})]})}),le!==null&&i.jsx(gn,{title:a("settings.deleteApiKeyTitle"),message:a("settings.deleteApiKeyMessage"),confirmText:a("settings.deleteKey"),variant:"danger",onConfirm:()=>{Zt.mutate(le),Fe(null)},onCancel:()=>Fe(null)}),P&&i.jsx(XQe,{plug:B,onClose:()=>{E(!1),O(null)}}),U&&i.jsx(ZQe,{provider:V,onClose:()=>{R(!1),G(null)}}),z&&i.jsx(JQe,{template:z,onClose:()=>K(null)}),Y&&i.jsx(nZe,{onClose:()=>ae(!1)}),L&&i.jsx(gn,{title:a("settings.clearNotificationLogs"),message:a("settings.clearLogsMessage"),confirmText:a("settings.clearLogs"),variant:"warning",onConfirm:async()=>{D(!1);try{const ce=await ne.clearNotificationLogs(30);o(ce.message,"success")}catch{o(a("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>D(!1)}),H&&i.jsx(gn,{title:a("settings.resetUiPreferences"),message:a("settings.resetUiPreferencesMessage"),confirmText:a("settings.resetPreferences"),variant:"default",onConfirm:()=>{he(!1),localStorage.clear(),o(a("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>he(!1)}),be&&i.jsx(gn,{title:`Turn All Plugs ${be==="on"?"On":"Off"}`,message:`This will turn ${be==="on"?"ON":"OFF"} all ${Ne?.filter(ce=>ce.enabled).length||0} enabled smart plugs. ${be==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${be==="on"?"On":"Off"}`,variant:be==="off"?"danger":"warning",onConfirm:()=>{const ce=be;fe(null),qa.mutate(ce)},onCancel:()=>fe(null)}),ze&&pn?.release_notes&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Ie(!1),children:i.jsxs(vt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ce=>ce.stopPropagation(),children:[i.jsxs(In,{className:"flex flex-row items-center justify-between shrink-0",children:[i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",pn.latest_version]}),pn.release_name&&pn.release_name!==pn.latest_version&&i.jsx("p",{className:"text-sm text-bambu-gray",children:pn.release_name})]}),i.jsx("button",{onClick:()=>Ie(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsx(_t,{className:"overflow-y-auto flex-1",children:i.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:pn.release_notes})}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[pn.release_url&&i.jsx("a",{href:pn.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:i.jsxs(Ce,{variant:"secondary",className:"w-full",children:[i.jsx(Kr,{className:"w-4 h-4"}),"View on GitHub"]})}),i.jsx(Ce,{onClick:()=>Ie(!1),className:"flex-1",children:"Close"})]})]})}),me==="users"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{className:"flex gap-1 border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>ue("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${je==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(hh,{className:"w-4 h-4"}),a("settings.tabs.users")]}),i.jsxs("button",{onClick:()=>ue("email"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${je==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[i.jsx(fv,{className:"w-4 h-4"}),a("settings.tabs.emailAuth")||"Email Authentication",Rt?.advanced_auth_enabled&&i.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]})]}),je==="users"&&i.jsxs(i.Fragment,{children:[i.jsx(vt,{children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?i.jsx(zm,{className:"w-5 h-5 text-green-400"}):i.jsx(I_,{className:"w-5 h-5 text-gray-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-white font-medium",children:a("settings.authentication")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:a(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&i.jsxs(Ce,{variant:"secondary",onClick:()=>tt(!0),children:[i.jsx(I_,{className:"w-4 h-4"}),a("common.disable")]}):i.jsxs(Ce,{onClick:()=>e("/setup"),children:[i.jsx(zm,{className:"w-4 h-4"}),a("common.enable")]})]})})}),Rt?.advanced_auth_enabled&&i.jsx(vt,{className:"border-blue-500/30 bg-blue-500/5",children:i.jsx(_t,{className:"py-4",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:i.jsx(fv,{className:"w-5 h-5 text-blue-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-white font-medium",children:a("settings.email.advancedAuthEnabled")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&i.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[i.jsxs("div",{className:"space-y-6",children:[c&&i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(hh,{className:"w-5 h-5 text-bambu-green"}),a("settings.currentUser")]}),i.jsxs(Ce,{size:"sm",variant:"ghost",onClick:()=>Se(!0),children:[i.jsx(nl,{className:"w-4 h-4"}),a("settings.changePassword")]})]})}),i.jsx(_t,{children:i.jsx("div",{className:"flex items-center justify-between",children:i.jsxs("div",{children:[i.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&i.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:a("settings.admin")}),c.groups?.map(ce=>i.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${ce.name==="Administrators"?"bg-purple-500/20 text-purple-300":ce.name==="Operators"?"bg-blue-500/20 text-blue-300":ce.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:ce.name},ce.id))]})]})})})]}),i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(hh,{className:"w-5 h-5 text-bambu-green"}),a("settings.users")]}),bn("users:create")&&i.jsxs(Ce,{size:"sm",onClick:()=>{Ge(!0),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addUser")]})]})}),i.jsx(_t,{children:Zn?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Nt.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8",children:a("settings.noUsersFound")}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Nt.map(ce=>i.jsxs("div",{className:"py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-white font-medium truncate",children:ce.username}),i.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[ce.is_admin&&i.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:a("settings.admin")}),ce.groups?.map(Et=>i.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${Et.name==="Administrators"?"bg-purple-500/20 text-purple-300":Et.name==="Operators"?"bg-blue-500/20 text-blue-300":Et.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:Et.name},Et.id))]})]}),i.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[bn("users:update")&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>rs(ce),children:i.jsx(Jm,{className:"w-4 h-4"})}),bn("users:delete")&&ce.id!==c?.id&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>Ss(ce.id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},ce.id))})})]})]}),i.jsx("div",{children:i.jsxs(vt,{children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(i3,{className:"w-5 h-5 text-bambu-green"}),a("settings.groups")]}),bn("groups:create")&&i.jsxs(Ce,{size:"sm",onClick:()=>e("/groups/new"),children:[i.jsx(Xn,{className:"w-4 h-4"}),a("settings.addGroup")]})]})}),i.jsx(_t,{children:hr?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):vr.length===0?i.jsx("p",{className:"text-center text-bambu-gray py-8",children:a("settings.noGroupsFound")}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:vr.map(ce=>i.jsxs("div",{className:"py-3",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(i3,{className:`w-4 h-4 ${ce.name==="Administrators"?"text-purple-400":ce.name==="Operators"?"text-blue-400":ce.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),i.jsx("span",{className:"text-white font-medium",children:ce.name}),ce.is_system&&i.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:a("settings.system")})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[bn("groups:update")&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>e(`/groups/${ce.id}/edit`),children:i.jsx(Jm,{className:"w-4 h-4"})}),bn("groups:delete")&&!ce.is_system&&i.jsx(Ce,{size:"sm",variant:"ghost",onClick:()=>yr(ce.id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:ce.description||a("settings.noDescription")}),i.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[i.jsx("span",{children:a("settings.userCount",{count:ce.user_count})}),i.jsx("span",{children:a("settings.permissionCount",{count:ce.permissions.length})})]})]},ce.id))})})]})})]}),!l&&i.jsx(vt,{children:i.jsx(_t,{className:"py-6",children:i.jsxs("div",{className:"text-center",children:[i.jsx(I_,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:a("settings.authDisabledTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:a("settings.authDisabledMessage")}),i.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature1")})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature2")})]}),i.jsxs("li",{className:"flex items-start gap-2",children:[i.jsx(pr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsx("span",{children:a("settings.authDisabledFeature3")})]})]}),i.jsxs(Ce,{onClick:()=>e("/setup"),children:[i.jsx(zm,{className:"w-4 h-4"}),a("settings.enableAuthentication")]})]})})})]}),je==="email"&&i.jsx("div",{className:"max-w-2xl",children:i.jsx(bZe,{})})]}),Te&&!Rt?.advanced_auth_enabled&&i.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(hh,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.createUser")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.username")}),i.jsx("input",{type:"text",value:wt.username,onChange:ce=>qt({...wt,username:ce.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:a("settings.enterUsername"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.password")}),i.jsx("input",{type:"password",value:wt.password,onChange:ce=>qt({...wt,password:ce.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:a("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.confirmPassword")}),i.jsx("input",{type:"password",value:wt.confirmPassword,onChange:ce=>qt({...wt,confirmPassword:ce.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${wt.confirmPassword&&wt.password!==wt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),wt.confirmPassword&&wt.password!==wt.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),i.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:[vr.map(ce=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:wt.group_ids.includes(ce.id),onChange:()=>si(ce.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:ce.name}),ce.is_system&&i.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},ce.id)),vr.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray",children:a("settings.noGroupsAvailable")})]})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),i.jsx(Ce,{onClick:ns,disabled:wa.isPending||!wt.username||!wt.password||wt.password!==wt.confirmPassword||wt.password.length<6,children:wa.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Xn,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),Te&&Rt?.advanced_auth_enabled&&i.jsx(aZe,{formData:wt,setFormData:qt,groups:vr,onClose:()=>{Ge(!1),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:ns,isCreating:wa.isPending,isCreateButtonDisabled:wa.isPending||!wt.username||!wt.email}),Re&&Ke!==null&&i.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Jm,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.editUser")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("settings.username")," ",Rt?.advanced_auth_enabled&&i.jsx("span",{className:"text-red-400",children:"*"})]}),i.jsx("input",{type:"text",value:wt.username,onChange:ce=>qt({...wt,username:ce.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:a("settings.enterUsername"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("users.form.email")||"Email"," ",Rt?.advanced_auth_enabled?i.jsx("span",{className:"text-red-400",children:"*"}):i.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("users.form.optional")||"optional",")"]})]}),i.jsx("input",{type:"email",value:wt.email,onChange:ce=>qt({...wt,email:ce.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:a("users.form.emailPlaceholder")||"user@example.com",required:Rt?.advanced_auth_enabled})]}),!Rt?.advanced_auth_enabled&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[a("users.form.password")||"Password"," ",i.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),i.jsx("input",{type:"password",value:wt.password,onChange:ce=>qt({...wt,password:ce.target.value,confirmPassword:""}),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:a("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),wt.password&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("settings.confirmPassword")}),i.jsx("input",{type:"password",value:wt.confirmPassword,onChange:ce=>qt({...wt,confirmPassword:ce.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${wt.confirmPassword&&wt.password!==wt.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),wt.confirmPassword&&wt.password!==wt.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]})]}),Rt?.advanced_auth_enabled&&i.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>Ke&&xn.mutate(Ke),disabled:xn.isPending||!wt.email,className:"w-full",children:xn.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("users.form.resettingPassword")||"Resetting Password..."]}):i.jsxs(i.Fragment,{children:[i.jsx(Fo,{className:"w-4 h-4"}),a("users.form.resetPassword")||"Reset Password"]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:a("users.form.groups")||"Groups"}),i.jsx("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:vr.map(ce=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:wt.group_ids.includes(ce.id),onChange:()=>si(ce.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),i.jsx("span",{className:"text-sm text-white",children:ce.name}),ce.is_system&&i.jsxs("span",{className:"text-xs text-yellow-400",children:["(",a("users.system")||"System",")"]})]},ce.id))})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{Le(!1),ft(null),qt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a("users.modal.cancel")||"Cancel"}),i.jsx(Ce,{onClick:()=>Tl(Ke),disabled:Va.isPending||!wt.username||Rt?.advanced_auth_enabled&&!wt.email||!!(!Rt?.advanced_auth_enabled&&wt.password&&(wt.password!==wt.confirmPassword||wt.password.length<6)),children:Va.isPending?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),a("users.modal.saving")||"Saving..."]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),a("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),kt!==null&&i.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{Lt(null),Mt(null)},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[i.jsx(Jt,{className:"w-5 h-5"}),i.jsx("h3",{className:"text-lg font-semibold",children:a("settings.deleteUserTitle")})]})}),i.jsx(_t,{className:"space-y-4",children:Ue?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):Kt&&Kt.archives+Kt.queue_items+Kt.library_files>0?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-white",children:a("settings.userHasCreated")}),i.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[Kt.archives>0&&i.jsxs("li",{children:[Kt.archives," archive",Kt.archives!==1?"s":""]}),Kt.queue_items>0&&i.jsxs("li",{children:[Kt.queue_items," queue item",Kt.queue_items!==1?"s":""]}),Kt.library_files>0&&i.jsxs("li",{children:[Kt.library_files," library file",Kt.library_files!==1?"s":""]})]}),i.jsx("p",{className:"text-bambu-gray text-sm",children:a("settings.userItemsQuestion")}),i.jsxs("div",{className:"flex flex-col gap-2",children:[i.jsx(Ce,{variant:"danger",onClick:()=>$t.mutate({id:kt,deleteItems:!0}),disabled:$t.isPending,className:"justify-center",children:"Delete user AND their items"}),i.jsx(Ce,{variant:"secondary",onClick:()=>$t.mutate({id:kt,deleteItems:!1}),disabled:$t.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),i.jsx(Ce,{variant:"ghost",onClick:()=>{Lt(null),Mt(null)},disabled:$t.isPending,className:"justify-center",children:"Cancel"})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-white",children:a("settings.deleteUserConfirm")}),i.jsx("p",{className:"text-bambu-gray text-sm",children:a("settings.actionCannotBeUndone")}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(Ce,{variant:"ghost",onClick:()=>{Lt(null),Mt(null)},disabled:$t.isPending,children:"Cancel"}),i.jsx(Ce,{variant:"danger",onClick:()=>$t.mutate({id:kt,deleteItems:!1}),disabled:$t.isPending,children:"Delete User"})]})]})})]})}),Cn!==null&&i.jsx(gn,{title:a("settings.deleteGroupTitle"),message:a("settings.deleteGroupMessage"),confirmText:a("settings.deleteGroup"),variant:"danger",onConfirm:()=>{Ci.mutate(Cn),yr(null)},onCancel:()=>yr(null)}),me==="backup"&&i.jsx(fZe,{}),qe&&i.jsx(gn,{title:a("settings.disableAuthenticationTitle"),message:a("settings.disableAuthenticationMessage"),confirmText:a("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ne.disableAuth(),o(a("settings.toast.authDisabled"),"success"),await u(),tt(!1),window.location.href="/"}catch(ce){const Et=ce instanceof Error?ce.message:a("settings.toast.authDisableFailed");o(Et,"error")}},onCancel:()=>tt(!1)}),Ee&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsxs(vt,{className:"w-full max-w-md",onClick:ce=>ce.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(nl,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("settings.changePassword")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsxs(_t,{children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),i.jsx("input",{type:"password",value:Me.currentPassword,onChange:ce=>xe({...Me,currentPassword:ce.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:a("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),i.jsx("input",{type:"password",value:Me.newPassword,onChange:ce=>xe({...Me,newPassword:ce.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:a("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),i.jsx("input",{type:"password",value:Me.confirmPassword,onChange:ce=>xe({...Me,confirmPassword:ce.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${Me.confirmPassword&&Me.newPassword!==Me.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:a("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Me.confirmPassword&&Me.newPassword!==Me.confirmPassword&&i.jsx("p",{className:"text-red-400 text-xs mt-1",children:a("settings.passwordsDoNotMatch")})]})]}),i.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>{Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),i.jsx(Ce,{onClick:async()=>{if(Me.newPassword!==Me.confirmPassword){o(a("settings.toast.passwordsDoNotMatch"),"error");return}if(Me.newPassword.length<6){o(a("settings.toast.passwordTooShort"),"error");return}He(!0);try{await ne.changePassword(Me.currentPassword,Me.newPassword),o(a("settings.toast.passwordChanged"),"success"),Se(!1),xe({currentPassword:"",newPassword:"",confirmPassword:""})}catch(ce){const Et=ce instanceof Error?ce.message:"Failed to change password";o(Et,"error")}finally{He(!1)}},disabled:ve||!Me.currentPassword||!Me.newPassword||Me.newPassword!==Me.confirmPassword||Me.newPassword.length<6,children:ve?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(nl,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const Rie=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},CZe=t=>t.startsWith("HH")?"HF":"S",kZe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},Fie=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const r of e)if(t.startsWith(r))return t.slice(r.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function Nj({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:a,onToggleSelect:s,note:o}){const l=CZe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&s?s():e()};return i.jsxs("div",{className:"flex items-center gap-2",children:[r&&i.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:a?i.jsx(so,{className:"w-4 h-4 text-bambu-green"}):i.jsx(vl,{className:"w-4 h-4"})}),i.jsxs("button",{onClick:u,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${a?"ring-1 ring-bambu-green":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:Rie(t.k_value)}),i.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&i.jsx("span",{title:"Has note",children:i.jsx(uX,{className:"w-3 h-3 text-yellow-500"})}),i.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&i.jsxs("div",{className:"text-xs mt-0.5 truncate text-yellow-500/70",title:o,children:["Note: ",o.length>50?o.substring(0,50)+"...":o]})]}),!r&&n&&i.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:i.jsx(Yl,{className:"w-4 h-4"})})]})}function Cj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],builtinFilaments:a=[],isDualNozzle:s=!1,initialNote:o="",initialNoteKey:l=null,onClose:c,onSave:u,onSaveNote:d,hasPermission:h}){const{t:f}=Ut(),{showToast:p}=cn(),[x,v]=w.useState(t?.name||""),[g,y]=w.useState(t?.k_value?Rie(t.k_value):"0.020"),[_,N]=w.useState(t?.filament_id||""),[k,A]=w.useState(t?.nozzle_id?kZe(t.nozzle_id):"HH00"),[M,C]=w.useState(t?.nozzle_diameter||n),[j,P]=w.useState(t?[t.extruder_id]:s?[0,1]:[0]),[E,B]=w.useState(!1),[O,U]=w.useState({current:0,total:0}),[R,V]=w.useState(o),G=Br.useMemo(()=>{const ee=new Map;for(const ye of a)ee.set(ye.filament_id,ye.name);const J=new Map;for(const ye of r)if(ye.filament_id&&!J.has(ye.filament_id)){const te=ee.get(ye.filament_id)||Fie(ye.name||"");J.set(ye.filament_id,{id:ye.filament_id,name:te||ye.filament_id})}return Array.from(J.values()).sort((ye,me)=>ye.name.localeCompare(me.name))},[r,a]),z=ot({mutationFn:ee=>(console.log("[KProfile] Calling API..."),ne.setKProfile(e,ee)),onSuccess:ee=>{if(console.log("[KProfile] Save success:",ee),p(f("kProfiles.toast.profileSaved")),d&&R!==o){let J;R===""&&l?J=l:t&&t.slot_id>0?J=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:J=`name_${x}_${_}`,d(J,R)}B(!0),setTimeout(()=>{B(!1),u()},2500)},onError:ee=>{console.error("[KProfile] Save error:",ee),p(ee.message,"error"),B(!1)}}),K=ot({mutationFn:ee=>(console.log("[KProfile] Deleting profile..."),ne.deleteKProfile(e,ee)),onSuccess:ee=>{console.log("[KProfile] Delete success:",ee),p(f("kProfiles.toast.profileDeleted")),B(!0),setTimeout(()=>{B(!1),c()},4e3)},onError:ee=>{console.error("[KProfile] Delete error:",ee),p(ee.message,"error"),B(!1)}}),[Y,ae]=w.useState(!1),$=()=>{t&&K.mutate({slot_id:t.slot_id,extruder_id:t.extruder_id,nozzle_id:t.nozzle_id,nozzle_diameter:t.nozzle_diameter,filament_id:t.filament_id,setting_id:t.setting_id})},W=async ee=>{if(ee.preventDefault(),s&&!t&&j.length===0){p(f("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const J=parseFloat(g).toFixed(6),ye=`${k}-${M}`;if(t||j.length===1){const te={name:x,k_value:J,filament_id:_,nozzle_id:ye,nozzle_diameter:M,extruder_id:t?t.extruder_id:j[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",te),z.mutate(te);return}B(!0),U({current:1,total:j.length});const me=j.map(te=>({name:x,k_value:J,filament_id:_,nozzle_id:ye,nozzle_diameter:M,extruder_id:te,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${me.length} profiles in batch:`,me);try{if(await ne.setKProfilesBatch(e,me),p(f("kProfiles.toast.profilesSaved",{count:j.length})),d&&R){const te=`name_${x}_${_}`;d(te,R)}}catch(te){console.error("[KProfile] Failed to save batch:",te),p(f("kProfiles.toast.failedToSaveBatch"),"error"),B(!1),U({current:0,total:0});return}U({current:j.length,total:j.length}),setTimeout(()=>{B(!1),U({current:0,total:0}),u()},3e3)};return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[i.jsxs(vt,{className:"w-full max-w-md relative",children:[E&&i.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),i.jsx("p",{className:"text-white font-medium",children:O.total>1?f("kProfiles.modal.savingExtruder",{current:O.current,total:O.total}):f("kProfiles.modal.syncing")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:f("kProfiles.modal.pleaseWait")})]}),i.jsxs(_t,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:f(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),i.jsx("button",{onClick:c,className:"text-bambu-gray hover:text-white transition-colors",disabled:E,children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:W,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.profileName")}),i.jsx("input",{type:"text",value:x,onChange:ee=>v(ee.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:f("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.kValue")}),i.jsx("input",{type:"text",inputMode:"decimal",value:g,onChange:ee=>{const J=ee.target.value;(J===""||/^\d*\.?\d*$/.test(J))&&y(J)},onBlur:ee=>{const J=parseFloat(ee.target.value);isNaN(J)||y((Math.trunc(J*1e3)/1e3).toFixed(3))},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 font-mono",placeholder:f("kProfiles.modal.kValuePlaceholder"),required:!0}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.kValueHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.filament")}),i.jsxs("select",{value:_,onChange:ee=>{const J=ee.target.value;if(N(J),!t&&J&&!x){const ye=G.find(me=>me.id===J);ye&&v(`${k==="HH00"?"HF":"S"} ${ye.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,required:!t,children:[i.jsx("option",{value:"",children:f("kProfiles.modal.selectFilament")}),t?.filament_id&&i.jsx("option",{value:t.filament_id,children:G.find(ee=>ee.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&G.map(ee=>i.jsx("option",{value:ee.id,children:ee.name},ee.id))]}),!t&&G.length===0&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.noFilamentsHelp")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.flowType")}),i.jsxs("select",{value:k,onChange:ee=>{const J=ee.target.value;if(A(J),!t&&_&&!x){const ye=G.find(me=>me.id===_);ye&&v(`${J==="HS00"?"HF":"S"} ${ye.name}`)}},disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[i.jsx("option",{value:"HH00",children:f("kProfiles.modal.highFlow")}),i.jsx("option",{value:"HS00",children:f("kProfiles.modal.standard")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.nozzleSize")}),i.jsxs("select",{value:M,onChange:ee=>C(ee.target.value),disabled:!!t,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 ${t?"opacity-60 cursor-not-allowed":""}`,children:[i.jsx("option",{value:"0.2",children:"0.2mm"}),i.jsx("option",{value:"0.4",children:"0.4mm"}),i.jsx("option",{value:"0.6",children:"0.6mm"}),i.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),s&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?i.jsx("div",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white opacity-60",children:t.extruder_id===1?f("kProfiles.modal.left"):f("kProfiles.modal.right")}):i.jsxs("div",{className:"flex gap-4",children:[i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:j.includes(1),onChange:ee=>{ee.target.checked?P([...j,1]):P(j.filter(J=>J!==1))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),i.jsx("span",{className:"text-white",children:f("kProfiles.modal.left")})]}),i.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:j.includes(0),onChange:ee=>{ee.target.checked?P([...j,0]):P(j.filter(J=>J!==0))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),i.jsx("span",{className:"text-white",children:f("kProfiles.modal.right")})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.notes")}),i.jsx("textarea",{value:R,onChange:ee=>V(ee.target.value),placeholder:f("kProfiles.modal.notesPlaceholder"),rows:2,className:"w-full px-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 resize-none"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.notesHelp")})]}),i.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>ae(!0),disabled:K.isPending||E||!h("kprofiles:delete"),title:h("kprofiles:delete")?void 0:f("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:K.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"})}),i.jsx(Ce,{type:"button",variant:"secondary",onClick:c,disabled:E,className:"flex-1",children:f("common.cancel")}),i.jsxs(Ce,{type:"submit",disabled:z.isPending||E||!h(t?"kprofiles:update":"kprofiles:create"),title:h(t?"kprofiles:update":"kprofiles:create")?void 0:f(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[z.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(BC,{className:"w-4 h-4"}),f("common.save")]})]})]})]})]}),Y&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:i.jsx(vt,{className:"w-full max-w-sm",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx(Jt,{className:"w-5 h-5 text-red-500"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:f("kProfiles.deleteConfirm.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:f("kProfiles.deleteConfirm.cannotUndo")})]})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:f("kProfiles.deleteConfirm.message",{name:t?.name})}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>ae(!1),className:"flex-1",children:f("common.cancel")}),i.jsxs(Ce,{onClick:()=>{ae(!1),$()},disabled:K.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[K.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),f("common.delete")]})]})]})})})]})}const F_={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function AZe(){const{t}=Ut(),{showToast:e}=cn(),{hasPermission:n}=Or(),[r,a]=w.useState(null),[s,o]=w.useState(()=>localStorage.getItem(F_.NOZZLE_DIAMETER)||"0.4"),[l,c]=w.useState(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,g]=w.useState("all"),[y,_]=w.useState("all"),[N,k]=w.useState(()=>localStorage.getItem(F_.SORT_OPTION)||"name"),[A,M]=w.useState(!1),[C,j]=w.useState(new Set),[P,E]=w.useState(!1),[B,O]=w.useState(!1),U=w.useCallback(D=>`${D.slot_id}_${D.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(F_.NOZZLE_DIAMETER,s)},[s]),w.useEffect(()=>{localStorage.setItem(F_.SORT_OPTION,N)},[N]);const{data:R,isLoading:V}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:G,isLoading:z,isFetching:K,error:Y,refetch:ae}=Je({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const D=await ne.getKProfiles(r,s);return console.log("[KProfiles] Received profiles:",D?.profiles?.length||0,"profiles"),D},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:$}=Je({queryKey:["kprofiles",r,"0.4"],queryFn:()=>ne.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:W}=Je({queryKey:["builtinFilaments"],queryFn:()=>ne.getBuiltinFilaments(),staleTime:3e5}),{data:ee}=Je({queryKey:["filamentIdMap"],queryFn:()=>ne.getFilamentIdMap(),staleTime:3e5}),{data:J,refetch:ye}=Je({queryKey:["kprofile-notes",r],queryFn:()=>ne.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),me=Y?.message?.includes("not connected");w.useEffect(()=>{if(!r&&R&&R.length>0){const D=R.find(H=>H.is_active);D&&a(D.id)}},[r,R]),w.useEffect(()=>{if(r){const D=setTimeout(()=>{ae()},150);return()=>clearTimeout(D)}},[r,s]);const te=R?.filter(D=>D.is_active)||[],je=Br.useMemo(()=>{const D=new Map;if(W)for(const H of W)D.set(H.filament_id,H.name);if(ee)for(const[H,he]of Object.entries(ee))D.has(H)||D.set(H,he);return D},[W,ee]),ue=Br.useMemo(()=>Array.from(je.entries()).map(([D,H])=>({filament_id:D,name:H})),[je]),oe=Br.useCallback(D=>je.get(D.filament_id)||Fie(D.name),[je]),_e=Br.useMemo(()=>G?.profiles?G.profiles.filter(H=>{const he=p.toLowerCase(),be=!he||H.name.toLowerCase().includes(he)||H.filament_id.toLowerCase().includes(he),fe=v==="all"||v==="left"&&H.extruder_id===1||v==="right"&&H.extruder_id===0,ze=y==="all"||y==="hf"&&H.nozzle_id.startsWith("HH")||y==="s"&&H.nozzle_id.startsWith("HS");return be&&fe&&ze}).sort((H,he)=>{switch(N){case"k_value":return parseFloat(H.k_value)-parseFloat(he.k_value);case"filament":return oe(H).localeCompare(oe(he));default:return H.name.localeCompare(he.name)}}):[],[G?.profiles,p,v,y,N,oe]),se=R?.find(D=>D.id===r),Oe=se?.nozzle_count===2;w.useEffect(()=>{const D=H=>{H.target instanceof HTMLInputElement||H.target instanceof HTMLTextAreaElement||H.target instanceof HTMLSelectElement||l||u||h||(H.key==="r"||H.key==="R"?(H.preventDefault(),ae()):H.key==="n"||H.key==="N"?(H.preventDefault(),d(!0)):H.key==="Escape"&&A&&(H.preventDefault(),M(!1),j(new Set)))};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[l,u,h,A,ae]);const q=w.useCallback(()=>{if(!G?.profiles||G.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const D={version:1,exported_at:new Date().toISOString(),printer:se?.name||"Unknown",nozzle_diameter:s,profiles:G.profiles.map(fe=>({name:fe.name,k_value:fe.k_value,filament_id:fe.filament_id,nozzle_id:fe.nozzle_id,nozzle_diameter:fe.nozzle_diameter,extruder_id:fe.extruder_id}))},H=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),he=URL.createObjectURL(H),be=document.createElement("a");be.href=he,be.download=`kprofiles_${se?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(be),be.click(),document.body.removeChild(be),URL.revokeObjectURL(he),e(t("kProfiles.toast.exportedProfiles",{count:G.profiles.length}))},[G?.profiles,se,s,e,t]),X=w.useCallback(()=>{const D=document.createElement("input");D.type="file",D.accept=".json",D.onchange=async H=>{const he=H.target.files?.[0];if(he)try{const be=await he.text(),fe=JSON.parse(be);if(!fe.profiles||!Array.isArray(fe.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let ze=0;for(const Ie of fe.profiles)if(!(!Ie.name||!Ie.k_value||!Ie.filament_id))try{await ne.setKProfile(r,{name:Ie.name,k_value:parseFloat(Ie.k_value).toFixed(6),filament_id:Ie.filament_id,nozzle_id:Ie.nozzle_id||`HH00-${s}`,nozzle_diameter:Ie.nozzle_diameter||s,extruder_id:Ie.extruder_id??0,slot_id:0}),ze++,await new Promise(qe=>setTimeout(qe,500))}catch(qe){console.error("Failed to import profile:",Ie.name,qe)}e(t("kProfiles.toast.importedProfiles",{count:ze,total:fe.profiles.length})),ae()}catch(be){console.error("Import error:",be),e(t("kProfiles.toast.failedToParseImport"),"error")}},D.click()},[r,s,e,ae,t]),de=w.useCallback(D=>{j(H=>{const he=new Set(H);return he.has(D)?he.delete(D):he.add(D),he})},[]),Z=w.useCallback(()=>{j(new Set(_e.map(D=>U(D))))},[_e,U]),ie=w.useCallback(()=>{C.size!==0&&E(!0)},[C.size]),le=w.useCallback(async()=>{const D=_e.filter(he=>C.has(U(he)));O(!0);let H=0;for(const he of D)try{await ne.deleteKProfile(r,{slot_id:he.slot_id,extruder_id:he.extruder_id,nozzle_id:he.nozzle_id,nozzle_diameter:he.nozzle_diameter,filament_id:he.filament_id,setting_id:he.setting_id}),H++,await new Promise(be=>setTimeout(be,300))}catch(be){console.error("Failed to delete profile:",he.name,be)}e(t("kProfiles.toast.profilesDeleted",{count:H})),O(!1),E(!1),M(!1),j(new Set),ae()},[r,C,_e,e,ae,U,t]),Fe=w.useCallback(D=>{const H=[];return D.setting_id&&H.push(D.setting_id),H.push(`slot_${D.slot_id}_${D.filament_id}_${D.extruder_id}`),H.push(`name_${D.name}_${D.filament_id}`),H},[]),pe=w.useCallback(async(D,H)=>{if(r)try{await ne.setKProfileNote(r,D,H),ye()}catch(he){console.error("Failed to save note:",he),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,ye,e,t]),Q=w.useCallback(D=>{if(!J?.notes)return{note:"",key:null};const H=Fe(D);for(const he of H)if(J.notes[he])return{note:J.notes[he],key:he};return{note:"",key:null}},[J,Fe]),L=w.useCallback(D=>Q(D).note,[Q]);return V?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!R||R.length===0?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(Ba,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):te.length===0?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(xr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):i.jsxs(i.Fragment,{children:[K&&!z&&i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[i.jsx(it,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),i.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),i.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[i.jsxs("div",{className:"flex-1 min-w-48",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),i.jsx("select",{value:r||"",onChange:D=>a(parseInt(D.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:te.map(D=>i.jsx("option",{value:D.id,children:D.name},D.id))})]}),i.jsxs("div",{className:"w-32",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),i.jsxs("select",{value:s,onChange:D=>o(D.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:[i.jsx("option",{value:"0.2",children:"0.2mm"}),i.jsx("option",{value:"0.4",children:"0.4mm"}),i.jsx("option",{value:"0.6",children:"0.6mm"}),i.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),i.jsxs("div",{className:"flex items-end gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:()=>ae(),disabled:K||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[i.jsx(Cr,{className:`w-4 h-4 ${K?"animate-spin":""}`}),t("kProfiles.refresh")]}),i.jsxs(Ce,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[i.jsx(Xn,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),i.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[i.jsxs("div",{className:"flex-1 min-w-48 relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:p,onChange:D=>x(D.target.value),placeholder:t("kProfiles.searchPlaceholder"),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"})]}),Oe&&i.jsx("div",{className:"w-36",children:i.jsxs("select",{value:v,onChange:D=>g(D.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:[i.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),i.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),i.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),i.jsx("div",{className:"w-32",children:i.jsxs("select",{value:y,onChange:D=>_(D.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:[i.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),i.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),i.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),i.jsx("div",{className:"w-32",children:i.jsxs("select",{value:N,onChange:D=>k(D.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:[i.jsx("option",{value:"name",children:t("kProfiles.sortName")}),i.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),i.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[i.jsxs(Ce,{variant:"secondary",onClick:q,disabled:!G?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[i.jsx(ua,{className:"w-4 h-4"}),t("kProfiles.export")]}),i.jsxs(Ce,{variant:"secondary",onClick:X,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[i.jsx(Ra,{className:"w-4 h-4"}),t("kProfiles.import")]}),i.jsx("div",{className:"flex-1"}),A?i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",onClick:Z,children:[i.jsx(so,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),i.jsxs(Ce,{variant:"secondary",onClick:ie,disabled:C.size===0||!n("kprofiles:delete"),className:"text-red-500 hover:bg-red-500/10",title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[i.jsx(Jt,{className:"w-4 h-4"}),t("kProfiles.delete")," (",C.size,")"]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>{M(!1),j(new Set)},children:[i.jsx(Ft,{className:"w-4 h-4"}),t("common.cancel")]})]}):i.jsxs(Ce,{variant:"secondary",onClick:()=>M(!0),disabled:!_e.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[i.jsx(so,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),z?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):me?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(Pf,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),i.jsxs(Ce,{variant:"secondary",onClick:()=>ae(),children:[i.jsx(Cr,{className:"w-4 h-4"}),t("common.refresh")]})]})}):_e.length>0?Oe?i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),i.jsx("div",{className:"space-y-1",children:_e.filter(D=>D.extruder_id===1).map(D=>i.jsx(Nj,{profile:D,onEdit:()=>c(D),onCopy:()=>f(D),selectionMode:A,isSelected:C.has(U(D)),onToggleSelect:()=>de(U(D)),note:L(D)},U(D)))})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),i.jsx("div",{className:"space-y-1",children:_e.filter(D=>D.extruder_id===0).map(D=>i.jsx(Nj,{profile:D,onEdit:()=>c(D),onCopy:()=>f(D),selectionMode:A,isSelected:C.has(U(D)),onToggleSelect:()=>de(U(D)),note:L(D)},U(D)))})]})]}):i.jsx("div",{className:"space-y-1",children:_e.map(D=>i.jsx(Nj,{profile:D,onEdit:()=>c(D),onCopy:()=>f(D),selectionMode:A,isSelected:C.has(U(D)),onToggleSelect:()=>de(U(D)),note:L(D)},U(D)))}):p||v!=="all"||y!=="all"?i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(kr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),i.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):i.jsx(vt,{children:i.jsxs(_t,{className:"py-12 text-center",children:[i.jsx(BC,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),i.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),i.jsxs(Ce,{onClick:()=>d(!0),children:[i.jsx(Xn,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:D,key:H}=Q(l);return i.jsx(Cj,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:$?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Oe,initialNote:D,initialNoteKey:H,onSaveNote:pe,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),ae()},onSave:()=>{c(null),ae()}})})(),u&&r&&i.jsx(Cj,{printerId:r,nozzleDiameter:s,existingProfiles:$?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Oe,onSaveNote:pe,hasPermission:n,onClose:()=>{d(!1),ae()},onSave:()=>{d(!1),ae()}}),h&&r&&i.jsx(Cj,{printerId:r,nozzleDiameter:s,existingProfiles:$?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Oe,onSaveNote:pe,hasPermission:n,profile:{...h,slot_id:0,name:`${h.name} (Copy)`},onClose:()=>{f(null),ae()},onSave:()=>{f(null),ae()}}),P&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-sm",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:i.jsx(Jt,{className:"w-5 h-5 text-red-500"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),i.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:C.size})}),i.jsxs("div",{className:"flex gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>E(!1),disabled:B,className:"flex-1",children:t("common.cancel")}),i.jsxs(Ce,{onClick:le,disabled:B,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[B?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const Lie=["PLA","PETG","PCTG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],TZe={PLA:"E8E8E8",PETG:"4A90D9",ABS:"E67E22",ASA:"D35400",TPU:"9B59B6",PC:"BDC3C7",PA:"2ECC71",NYLON:"2ECC71",PVA:"F1C40F",HIPS:"95A5A6",PP:"ECF0F1",PET:"3498DB"};function MZe(t){const e=t.toUpperCase();for(const n of Lie)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function PZe(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of Lie){const a=n.indexOf(r);if(a>0){const s=e.slice(0,a).trim();if(s&&s.length>1)return s}}return null}function kj({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:a}=Ut(),{hasPermission:s}=Or(),o=t.filament_type||MZe(t.name),l=t.filament_vendor||PZe(t.name);let c=null,u=!1;if(t.default_filament_colour)try{const d=JSON.parse(t.default_filament_colour),h=Array.isArray(d)?d[0]:d;typeof h=="string"&&/^#?[0-9a-fA-F]{6,8}$/.test(h.replace("#",""))&&(c=h.replace("#","").slice(0,6),u=!0)}catch{const d=t.default_filament_colour;/^#?[0-9a-fA-F]{6,8}$/.test(d.replace("#",""))&&(c=d.replace("#","").slice(0,6),u=!0)}return!c&&o&&(c=TZe[o.toUpperCase()]||null),i.jsx(vt,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:i.jsxs(_t,{className:"p-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&i.jsx("div",{className:`w-4 h-4 rounded-full border border-white/20 flex-shrink-0 ${!u&&!c?"opacity-25":u?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),i.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&i.jsx("span",{className:"text-xs text-bambu-gray",children:l}),i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:a("profiles.localProfiles.badge")})]})]}),i.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&i.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:a("profiles.localProfiles.delete"),children:i.jsx(Jt,{className:"w-3.5 h-3.5"})}),i.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?i.jsx(yl,{className:"w-3.5 h-3.5"}):i.jsx(Un,{className:"w-3.5 h-3.5"})})]})]}),r&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.filamentType")}),i.jsx("span",{className:"text-white",children:o})]}),l&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.vendor")}),i.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.nozzleTemp")}),i.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.cost")}),i.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.density")}),i.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.pressureAdvance")}),i.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.compatiblePrinters")}),i.jsx("span",{className:"text-white truncate ml-2",children:(()=>{try{return JSON.parse(t.compatible_printers).join(", ")}catch{return t.compatible_printers}})()})]}),t.inherits&&t.inherits!==t.name&&i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.inheritsFrom")}),i.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-bambu-gray",children:a("profiles.localProfiles.source")}),i.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function EZe(){const{t}=Ut(),{hasPermission:e}=Or(),n=tn(),{showToast:r}=cn(),[a,s]=w.useState(""),[o,l]=w.useState(null),[c,u]=w.useState(!1),[d,h]=w.useState(null),{data:f,isLoading:p}=Je({queryKey:["localPresets"],queryFn:()=>ne.getLocalPresets()}),x=ot({mutationFn:async C=>{const j=[];for(const P of Array.from(C)){const E=new FormData;E.append("file",P),j.push(await ne.importLocalPresets(E))}return j},onSuccess:C=>{n.invalidateQueries({queryKey:["localPresets"]});let j=0,P=0,E=0;for(const B of C)j+=B.imported,P+=B.skipped,E+=B.errors.length;j>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:j})),P>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:P}),"warning"),E>0&&r(t("profiles.localProfiles.toast.importError",{count:E}),"error")},onError:C=>{r(C.message,"error")}}),v=ot({mutationFn:C=>ne.deleteLocalPreset(C),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),h(null),r(t("profiles.localProfiles.toast.deleted"))}}),g=w.useCallback(C=>{!C||C.length===0||x.mutate(C)},[x]),y=w.useCallback(C=>{C.preventDefault(),u(!1),g(C.dataTransfer.files)},[g]),_=w.useCallback(C=>{if(!a)return C;const j=a.toLowerCase();return C.filter(P=>P.name.toLowerCase().includes(j)||P.filament_type?.toLowerCase().includes(j)||P.filament_vendor?.toLowerCase().includes(j))},[a]),N=w.useMemo(()=>_(f?.filament||[]),[f?.filament,_]),k=w.useMemo(()=>_(f?.printer||[]),[f?.printer,_]),A=w.useMemo(()=>_(f?.process||[]),[f?.process,_]),M=N.length+k.length+A.length;return p?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&i.jsxs("div",{onDragOver:C=>{C.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:y,className:`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[i.jsx("input",{type:"file",accept:".json,.zip,.orca_filament,.bbscfg,.bbsflmt",multiple:!0,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",onChange:C=>g(C.target.files)}),x.isPending?i.jsxs("div",{className:"flex items-center justify-center gap-2",children:[i.jsx(it,{className:"w-5 h-5 text-bambu-green animate-spin"}),i.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),M>0&&i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:a,onChange:C=>s(C.target.value),placeholder:t("profiles.localProfiles.search"),className:"w-full pl-9 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),M===0&&!p&&i.jsxs("div",{className:"text-center py-12",children:[i.jsx(Ub,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),i.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),M>0&&i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[N.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(IC,{className:"w-4 h-4 text-bambu-green"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:N.map(C=>i.jsx(kj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),A.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(mi,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",A.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:A.map(C=>i.jsx(kj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),k.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(ed,{className:"w-4 h-4 text-orange-400"}),i.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",k.length,")"]})]}),i.jsx("div",{className:"space-y-2",children:k.map(C=>i.jsx(kj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]})]}),d!==null&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[i.jsx(Ba,{className:"w-5 h-5 text-red-400"}),i.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",size:"sm",onClick:()=>h(null),children:t("profiles.localProfiles.cancel")}),i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>v.mutate(d),disabled:v.isPending,children:[v.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function s4(t,e){const n=`${t} ${e||""}`,r=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),a=r?r[1].trim():null,s=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=s?(s[1]||s[2])+"mm":null,l=n.match(/(\d+\.?\d*)mm\s*(?:Standard|Fine|Extra Fine|Draft|Quality)?/i),c=l?l[1]+"mm":null,u=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),d=u?u[1].toUpperCase():null;return{printer:a,nozzle:o,layerHeight:c,filamentType:d}}function r0(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function jZe({onSuccess:t,t:e}){const{showToast:n}=cn(),[r,a]=w.useState("email"),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),[p,x]=w.useState("global"),[v,g]=w.useState(null),[y,_]=w.useState(null),N=ot({mutationFn:()=>ne.cloudLogin(s,l,p),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):j.needs_verification?(g(j.verification_type||"email"),_(j.tfa_key||null),j.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),a("code")):n(j.message,"error")},onError:j=>n(j.message,"error")}),k=ot({mutationFn:()=>ne.cloudVerify(s,u,y||void 0),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):n(j.message,"error")},onError:j=>n(j.message,"error")}),A=ot({mutationFn:()=>ne.cloudSetToken(h),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:j=>n(j.message,"error")}),M=j=>{j.preventDefault(),r==="email"?N.mutate():r==="code"?k.mutate():r==="token"&&A.mutate()},C=N.isPending||k.isPending||A.isPending;return i.jsx(vt,{className:"max-w-md mx-auto",children:i.jsxs(_t,{children:[i.jsxs("div",{className:"text-center mb-6",children:[i.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:i.jsx(zb,{className:"w-6 h-6 text-bambu-green"})}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),i.jsxs("form",{onSubmit:M,className:"space-y-4",children:[r==="email"&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),i.jsx("input",{type:"email",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"your@email.com",required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),i.jsx("input",{type:"password",value:l,onChange:j=>c(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"••••••••",required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),i.jsxs("select",{value:p,onChange:j=>x(j.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:[i.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),i.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(v==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:v==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),i.jsx("input",{type:"text",value:u,onChange:j=>d(j.target.value.replace(/\D/g,"").slice(0,6)),className:"w-full px-3 py-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:border-bambu-green focus:outline-none",placeholder:"000000",maxLength:6,required:!0})]}),r==="token"&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),i.jsx("textarea",{value:h,onChange:j=>f(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none resize-none",placeholder:"eyJ...",rows:4,required:!0})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[r==="code"&&i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>a("email"),className:"flex-1",children:e("profiles.login.back")}),i.jsxs(Ce,{type:"submit",disabled:C,className:"flex-1",children:[C?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(EB,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&i.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("button",{type:"button",onClick:()=>a("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[i.jsx(nl,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&i.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("button",{type:"button",onClick:()=>a("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[i.jsx(EB,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function Ag({label:t,value:e,options:n,onChange:r}){const[a,s]=w.useState(!1),o=n.find(l=>l.value===e);return i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>s(!a),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white hover:border-bambu-gray-dark transition-colors",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),i.jsx("span",{children:o?.label||"All"}),i.jsx(Un,{className:`w-4 h-4 text-bambu-gray transition-transform ${a?"rotate-180":""}`})]}),a&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),i.jsx("div",{className:"absolute top-full left-0 mt-1 min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 py-1 max-h-60 overflow-y-auto",children:n.map(l=>i.jsxs("button",{onClick:()=>{r(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center justify-between hover:bg-bambu-dark-tertiary transition-colors ${e===l.value?"text-bambu-green":"text-white"}`,children:[i.jsx("span",{children:l.label}),l.count!==void 0&&i.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function DZe(){const[t,e]=w.useState(!1);w.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?i.jsx("button",{onClick:n,className:"fixed bottom-6 right-6 p-3 bg-bambu-green hover:bg-bambu-green-light text-white rounded-full shadow-lg shadow-bambu-green/25 transition-all z-40","aria-label":"Scroll to top",children:i.jsx(Af,{className:"w-5 h-5"})}):null}function Aj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:a,compareIndex:s,compareDisabled:o,t:l}){const c=s4(t.name),u=r0(t.setting_id);return i.jsxs("div",{className:"flex items-center gap-2 group",children:[i.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${a?"bg-blue-500/20 border border-blue-500/50":o?"bg-bambu-dark/50 opacity-40 cursor-not-allowed":"bg-bambu-dark hover:bg-bambu-dark-tertiary"} ${r&&!o?"cursor-pointer":""}`,children:i.jsxs("div",{className:"flex items-center gap-2",children:[a&&s!==void 0&&i.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-blue-500 text-white text-xs flex items-center justify-center font-medium",children:s+1}),!a&&u&&i.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),i.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),i.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:l("profiles.presets.duplicate"),children:i.jsx(Yl,{className:"w-4 h-4"})})]})}function eF(t,e=0){const n=" ".repeat(e);if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){if(t.includes("\\n")||t.includes(` `)){const a=t.replace(/\\n/g,` `).replace(/\\"/g,'"').replace(/\\t/g," ").split(` `);if(a.length>1)return`""" @@ -8681,6 +8681,6 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Qs(t. `+n+"]";if(typeof t=="object"){const r=Object.entries(t);return r.length===0?"{}":`{ `+r.map(([s,o])=>n+" "+JSON.stringify(s)+": "+eF(o,e+1)).join(`, `)+` -`+n+"}"}return String(t)}function RZe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=cn(),c=tn(),[u,d]=w.useState(!1),{data:h,isLoading:f}=Je({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ne.getCloudSettingDetail(t.setting_id)}),p=ot({mutationFn:()=>ne.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:g=>l(g.message,"error")}),x=r0(t.setting_id),v=s4(t.name,h?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),x&&i.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:eF(h)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(Tn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>d(!1),disabled:p.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(Ce,{variant:"danger",onClick:()=>p.mutate(),disabled:p.isPending,className:"flex-1",children:[p.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(Ce,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(Yl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",onClick:a,disabled:f||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx($a,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(Ce,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})})]})})})}function Oie(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Iie(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function FZe({onClose:t,onApply:e,t:n}){const{showToast:r}=cn(),[a,s]=w.useState(Oie),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,h]=w.useState(""),[f,p]=w.useState(""),[x,v]=w.useState("{}"),[g,y]=w.useState(null),[_,N]=w.useState(null),k=o==="all"?a:a.filter(U=>U.type===o),A=U=>{s(U),Iie(U)},M=U=>{const R=a.filter(V=>V.id!==U);A(R),N(null),r(n("profiles.templates.toast.deleted"))},C=U=>{u(U.id),h(U.name),p(U.description),v(JSON.stringify(U.settings,null,2)),y(null)},j=()=>{if(!(!c||!d.trim()))try{const U=JSON.parse(x),R=a.map(V=>V.id===c?{...V,name:d.trim(),description:f.trim(),settings:U}:V);A(R),u(null),r(n("profiles.templates.toast.updated"))}catch(U){y(U.message)}},P=()=>{u(null),h(""),p(""),v("{}"),y(null)},E=U=>{const R=a.map(V=>V.id===U?{...V,showInModal:!V.showInModal}:V);A(R)},B={filament:{label:n("profiles.presets.types.filament"),icon:IC,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:ed,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:xr,color:"text-purple-400"}},O=_?a.find(U=>U.id===_):null;return w.useEffect(()=>{const U=R=>{R.key==="Escape"&&(_?N(null):c?P():t())};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[O&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(vt,{className:"w-full max-w-md",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(Tn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:O.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(Ce,{onClick:()=>M(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(Jt,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(vt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(lb,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(U=>i.jsx("button",{onClick:()=>l(U),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:U==="all"?n("common.all"):B[U].label},U))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:k.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(lb,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:k.map(U=>{const R=B[U.type],V=R.icon;return c===U.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:G=>h(G.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:f,onChange:G=>p(G.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:x,onChange:G=>{v(G.target.value),y(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${g?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),g&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:g})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:j,disabled:!d.trim(),children:[i.jsx(ps,{className:"w-4 h-4"}),"Save"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:P,children:"Cancel"})]})]},U.id):i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[i.jsx(V,{className:`w-5 h-5 ${R.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:U.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:U.description})]}),i.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(U.settings).length})}),i.jsx("button",{onClick:()=>E(U.id),className:`p-1 transition-colors ${U.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:U.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:U.showInModal?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(o0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(U),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),i.jsx("button",{onClick:()=>C(U),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(U.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]},U.id)})})})]})})]})}function zie({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const x=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const g of x){if(g==="inherits"||g==="version")continue;const y=e[g],_=n[g],N=g in e,k=g in n;let A;!N&&k?A="added":N&&!k?A="removed":JSON.stringify(y)!==JSON.stringify(_)?A="changed":A="same",v.push({key:g,left:y,right:_,status:A})}return v.sort((g,y)=>{const _={changed:0,added:1,removed:2,same:3};return _[g.status]!==_[y.status]?_[g.status]-_[y.status]:g.key.localeCompare(y.key)})},[e,n]),h=w.useMemo(()=>{let x=[...d];if(o==="changes"&&(x=x.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();x=x.filter(g=>g.key.toLowerCase().includes(v)||String(g.left).toLowerCase().includes(v)||String(g.right).toLowerCase().includes(v))}return x},[d,o,c]),f=w.useMemo(()=>({added:d.filter(x=>x.status==="added").length,removed:d.filter(x=>x.status==="removed").length,changed:d.filter(x=>x.status==="changed").length,same:d.filter(x=>x.status==="same").length}),[d]),p=x=>{if(x===void 0)return"—";if(x===null)return"null";if(Array.isArray(x))return x.length===0?"[]":x.length===1?String(x[0]):x.join(", ");if(typeof x=="object")return JSON.stringify(x);const v=String(x);if(v.includes("\\n")||v.length>100){const g=v.split("\\n").length;if(g>1)return`[${g} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const x=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx($g,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(Xn,{className:"w-3.5 h-3.5"}),f.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(x1,{className:"w-3.5 h-3.5"}),f.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(Qj,{className:"w-3.5 h-3.5"}),f.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx(LM,{className:"w-3.5 h-3.5"}),f.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:x=>u(x.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),f.same>0&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),i.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:h.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(LM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:h.map(x=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[x.status],g={added:i.jsx(Xn,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(x1,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(Qj,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx(LM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[x.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[g,i.jsx("span",{className:"text-sm text-white font-mono",children:x.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="removed"?"text-red-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="added"?"text-green-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.right)})})]},x.key)})})]})})]})})})}function LZe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=cn(),s=tn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[h,f]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[p,x]=w.useState(e?.base_id||""),[v,g]=w.useState(""),[y,_]=w.useState(e?.setting||{inherits:""}),[N,k]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[A,M]=w.useState(null),[C,j]=w.useState(""),[P,E]=w.useState(!1),[B,O]=w.useState(""),[U,R]=w.useState(!1),[V,G]=w.useState(Oie),[z,K]=w.useState(!1),[Y,ae]=w.useState(""),[$,W]=w.useState(""),[ee,J]=w.useState(!0),[ye,me]=w.useState(null),[te,je]=w.useState(!1),ue=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),oe=w.useMemo(()=>ue.filter(Me=>r0(Me.setting_id)),[ue]),{data:_e}=Je({queryKey:["cloudFields",u],queryFn:()=>ne.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:se}=Je({queryKey:["allPresetDetails",u,oe.map(Me=>Me.setting_id).join(",")],queryFn:async()=>{const Me={};for(let ve=0;ve{try{const Te=await ne.getCloudSettingDetail(nt.setting_id);return{id:nt.setting_id,detail:Te}}catch{return null}}))).forEach(nt=>{nt&&(Me[nt.id]=nt.detail)})}return Me},enabled:oe.length>0,staleTime:1e3*60*10}),{data:Oe,isLoading:q}=Je({queryKey:["cloudSettingDetail",p],queryFn:()=>ne.getCloudSettingDetail(p),enabled:!!p});w.useEffect(()=>{l!=="json"&&k(JSON.stringify(y,null,2))},[y,l]);const X=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(xe=>!r0(xe.setting_id)).sort((xe,ve)=>xe.name.localeCompare(ve.name)),[n,u]);w.useEffect(()=>{if(!p)return;const Me=X.find(xe=>xe.setting_id===p);Me&&(g(Me.name),o||(_({inherits:Me.name}),k(JSON.stringify({inherits:Me.name},null,2))))},[p,X,o]);const de=w.useMemo(()=>{const Me=_e?.fields||[],xe=new Set(Me.map(nt=>nt.key)),ve=new Set,He=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);se&&Object.values(se).forEach(nt=>{nt?.setting&&Object.keys(nt.setting).forEach(Te=>{!xe.has(Te)&&!He.has(Te)&&ve.add(Te)})}),Object.keys(y).forEach(nt=>{!xe.has(nt)&&!He.has(nt)&&ve.add(nt)});const Pe=Array.from(ve).sort().map(nt=>({key:nt,label:nt.replace(/_/g," ").replace(/\b\w/g,Te=>Te.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Me,...Pe]},[_e,se,y,r]),Z=de.filter(Me=>Me.label.toLowerCase().includes(C.toLowerCase())||Me.key.toLowerCase().includes(C.toLowerCase())),ie=()=>{if(B.trim()){const Me=B.trim().toLowerCase().replace(/\s+/g,"_");le(Me,""),O(""),R(!1),a(r("profiles.presets.toast.fieldAdded",{key:Me}))}},le=(Me,xe)=>{_(ve=>{const He={...ve};return xe===""||xe===void 0?delete He[Me]:He[Me]=xe,He})},Fe=Me=>{_(xe=>({...xe,...Me.settings})),me(Me.name),a(r("profiles.templates.toast.applied"))},pe=()=>{if(!Y.trim())return;const Me={...y};if(delete Me.inherits,Object.keys(Me).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const xe={id:Date.now().toString(),name:Y.trim(),description:$.trim()||r("profiles.presets.customTemplate"),type:u,settings:Me,showInModal:ee},ve=[...V,xe];G(ve),Iie(ve),K(!1),ae(""),W(""),J(!0),a(r("profiles.templates.toast.created"))},Q=w.useMemo(()=>V.filter(Me=>Me.type===u&&Me.showInModal),[u,V]),L=Me=>{k(Me);try{const xe=JSON.parse(Me);_(xe),M(null)}catch(xe){M(xe.message)}},D=Me=>{Me.preventDefault(),E(!1);const xe=Me.dataTransfer.files[0];if(xe&&xe.name.endsWith(".json")){const ve=new FileReader;ve.onload=He=>{try{const Pe=He.target?.result,nt=JSON.parse(Pe),Te=nt.setting||nt;_(Ge=>({...Ge,...Te})),k(JSON.stringify({...y,...Te},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},ve.readAsText(xe)}},H=ot({mutationFn:()=>{const Me={...y},xe=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Me[xe]=`"${h}"`;const ve={type:u,name:h,base_id:p,setting:Me};return ne.createCloudSetting(ve)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>a(Me.message,"error")}),he=ot({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ne.updateCloudSetting(e.setting_id,{name:h,setting:y})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>a(Me.message,"error")}),be=o?he:H,fe=Oe?.setting?.inherits,ze=fe?X.find(Me=>Me.name===fe):void 0,{data:Ie}=Je({queryKey:["cloudSettingDetail",ze?.setting_id],queryFn:()=>ne.getCloudSettingDetail(ze.setting_id),enabled:!!ze?.setting_id}),qe=w.useMemo(()=>{const Me=Ie?.setting||{},xe=Oe?.setting||{},ve=p&&se?.[p]?.setting?se[p].setting:{};return{...Me,...xe,...ve}},[p,Oe,Ie,se]),tt=Me=>{if(Me==null)return"";if(Array.isArray(Me)){const xe=[...new Set(Me.map(ve=>String(ve)))];return xe.length===1?xe[0]:Me.join(", ")}return String(Me)},Ee=Me=>{const xe=y[Me.key],ve=qe[Me.key],He=tt(ve),Pe=q?r("common.loading"):He||"",nt="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Me.type==="boolean"){const Te=xe==="1"||xe===void 0&&ve==="1";return i.jsx("button",{type:"button",onClick:()=>le(Me.key,xe==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Te?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Te?"translate-x-3.5":"translate-x-0.5"}`})})}return Me.type==="select"?i.jsxs("select",{value:xe||"",onChange:Te=>le(Me.key,Te.target.value),className:nt,children:[i.jsx("option",{value:"",children:Pe}),Me.options?.map(Te=>i.jsx("option",{value:Te.value,children:Te.label},Te.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Me.type==="number"?"number":"text",value:xe!==void 0?String(xe):"",onChange:Te=>le(Me.key,Te.target.value),step:Me.step,min:Me.min,max:Me.max,placeholder:Pe,className:nt}),Me.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Me.unit})]})},Se=w.useMemo(()=>Oe?.setting?Oe.setting:{},[Oe]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Me=>{Me.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:D,children:[te&&p&&i.jsx(zie,{onClose:()=>je(!1),leftPreset:Se,rightPreset:y,leftLabel:r("profiles.presets.baseLabel",{name:v||p}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),i.jsx(vt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[p&&i.jsxs("button",{onClick:()=>je(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[i.jsx($g,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]})]}),P&&i.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Ra,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:Me=>{d(Me.target.value),x("")},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:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:p,onChange:Me=>x(Me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),X.map(Me=>i.jsx("option",{value:Me.setting_id,children:Me.name},Me.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:h,onChange:Me=>f(Me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(ra,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),q&&i.jsx(it,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(jB,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(HC,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(nX,{className:"w-4 h-4"}),"JSON",A&&i.jsx(Ba,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const Me={name:h,type:u,base_id:p,setting:y},xe=new Blob([JSON.stringify(Me,null,2)],{type:"application/json"}),ve=URL.createObjectURL(xe),He=document.createElement("a");He.href=ve,He.download=`${h||"preset"}.json`,document.body.appendChild(He),He.click(),document.body.removeChild(He),URL.revokeObjectURL(ve),a(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[i.jsx(ua,{className:"w-4 h-4"}),r("common.download")]}),i.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[i.jsx(Ra,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Me=>{const xe=Me.target.files?.[0];if(xe){const ve=new FileReader;ve.onload=He=>{try{const Pe=JSON.parse(He.target?.result),nt=Pe.setting||Pe;_(Te=>({...Te,...nt})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},ve.readAsText(xe)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(lb,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(y).filter(Me=>Me!=="inherits").length>0&&i.jsxs("button",{onClick:()=>K(!z),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(ps,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),z&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:Y,onChange:Me=>ae(Me.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:$,onChange:Me=>W(Me.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:pe,disabled:!Y.trim(),children:[i.jsx(ps,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>K(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>J(!ee),className:`flex items-center gap-1.5 text-xs transition-colors ${ee?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[ee?i.jsx(Ql,{className:"w-3.5 h-3.5"}):i.jsx(o0,{className:"w-3.5 h-3.5"}),r(ee?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),ye&&i.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[i.jsx(ra,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:ye})]}),i.jsx("button",{onClick:()=>me(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[Q.map(Me=>i.jsxs("button",{onClick:()=>Fe(Me),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Me.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Me.description})]},Me.id)),Q.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:de.slice(0,10).map(Me=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Me.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:Ee(Me)})]},Me.key))})]}),Object.keys(y).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([Me])=>Me!=="inherits").map(([Me,xe])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Me,": ",String(xe).slice(0,20),i.jsx("button",{onClick:()=>le(Me,void 0),className:"hover:text-white",children:i.jsx(Ft,{className:"w-3 h-3"})})]},Me))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:se?r("profiles.templates.fieldsCount",{count:de.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:C,onChange:Me=>j(Me.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Z.filter(Me=>!(Me.key in y)).map(Me=>{const xe=qe[Me.key],ve=tt(xe);return i.jsxs("div",{onClick:()=>{_(He=>({...He,[Me.key]:ve||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Me.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Me.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ve&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:ve,children:[ve.slice(0,20),ve.length>20?"...":""]}),i.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:i.jsx(Xn,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Me.key)}),Z.filter(Me=>!(Me.key in y)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(C?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:U?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:B,onChange:Me=>O(Me.target.value),onKeyDown:Me=>Me.key==="Enter"&&ie(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx(Ce,{size:"sm",onClick:ie,disabled:!B.trim(),children:i.jsx(Xn,{className:"w-4 h-4"})}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>{R(!1),O("")},children:i.jsx(Ft,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>R(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(Xn,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(y).filter(Me=>Me!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([Me])=>Me!=="inherits").map(([Me,xe])=>{const ve=de.find(He=>He.key===Me);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:ve?.label||Me}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Me})]}),i.jsx("button",{onClick:()=>le(Me,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),ve?Ee(ve):i.jsx("input",{type:"text",value:String(xe),onChange:He=>le(Me,He.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Me)}),Object.keys(y).filter(Me=>Me!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(jB,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(y).filter(Me=>Me!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{K(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(ps,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[A&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Ba,{className:"w-4 h-4"}),A]}),i.jsx("textarea",{value:N,onChange:Me=>L(Me.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${A?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(Ce,{onClick:()=>be.mutate(),disabled:be.isPending||!h.trim()||!o&&!p||!!A,className:"flex-1",children:[be.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o?i.jsx(ps,{className:"w-4 h-4"}):i.jsx(Xn,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function OZe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[h,f]=w.useState("all"),[p,x]=w.useState("all"),[v,g]=w.useState("all"),[y,_]=w.useState("all"),[N,k]=w.useState("all"),[A,M]=w.useState(null),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[B,O]=w.useState(null),[U,R]=w.useState(null),[V,G]=w.useState(null),[z,K]=w.useState(!1),[Y,ae]=w.useState([null,null]),[$,W]=w.useState(!1),[ee,J]=w.useState(null),ye=tn(),me=w.useMemo(()=>[...t.filament.map(ie=>({...ie,type:"filament"})),...t.printer.map(ie=>({...ie,type:"printer"})),...t.process.map(ie=>({...ie,type:"process"}))].map(ie=>({...ie,meta:s4(ie.name)})),[t]),te=w.useMemo(()=>{const Z=new Set,ie=new Set,le=new Set;return me.forEach(Fe=>{Fe.meta.nozzle&&Z.add(Fe.meta.nozzle),Fe.meta.filamentType&&ie.add(Fe.meta.filamentType),Fe.meta.layerHeight&&le.add(Fe.meta.layerHeight)}),{printers:a.map(Fe=>({id:Fe.id.toString(),name:Fe.name})),nozzles:Array.from(Z).sort((Fe,pe)=>parseFloat(Fe)-parseFloat(pe)),filaments:Array.from(ie).sort(),layerHeights:Array.from(le).sort((Fe,pe)=>parseFloat(Fe)-parseFloat(pe))}},[me,a]),je=w.useMemo(()=>p==="all"?null:a.find(ie=>ie.id.toString()===p)?.model||null,[p,a]),ue=w.useMemo(()=>me.filter(Z=>u==="all"||Z.type===u).filter(Z=>{if(h==="all")return!0;const ie=r0(Z.setting_id);return h==="custom"?ie:!ie}).filter(Z=>{if(p==="all"||!je)return!0;const ie=Z.meta.printer?.toLowerCase()||"",le=je.toLowerCase();return ie.includes(le)||le.includes(ie)}).filter(Z=>v==="all"||Z.meta.nozzle===v).filter(Z=>y==="all"||Z.meta.filamentType===y).filter(Z=>N==="all"||Z.meta.layerHeight===N).filter(Z=>l===""||Z.name.toLowerCase().includes(l.toLowerCase())).sort((Z,ie)=>Z.name.localeCompare(ie.name)),[me,u,h,p,je,v,y,N,l]),oe=Z=>{if(z){const ie=Y[0]?.setting_id===Z.setting_id,le=Y[1]?.setting_id===Z.setting_id;if(ie)ae([Y[1],null]);else if(le)ae([Y[0],null]);else if(!Y[0])ae([Z,null]);else if(Y[1]){if(Y[0].type!==Z.type)return;ae([Y[0],Z])}else{if(Y[0].type!==Z.type)return;ae([Y[0],Z])}}else M(Z)},_e=Z=>{if(Y[0]?.setting_id===Z.setting_id)return 0;if(Y[1]?.setting_id===Z.setting_id)return 1},se=async Z=>{try{const ie=await ne.getCloudSettingDetail(Z.setting_id),le=Z.type==="process"?"print":Z.type;O({type:le,name:Z.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{}}),M(null)}catch(ie){console.error("Failed to fetch preset details for duplication:",ie)}},Oe=async Z=>{try{ye.removeQueries({queryKey:["cloudSettingDetail",Z.setting_id]});const ie=await ne.getCloudSettingDetail(Z.setting_id),le=Z.type==="process"?"print":Z.type;R({type:le,name:Z.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{},setting_id:Z.setting_id}),M(null)}catch(ie){console.error("Failed to fetch preset details for editing:",ie)}},q=()=>{d("all"),f("all"),x("all"),g("all"),_("all"),k("all"),c("")},X=u!=="all"||h!=="all"||p!=="all"||v!=="all"||y!=="all"||N!=="all"||l!=="",de=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:Z=>c(Z.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(Ce,{variant:z?"primary":"secondary",onClick:()=>{z?(K(!1),ae([null,null])):K(!0)},children:[i.jsx($g,{className:"w-4 h-4"}),o(z?"common.cancel":"profiles.presets.compare")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(lb,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(Ce,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Cr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(Ce,{onClick:()=>j(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(UC,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(Ag,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:de},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:Z=>d(Z)}),i.jsx(Ag,{label:o("profiles.cloudView.filters.owner"),value:h,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:Z=>f(Z)}),te.printers.length>0&&i.jsx(Ag,{label:o("profiles.cloudView.filters.printer"),value:p,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.printers.map(Z=>({value:Z.id,label:Z.name}))],onChange:x}),te.nozzles.length>0&&i.jsx(Ag,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.nozzles.map(Z=>({value:Z,label:Z}))],onChange:g}),te.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(Ag,{label:o("profiles.cloudView.filters.filament"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.filaments.map(Z=>({value:Z,label:Z}))],onChange:_}),te.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(Ag,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.layerHeights.map(Z=>({value:Z,label:Z}))],onChange:k}),X&&i.jsx("button",{onClick:q,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),z&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx($g,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:Y[0]?o("profiles.cloudView.selectAnotherPreset",{type:Y[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[0]?Y[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(Qj,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[1]?Y[1].name:o("profiles.cloudView.selectSecond")})]}),Y[0]&&Y[1]&&i.jsxs(Ce,{size:"sm",onClick:async()=>{try{const[Z,ie]=await Promise.all([ne.getCloudSettingDetail(Y[0].setting_id),ne.getCloudSettingDetail(Y[1].setting_id)]);J([Z.setting||{},ie.setting||{}]),W(!0)}catch{}},children:[i.jsx($g,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Gn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",gv(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:ue.length,total:de})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),ue.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(mi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),X&&i.jsx("button",{onClick:q,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(IC,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="filament").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(ed,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="process").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(xr,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="printer").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),A&&i.jsx(RZe,{setting:A,onClose:()=>M(null),onDeleted:()=>M(null),onDuplicate:()=>se(A),onEdit:()=>Oe(A),hasPermission:s,t:o}),(C||B||U||V)&&i.jsx(LZe,{onClose:()=>{j(!1),O(null),R(null),G(null)},initialData:U||B||(V?{type:V.type,name:"",base_id:"",setting:V.setting}:void 0),allPresets:t,t:o}),P&&i.jsx(FZe,{onClose:()=>E(!1),onApply:Z=>{G({type:Z.type,setting:Z.settings}),E(!1)},t:o}),$&&ee&&Y[0]&&Y[1]&&i.jsx(zie,{onClose:()=>{W(!1),J(null)},leftPreset:ee[0],rightPreset:ee[1],leftLabel:Y[0].name,rightLabel:Y[1].name,t:o})]})}function IZe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=Je({queryKey:["cloudStatus"],queryFn:ne.getCloudStatus}),{data:d=[]}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:h,isLoading:f,refetch:p,dataUpdatedAt:x}=Je({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{x&&l(new Date(x))},[x]);const v=ot({mutationFn:ne.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),g=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(zb,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Ub,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(BC,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(r3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.jsx(OZe,{settings:h,lastSyncTime:o,onRefresh:()=>p(),isRefreshing:f,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(Ce,{onClick:()=>p(),children:t("profiles.retry")})]}):i.jsx(jZe,{onSuccess:g,t})]}),a==="local"&&i.jsx(EZe,{}),a==="kprofiles"&&i.jsx(AZe,{}),i.jsx(DZe,{})]})}const Oy={Droplet:IC,Flame:sme,Ruler:Ife,Sparkles:lb,Square:vl,Cable:$de,Wrench:Ef,Calendar:na,Timer:Lu,Cog:Mhe,Fan:rX,Zap:Vh,Wind:fX,Thermometer:XC,Layers:mi,Box:Ja,Target:dX,RefreshCw:Cr,Settings:KC,Filter:UC,CircleDot:uhe};function ov(t){return t&&Oy[t]||Ef}function Tg(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function Tj(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function zZe(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,h=n.includes("P2S");switch(t){case"Lubricate Carbon Rods":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":h?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a||h?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":u?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return d?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function UZe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=ov(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const p=t.days_since_maintenance??0;return Math.max(0,Math.min(100,p/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",h=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",f=()=>{if(!t.enabled)return a("common.disabled");if(o==="days"){const p=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Tg(Math.abs(p),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Tg(p,"days",a)}):a("maintenance.timeLeft",{duration:Tg(p,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Tg(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Tg(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Tg(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${h()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const p=t.maintenance_type_wiki_url||zZe(t.maintenance_type_name,t.printer_model);return p?i.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:x=>x.stopPropagation(),children:i.jsx(Kr,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(Tn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Gn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(ra,{className:"w-3 h-3"}),f()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(On,{checked:t.enabled,onChange:p=>n(t.id,p),disabled:!r("maintenance:update")})}),i.jsxs(Ce,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(Fo,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function BZe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.total_print_hours.toFixed(1)),f=[...t.maintenance_items].sort((v,g)=>v.is_due&&!g.is_due?-1:!v.is_due&&g.is_due?1:v.is_warning&&!g.is_warning?-1:!v.is_warning&&g.is_warning?1:v.maintenance_type_id-g.maintenance_type_id),p=f.find(v=>v.enabled&&(v.is_due||v.is_warning)),x=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(vt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Tn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Gn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(ra,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?i.jsx(yl,{className:"w-4 h-4"}):i.jsx(Un,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(Lu,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>h(v.target.value),onKeyDown:v=>{v.key==="Enter"&&x(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(Ce,{size:"sm",onClick:x,children:s("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(h(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(Tf,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),p&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=ov(p.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${p.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${p.is_due?"text-red-400":"text-amber-400"}`,children:p.maintenance_type_name}),i.jsx("div",{className:`text-xs ${p.is_due?"text-red-400/70":"text-amber-400/70"}`,children:p.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(_t,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:f.map(v=>i.jsx(UZe,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function HZe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:h}){const[f,p]=w.useState(null),[x,v]=w.useState(""),[g,y]=w.useState("hours"),[_,N]=w.useState(!1),[k,A]=w.useState(""),[M,C]=w.useState("100"),[j,P]=w.useState("hours"),[E,B]=w.useState("Wrench"),[O,U]=w.useState(""),[R,V]=w.useState(new Set),[G,z]=w.useState(null),[K,Y]=w.useState(null),ae=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),$=L=>t?t.filter(D=>D.maintenance_items.some(H=>H.maintenance_type_id===L)).map(D=>({printerId:D.printer_id,printerName:D.printer_name,itemId:D.maintenance_items.find(H=>H.maintenance_type_id===L)?.id})):[],W=L=>{if(!t)return[];const D=new Set($(L).map(H=>H.printerId));return ae.filter(H=>!D.has(H.id))},[ee,J]=w.useState(null),[ye,me]=w.useState(""),[te,je]=w.useState(""),[ue,oe]=w.useState("hours"),[_e,se]=w.useState("Wrench"),[Oe,q]=w.useState(""),X=L=>{J(L),me(L.name),je(L.default_interval_hours.toString()),oe(L.interval_type||"hours"),se(L.icon||"Wrench"),q(L.wiki_url||"")},de=()=>{ee&&ye.trim()&&parseFloat(te)>0&&(a(ee.id,{name:ye.trim(),default_interval_hours:parseFloat(te),interval_type:ue,icon:_e,wiki_url:Oe.trim()||null}),J(null))},Z=(L,D,H)=>{const he=parseFloat(x);if(!isNaN(he)&&he>0){const be=Math.abs(he-D)<.01?null:he;n(L,{custom_interval_hours:be,custom_interval_type:g!==H?g:null})}p(null)},ie=L=>{L.preventDefault(),k.trim()&&parseFloat(M)>0&&R.size>0&&(r({name:k.trim(),default_interval_hours:parseFloat(M),interval_type:j,icon:E,wiki_url:O.trim()||null},Array.from(R)),A(""),C("100"),P("hours"),U(""),V(new Set),N(!1))},le=L=>{V(D=>{const H=new Set(D);return H.has(L)?H.delete(L):H.add(L),H})},Fe=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((D,H)=>D.maintenance_type_id-H.maintenance_type_id)})).sort((L,D)=>L.printerName.localeCompare(D.printerName))||[],pe=e.filter(L=>L.is_system),Q=e.filter(L=>!L.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),children:h("maintenance.restoreDefaults")}),i.jsxs(Ce,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionEditTypes"),children:[i.jsx(Xn,{className:"w-4 h-4"}),h("maintenance.addCustomType")]})]})]}),_&&i.jsx(vt,{className:"mb-6",children:i.jsx(_t,{className:"py-4",children:i.jsxs("form",{onSubmit:ie,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("common.name")}),i.jsx("input",{type:"text",value:k,onChange:L=>A(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalType")}),i.jsxs("select",{value:j,onChange:L=>{P(L.target.value),L.target.value==="days"?C("30"):C("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalValue",{type:j==="days"?h("maintenance.calendarDays").toLowerCase():h("common.hours")})}),i.jsx("input",{type:"number",value:M,onChange:L=>C(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Oy).map(L=>{const D=Oy[L];return i.jsx("button",{type:"button",onClick:()=>B(L),className:`p-2 rounded-lg transition-colors ${E===L?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(D,{className:"w-4 h-4"})},L)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:O,onChange:L=>U(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:ae.map(L=>i.jsx("button",{type:"button",onClick:()=>le(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${R.has(L.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:L.name},L.id))}),R.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:h("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>{N(!1),V(new Set)},children:h("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!k.trim()||R.size===0,children:h("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[pe.map(L=>{const D=ov(L.icon),H=L.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(D,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[H==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(L.default_interval_hours,H,h)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&Y(L)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]})},L.id)}),Q.map(L=>{const D=ov(L.icon),H=L.interval_type||"hours";if(ee?.id===L.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:ye,onChange:Ie=>me(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:ue,onChange:Ie=>oe(Ie.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:te,onChange:Ie=>je(Ie.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Oy).map(Ie=>{const qe=Oy[Ie];return i.jsx("button",{type:"button",onClick:()=>se(Ie),className:`p-1.5 rounded transition-colors ${_e===Ie?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(qe,{className:"w-3.5 h-3.5"})},Ie)})}),i.jsx("input",{type:"url",value:Oe,onChange:Ie=>q(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{size:"sm",onClick:de,disabled:!ye.trim(),children:h("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>J(null),children:h("common.cancel")})]})]})},L.id);const be=$(L.id),fe=W(L.id),ze=G===L.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(D,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:h("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[H==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(L.default_interval_hours,H,h)]})]}),i.jsxs("button",{onClick:()=>z(ze?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${be.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:h("maintenance.printersAssignedClick",{count:be.length}),children:[i.jsx(xr,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:be.length}),i.jsx(Un,{className:`w-3 h-3 transition-transform ${ze?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>X(L),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Tf,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(h("maintenance.deleteTypeConfirm",{name:L.name}))&&s(L.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]}),ze&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:h("maintenance.assignedToPrinters")}),be.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:h("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:be.map(Ie=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[Ie.printerName,i.jsx("button",{onClick:()=>Ie.itemId&&u(Ie.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?h("maintenance.removeFromPrinter"):h("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},Ie.printerId))}),fe.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:h("maintenance.addPrinterShort")}),fe.map(Ie=>i.jsxs("button",{onClick:()=>c(Ie.id,L.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",Ie.name]},Ie.id))]})]})]},L.id)})]})]}),Fe.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:Fe.map(L=>i.jsx(vt,{children:i.jsxs(_t,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:L.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:L.items.map(D=>{const H=ov(D.maintenance_type_icon),he=e.find(qe=>qe.id===D.maintenance_type_id),be=he?.default_interval_hours||D.interval_hours,fe=he?.interval_type||"hours",ze=D.interval_type||"hours",Ie=f===D.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(H,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:D.maintenance_type_name}),Ie?i.jsxs("div",{className:"flex items-center gap-1",children:[g==="days"?i.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(Lu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:g,onChange:qe=>y(qe.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:x,onChange:qe=>v(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"&&Z(D.id,be,fe),qe.key==="Escape"&&p(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(Ce,{size:"sm",onClick:()=>Z(D.id,be,fe),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(p(D.id),v(D.interval_hours.toString()),y(ze))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ze==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(D.interval_hours,ze,h),i.jsx(Tf,{className:"w-3 h-3 text-bambu-gray"})]})]},D.id)})})]})},L.printerId))})]}),Fe.length===0&&i.jsx(vt,{children:i.jsxs(_t,{className:"text-center py-12",children:[i.jsx(Gn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:h("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:h("maintenance.intervalOverridesDescription")})]})}),K&&i.jsx(gn,{title:h("maintenance.deleteSystemTypeTitle"),message:h("maintenance.deleteSystemTypeMessage",{name:K.name}),confirmText:h("common.delete"),cancelText:h("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(K.id),Y(null)},onCancel:()=>Y(null)})]})}function $Ze(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),[a,s]=w.useState("status"),{data:o,isLoading:l}=Je({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview}),{data:c}=Je({queryKey:["maintenanceTypes"],queryFn:ne.getMaintenanceTypes}),u=ot({mutationFn:({id:M,notes:C})=>ne.performMaintenance(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),d=ot({mutationFn:({id:M,data:C})=>ne.updateMaintenanceItem(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),h=ot({mutationFn:({id:M,data:C})=>ne.updateMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),f=ot({mutationFn:ne.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),p=ot({mutationFn:ne.restoreDefaultMaintenanceTypes,onSuccess:M=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:M.restored}))},onError:M=>{n(M.message,"error")}}),x=ot({mutationFn:({printerId:M,hours:C})=>ne.setPrinterHours(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),v=ot({mutationFn:({printerId:M,typeId:C})=>ne.assignMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),g=ot({mutationFn:ne.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),y=M=>{u.mutate({id:M})},_=(M,C)=>{d.mutate({id:M,data:{enabled:C}})},N=(M,C)=>{x.mutate({printerId:M,hours:C})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});const k=o?.reduce((M,C)=>M+C.due_count,0)||0,A=o?.reduce((M,C)=>M+C.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[k>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:k})}),k>0&&A>0&&" · ",A>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:A})}),k===0&&A===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((M,C)=>{const j=M.due_count*10+M.warning_count,P=C.due_count*10+C.warning_count;return j!==P?P-j:M.printer_name.localeCompare(C.printer_name)}).map(M=>i.jsx(BZe,{overview:M,onPerform:y,onToggle:_,onSetHours:N,hasPermission:r,t},M.printer_id)):i.jsx(vt,{children:i.jsxs(_t,{className:"text-center py-16",children:[i.jsx(Ef,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(HZe,{overview:o,types:c||[],onUpdateInterval:(M,C)=>d.mutate({id:M,data:C}),onAddType:async(M,C)=>{const j=await ne.createMaintenanceType(M);for(const P of C)await ne.assignMaintenanceType(P,j.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,C)=>h.mutate({id:M,data:C}),onDeleteType:M=>f.mutate(M),onRestoreDefaults:()=>p.mutate(),isRestoringDefaults:p.isPending,onAssignType:(M,C)=>v.mutate({printerId:M,typeId:C}),onRemoveItem:M=>g.mutate(M),hasPermission:r,t})]})}const JW=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Uie({project:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.description||""),[u,d]=w.useState(t?.color||JW[0]),[h,f]=w.useState(t?.target_count?.toString()||""),[p,x]=w.useState(t?.target_parts_count?.toString()||""),[v,g]=w.useState(t?.status||"active"),[y,_]=w.useState(t?.tags||""),[N,k]=w.useState(t?.due_date?.split("T")[0]||""),[A,M]=w.useState(t?.priority||"normal"),C=j=>{j.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:p?parseInt(p,10):void 0,tags:y.trim()||void 0,due_date:N||void 0,priority:A,...t&&{status:v}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:C,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.name")}),i.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.description")}),i.jsx("textarea",{value:l,onChange:j=>c(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:a("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:JW.map(j=>i.jsx("button",{type:"button",onClick:()=>d(j),className:`w-8 h-8 rounded-full transition-transform ${u===j?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:j}},j))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetPlates")}),i.jsx("input",{type:"number",value:h,onChange:j=>f(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetParts")}),i.jsx("input",{type:"number",value:p,onChange:j=>x(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.tagsLabel")}),i.jsx("input",{type:"text",value:y,onChange:j=>_(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.dueDate")}),i.jsx("input",{type:"date",value:N,onChange:j=>k(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.priority")}),i.jsxs("select",{value:A,onChange:j=>M(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"low",children:a("projects.priorityLow")}),i.jsx("option",{value:"normal",children:a("projects.priorityNormal")}),i.jsx("option",{value:"high",children:a("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:a("projects.priorityUrgent")})]})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.status")}),i.jsxs("select",{value:v,onChange:j=>g(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"active",children:a("projects.statusActive")}),i.jsx("option",{value:"completed",children:a("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:a("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a(t?"common.save":"projects.create")})]})]})]})})}function VZe({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",u=t.status==="archived",[d,h]=w.useState(!1),p=c?{icon:ob,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:js,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Gn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:gs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[i.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.bg} flex-shrink-0`,children:i.jsx(p.icon,{className:`w-5 h-5 ${p.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&i.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),u&&i.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const x=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(x)],g=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),y=[...new Set(g)];return v.length===0&&y.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),y.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[y.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),y.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",y.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:x=>x.stopPropagation(),children:[i.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>h(!d),children:i.jsx(Ah,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>h(!1)}),i.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),h(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),h(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(Jt,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(js,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(x=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:x.print_name||"Unknown",children:[x.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(x.id),alt:x.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(fi,{className:"w-6 h-6"})}),x.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(Tn,{className:"w-4 h-4 text-white"})})]},x.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(mi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(fi,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(n3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function qZe(){const{t}=Ut(),e=rc(),n=tn(),{showToast:r}=cn(),{hasPermission:a}=Or(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[h,f]=w.useState(null),{data:p,isLoading:x}=Je({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ne.getProjects(u==="all"?void 0:u)}),v=ot({mutationFn:U=>ne.createProject(U),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:U=>{r(U.message,"error")}}),g=ot({mutationFn:({id:U,data:R})=>ne.updateProject(U,R),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:U=>{r(U.message,"error")}}),y=ot({mutationFn:U=>ne.deleteProject(U),onSuccess:()=>{f(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:U=>{f(null),r(U.message,"error")}}),_=ot({mutationFn:U=>ne.importProject(U),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:U=>{r(U.message,"error")}}),N=w.useRef(null),k=async()=>{try{const U=await ne.getProjects(),R=await Promise.all(U.map(async K=>await ne.exportProjectJson(K.id))),V=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),G=URL.createObjectURL(V),z=document.createElement("a");z.href=G,z.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,z.click(),URL.revokeObjectURL(G),r(t("projects.toast.exported"),"success")}catch(U){r(U.message,"error")}},A=()=>{N.current?.click()},M=async U=>{const R=U.target.files?.[0];if(R){try{if(R.name.toLowerCase().endsWith(".zip"))await ne.importProjectFile(R),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const G=await R.text(),z=JSON.parse(G),K=Array.isArray(z)?z:[z];for(const Y of K)await _.mutateAsync(Y);K.length>1&&r(t("projects.toast.multipleImported",{count:K.length}),"success")}}catch(V){r(`${t("projects.toast.importFailed")}: ${V.message}`,"error")}U.target.value=""}},C=U=>{l?g.mutate({id:l.id,data:U}):v.mutate(U)},j=U=>{c(U),o(!0)},P=U=>{e(`/projects/${U.id}`)},E=U=>{f(U)},B=()=>{h!==null&&y.mutate(h)},O=p?.reduce((U,R)=>(U[R.status]=(U[R.status]||0)+1,U.all=(U.all||0)+1,U),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:M,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(gs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:A,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(Ce,{variant:"secondary",onClick:k,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(ua,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(Ce,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Gn},{key:"completed",label:t("projects.statusCompleted"),icon:ob},{key:"archived",label:t("projects.statusArchived"),icon:js},{key:"all",label:t("common.all"),icon:gs}].map(({key:U,label:R,icon:V})=>i.jsxs("button",{onClick:()=>d(U),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===U?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx(V,{className:"w-4 h-4"}),i.jsx("span",{children:R}),O[U]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===U?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:O[U]})]},U))}),x?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):p?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(gs,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&i.jsxs(Ce,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:p?.map(U=>i.jsx(VZe,{project:U,onClick:()=>P(U),onEdit:()=>j(U),onDelete:()=>E(U.id),hasPermission:a,t},U.id))}),h!==null&&i.jsx(gn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:B,onCancel:()=>f(null)}),s&&i.jsx(Uie,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:v.isPending||g.isPending,t})]})}function GZe(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}function WZe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function KZe({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function eK({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(vt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function XZe({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(fi,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>i.jsxs(Ks,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(fi,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(hi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(pr,{className:"w-4 h-4 text-bambu-green"})}),i.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function YZe({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(Tn,{className:"w-3 h-3"}),a]})}function QZe(t){return t?cb(t,{year:"numeric",month:"short",day:"numeric"}):""}function Mj(t,e){if(!t)return null;const n=di(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function ZZe(){const{id:t}=i0(),e=rc(),{t:n}=Ut(),r=tn(),{showToast:a}=cn(),{hasPermission:s}=Or(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(""),f=parseInt(t||"0",10),{data:p,isLoading:x,error:v}=Je({queryKey:["project",f],queryFn:()=>ne.getProject(f),enabled:f>0}),{data:g,isLoading:y}=Je({queryKey:["project-archives",f],queryFn:()=>ne.getProjectArchives(f),enabled:f>0}),{data:_,isLoading:N}=Je({queryKey:["project-bom",f],queryFn:()=>ne.getProjectBOM(f),enabled:f>0}),{data:k,isLoading:A}=Je({queryKey:["project-timeline",f],queryFn:()=>ne.getProjectTimeline(f,20),enabled:f>0}),{data:M}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:C}=Je({queryKey:["project-folders",f],queryFn:()=>ne.getLibraryFoldersByProject(f),enabled:f>0}),j=rl(M?.currency||"USD"),P=M?.time_format||"system",E=ot({mutationFn:ve=>ne.updateProject(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project",f]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:ve=>{a(ve.message,"error")}}),B=()=>{h(p?.notes||""),u(!0)},O=()=>{E.mutate({notes:d})},U=()=>{u(!1),h("")},[R,V]=w.useState(""),[G,z]=w.useState(1),[K,Y]=w.useState(""),[ae,$]=w.useState(""),[W,ee]=w.useState(""),[J,ye]=w.useState(!1),[me,te]=w.useState(!1),[je,ue]=w.useState(null),[oe,_e]=w.useState(""),[se,Oe]=w.useState(1),[q,X]=w.useState(""),[de,Z]=w.useState(""),[ie,le]=w.useState(""),[Fe,pe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),Q=ot({mutationFn:ve=>ne.createBOMItem(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),V(""),z(1),Y(""),$(""),ee(""),ye(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:ve=>a(ve.message,"error")}),L=ot({mutationFn:({itemId:ve,data:He})=>ne.updateBOMItem(f,ve,He),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),ue(null)},onError:ve=>a(ve.message,"error")}),D=ot({mutationFn:ve=>ne.deleteBOMItem(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:ve=>a(ve.message,"error")}),H=ve=>{ve.preventDefault(),R.trim()&&Q.mutate({name:R.trim(),quantity_needed:G,unit_price:K?parseFloat(K):void 0,sourcing_url:ae.trim()||void 0,remarks:W.trim()||void 0})},he=ve=>{const He=ve.is_complete?0:ve.quantity_needed;L.mutate({itemId:ve.id,data:{quantity_acquired:He}})},be=(ve,He)=>{pe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:He}),onConfirm:()=>{pe(Pe=>({...Pe,isOpen:!1})),D.mutate(ve)}})},fe=ve=>{ue(ve),_e(ve.name),Oe(ve.quantity_needed),X(ve.unit_price?.toString()||""),Z(ve.sourcing_url||""),le(ve.remarks||"")},ze=ve=>{ve.preventDefault(),!(!je||!oe.trim())&&L.mutate({itemId:je.id,data:{name:oe.trim(),quantity_needed:se,unit_price:q?parseFloat(q):void 0,sourcing_url:de.trim()||void 0,remarks:ie.trim()||void 0}})},Ie=()=>{ue(null)},qe=async()=>{try{const{blob:ve,filename:He}=await ne.exportProjectZip(Number(f)),Pe=URL.createObjectURL(ve),nt=document.createElement("a");nt.href=Pe,nt.download=He||`${p?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,nt.click(),URL.revokeObjectURL(Pe),a(n("projectDetail.toast.projectExported"),"success")}catch(ve){a(ve.message,"error")}},tt=ot({mutationFn:()=>ne.createTemplateFromProject(f),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:ve=>a(ve.message,"error")}),Ee=ve=>jf(ve,P,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(x)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!p)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(Ce,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Se=p.stats,Me=Se?.progress_percent??0,xe=Se?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(Ks,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(pi,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:p.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx(ZK,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:p.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:p.name}),p.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:p.description})]})]}),i.jsx(KZe,{status:p.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:qe,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(ua,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(Ce,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(p.target_count||p.target_parts_count)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4 space-y-4",children:[p.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.total_archives||0," / ",p.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Me,100)}%`,backgroundColor:Me>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Me.toFixed(0)})}),Se?.remaining_prints!=null&&Se.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_prints})})]})]}),p.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.completed_prints||0," / ",p.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(xe,100)}%`,backgroundColor:xe>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:xe.toFixed(0)})}),Se?.remaining_parts!=null&&Se.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_parts})})]})]})]})}),Se&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(vt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(fi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[Se.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Se.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Se.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Se.completed_prints})})]})]})})}),i.jsx(eK,{icon:Gn,label:n("projectDetail.stats.printTime"),value:GZe(Se.total_print_time_hours),color:"text-yellow-400"}),i.jsx(eK,{icon:xr,label:n("projectDetail.stats.filamentUsed"),value:WZe(Se.total_filament_grams),color:"text-purple-400"})]}),Se&&(Se.estimated_cost>0||p.budget)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,Se.estimated_cost.toFixed(2)]})]}),Se.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[Se.total_energy_kwh.toFixed(3)," kWh",Se.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",j,Se.total_energy_cost.toFixed(2),")"]})]})]}),p.budget&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,p.budget.toFixed(2)]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.remaining")}),i.jsxs("p",{className:`text-lg font-semibold ${p.budget-Se.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[j,(p.budget-Se.estimated_cost).toFixed(2)]})]})]})]})]})}),p.children&&p.children.length>0&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(hme,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:p.children.length})]}),i.jsx("div",{className:"space-y-2",children:p.children.map(ve=>i.jsxs(Ks,{to:`/projects/${ve.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ve.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:ve.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ve.status==="completed"?"bg-status-ok/20 text-status-ok":ve.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ve.status})]}),ve.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[ve.progress_percent.toFixed(0),"%"]})]},ve.id))})]})}),p.parent_id&&p.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(mi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(Ks,{to:`/projects/${p.parent_id}`,className:"text-bambu-green hover:underline",children:p.parent_name})]}),(p.tags||p.due_date||p.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[p.priority&&p.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(YZe,{priority:p.priority,t:n})]}),p.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(na,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:QZe(p.due_date)}),Mj(p.due_date,n)&&i.jsxs("span",{className:`text-xs ${Mj(p.due_date,n).color}`,children:["(",Mj(p.due_date,n).label,")"]})]}),p.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx($h,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:p.tags.split(",").map((ve,He)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ve.trim()},He))})]})]}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:U,disabled:E.isPending,children:[i.jsx(Ft,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(Ce,{size:"sm",onClick:O,disabled:E.isPending,children:[E.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(ps,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:B,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(KR,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):p.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.notes}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Zl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(Ks,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),C&&C.length>0?i.jsx("div",{className:"space-y-2",children:C.map(ve=>i.jsxs(Ks,{to:`/files?folder=${ve.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Zl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:ve.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ve.file_count})})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},ve.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(cX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Se&&Se.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Se.bom_completed_items,total:Se.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(ve=>ve.is_complete)&&i.jsx("button",{onClick:()=>te(!me),className:`text-xs px-2 py-1 rounded transition-colors ${me?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(me?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!J&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>ye(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),J&&i.jsxs("form",{onSubmit:H,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:R,onChange:ve=>V(ve.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:G,onChange:ve=>z(parseInt(ve.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:K,onChange:ve=>Y(ve.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),i.jsx("input",{type:"url",value:ae,onChange:ve=>$(ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:W,onChange:ve=>ee(ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:()=>ye(!1),children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!R.trim()||Q.isPending,children:Q.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(ve=>!me||!ve.is_complete).map(ve=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${ve.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:je?.id===ve.id?i.jsxs("form",{onSubmit:ze,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:oe,onChange:He=>_e(He.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:se,onChange:He=>Oe(parseInt(He.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:q,onChange:He=>X(He.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),i.jsx("input",{type:"url",value:de,onChange:He=>Z(He.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:ie,onChange:He=>le(He.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:Ie,children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!oe.trim()||L.isPending,children:L.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&he(ve),disabled:L.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${ve.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:ve.is_complete&&i.jsx(pr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${ve.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ve.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ve.quantity_needed]})]}),ve.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[j,(ve.unit_price*ve.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&fe(ve),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&be(ve.id,ve.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]}),ve.sourcing_url&&i.jsxs("a",{href:ve.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:He=>He.stopPropagation(),children:[i.jsx(Kr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ve.sourcing_url).hostname.replace("www.","")}catch{return ve.sourcing_url}})()})]}),ve.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ve.remarks})]})]})},ve.id)),_.some(ve=>ve.unit_price!==null)&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[j,_.reduce((ve,He)=>ve+(He.unit_price||0)*He.quantity_needed,0).toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(mv,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),A?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):k&&k.length>0?i.jsx("div",{className:"space-y-3",children:k.slice(0,10).map((ve,He)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${ve.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ve.event_type==="print_failed"?"bg-status-error/20 text-status-error":ve.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ve.event_type==="print_completed"&&i.jsx(pr,{className:"w-4 h-4"}),ve.event_type==="print_failed"&&i.jsx(hi,{className:"w-4 h-4"}),ve.event_type==="print_started"&&i.jsx(xr,{className:"w-4 h-4"}),ve.event_type==="queued"&&i.jsx(n3,{className:"w-4 h-4"}),ve.event_type==="project_created"&&i.jsx(Xn,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:ve.title}),ve.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ve.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:Ee(ve.timestamp)})]})]},He))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!p.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>tt.mutate(),disabled:tt.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[tt.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(Yl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Se&&(Se.queued_prints>0||Se.in_progress_prints>0)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(n3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(Ks,{to:`/queue?project=${f}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Se.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Se.in_progress_prints})}),Se.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Se.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(fi,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:g?.length||0})]})}),y?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(XZe,{archives:g||[],t:n})]}),o&&i.jsx(Uie,{t:n,project:{...p,archive_count:Se?.total_archives||0,total_items:Se?.total_items||0,completed_count:Se?.completed_prints||0,failed_count:Se?.failed_prints||0,queue_count:Se?.queued_prints||0,progress_percent:Se?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ve=>E.mutate(ve),isLoading:E.isPending}),Fe.isOpen&&i.jsx(gn,{title:Fe.title,message:Fe.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Fe.onConfirm,onCancel:()=>pe(ve=>({...ve,isOpen:!1}))})]})}function JZe({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function eJe({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:u=>l(u.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!o.trim()||o.trim()===e||a,children:a?i.jsx(it,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function tJe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(h,f=0)=>{const p=[];for(const x of h)p.push({id:x.id,name:x.name,depth:f}),x.children.length>0&&p.push(...u(x.children,f+1));return p},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(h=>i.jsxs("button",{onClick:()=>c(h.id),disabled:h.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===h.id?"bg-bambu-green/20 text-bambu-green":h.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+h.depth*16}px`},children:[i.jsx(Zl,{className:"w-4 h-4"}),h.name,h.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},h.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(Ce,{onClick:()=>a(l),disabled:s,children:s?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function nJe({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:d}=Je({queryKey:["archives-for-link"],queryFn:()=>ne.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},f=()=>{n({project_id:0,archive_id:0})},p=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Eh,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(JK,{className:"w-4 h-4"}),a("fileManager.project")]}),i.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(js,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:x.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:x.name})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(df,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:x.print_name||x.filename})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[p&&i.jsxs(Ce,{variant:"danger",onClick:f,disabled:r,children:[i.jsx(YC,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${p?"":"ml-auto"}`,children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{onClick:h,disabled:!l||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function rJe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[a,s]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(!0),[f,p]=w.useState(!1),[x,v]=w.useState(!0),g=w.useRef(null),y=V=>{V.preventDefault(),l(!0)},_=V=>{V.preventDefault(),l(!1)},N=V=>{V.preventDefault(),l(!1);const G=Array.from(V.dataTransfer.files);A(G)},k=V=>{V.target.files&&A(Array.from(V.target.files))},A=V=>{const G=V.map(z=>({file:z,status:"pending",isZip:z.name.toLowerCase().endsWith(".zip"),is3mf:z.name.toLowerCase().endsWith(".3mf")}));s(z=>[...z,...G])},M=V=>{s(G=>G.filter((z,K)=>K!==V))},C=a.some(V=>V.isZip&&V.status==="pending"),j=a.some(V=>V.file.name.toLowerCase().endsWith(".stl")&&V.status==="pending"),P=a.some(V=>V.is3mf&&V.status==="pending"),E=async()=>{if(a.length!==0){u(!0);for(let V=0;VG.map((z,K)=>K===V?{...z,status:"uploading"}:z));try{if(a[V].isZip){const G=await ne.extractZipFile(a[V].file,t,d,f,x);s(z=>z.map((K,Y)=>Y===V?{...K,status:G.errors.length>0&&G.extracted===0?"error":"success",extractedCount:G.extracted,error:G.errors.length>0?`${G.errors.length} files failed`:void 0}:K))}else await ne.uploadLibraryFile(a[V].file,t,x),s(G=>G.map((z,K)=>K===V?{...z,status:"success"}:z))}catch(G){s(z=>z.map((K,Y)=>Y===V?{...K,status:"error",error:G instanceof Error?G.message:"Upload failed"}:K))}}u(!1),n(),e()}},B=a.filter(V=>V.status==="pending").length,O=a.filter(V=>V.status==="success").length,U=a.filter(V=>V.status==="error").length,R=a.length>0&&B===0&&!c;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("fileManager.uploadFiles")}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:y,onDragLeave:_,onDrop:N,onClick:()=>g.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(Ra,{className:`w-10 h-10 mx-auto mb-3 ${o?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:r(o?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.orClickToBrowse")}),i.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:r("fileManager.allFileTypesSupported")})]}),i.jsx("input",{ref:g,type:"file",multiple:!0,className:"hidden",onChange:k}),C&&i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(js,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-blue-300 font-medium",children:r("fileManager.zipFilesDetected")}),i.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:r("fileManager.zipExtractOptions")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d,onChange:V=>h(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.preserveZipStructure")})]}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:f,onChange:V=>p(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.createFolderFromZip")})]})]})]})}),P&&i.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(xr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-purple-300 font-medium",children:r("fileManager.threemfDetected")}),i.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:r("fileManager.threemfExtractionInfo")})]})]})}),(j||C)&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Ju,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium",children:r("fileManager.stlThumbnailGeneration")}),i.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:r(C&&!j?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:x,onChange:V=>v(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.generateThumbnailsForStl")})]})]})]})}),a.length>0&&i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:a.map((V,G)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[V.isZip?i.jsx(js,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(zC,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:V.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(V.file.size/1024/1024).toFixed(2)," MB",V.isZip&&V.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),V.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:V.extractedCount})]})]})]}),V.status==="pending"&&i.jsx("button",{onClick:()=>M(G),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ft,{className:"w-4 h-4 text-bambu-gray"})}),V.status==="uploading"&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),V.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),V.status==="error"&&i.jsx("span",{title:V.error,children:i.jsx(hi,{className:"w-4 h-4 text-red-500"})})]},G))}),R&&i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[r("fileManager.uploadComplete",{succeeded:O}),U>0&&i.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:U})]})]})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:r(R?"common.close":"common.cancel")}),!R&&i.jsx(Ce,{onClick:E,disabled:B===0||c,children:c?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",B>0?`(${B})`:""]})})]})]})})}function Bie({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,h]=w.useState(!0),[f,p]=w.useState(!1),x=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[x?i.jsx("button",{onClick:g=>{g.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(pi,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Zl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:g=>{g.stopPropagation(),a(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[i.jsx(Eh,{className:"w-3 h-3"}),t.project_name?i.jsx(JK,{className:"w-3 h-3"}):i.jsx(js,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:g=>{g.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(Eh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:g=>g.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>p(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),i.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(a(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(Eh,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),p(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),x&&d&&i.jsx("div",{children:t.children.map(g=>i.jsx(Bie,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},g.id))})]})}function tF(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function aJe({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:h,hasPermission:f,canModify:p,authEnabled:x,t:v}){const[g,y]=w.useState(!1);return i.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(df,{className:"w-12 h-12 text-bambu-gray/30"}),i.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:ul(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Gn,{className:"w-3 h-3"}),Qs(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(xr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),x&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(td,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>y(!g),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}),g&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),i.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&tF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("printers:control")&&(l(t),y(!1))},disabled:!f("printers:control"),title:f("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(xr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&tF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("queue:create")&&(o(t.id),y(!1))},disabled:!f("queue:create"),title:f("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(c(t),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(Ja,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(s(t.id),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(ua,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(u(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(d(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ju,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","delete",t.created_by_id)&&(a(t.id),y(!1))},disabled:!p("library","delete",t.created_by_id),title:p("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function iJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Or(),[l]=dF(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=w.useState(u),[f,p]=w.useState([]),[x,v]=w.useState(!1),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(null),[M,C]=w.useState(null),[j,P]=w.useState(null),[E,B]=w.useState(null),[O,U]=w.useState(null),[R,V]=w.useState(null),[G,z]=w.useState({}),[K,Y]=w.useState(null),[ae,$]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[W,ee]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[J,ye]=w.useState(()=>{const Ue=localStorage.getItem("library-sidebar-width");return Ue?parseInt(Ue,10):256}),[me,te]=w.useState(!1),je=w.useRef(null);w.useEffect(()=>{if(!me)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ue=wt=>{if(!je.current)return;const qt=je.current.parentElement?.getBoundingClientRect();if(!qt)return;const Cn=wt.clientX-qt.left,yr=Math.min(500,Math.max(200,Cn));ye(yr)},bt=()=>{te(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(J))};return document.addEventListener("mousemove",Ue),document.addEventListener("mouseup",bt),()=>{document.removeEventListener("mousemove",Ue),document.removeEventListener("mouseup",bt),document.body.style.userSelect="",document.body.style.cursor=""}},[me,J]);const[ue,oe]=w.useState(""),[_e,se]=w.useState("all"),[Oe,q]=w.useState(""),[X,de]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[Z,ie]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),le=sne();w.useEffect(()=>{const Ue=l.get("folder");if(Ue){const bt=parseInt(Ue,10);h(bt)}},[l]);const{data:Fe}=Je({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:pe,isLoading:Q}=Je({queryKey:["library-folders"],queryFn:()=>ne.getLibraryFolders()}),{data:L,isLoading:D}=Je({queryKey:["library-files",d],queryFn:()=>ne.getLibraryFiles(d,d===null)}),{data:H}=Je({queryKey:["library-stats"],queryFn:()=>ne.getLibraryStats()}),{data:he}=Je({queryKey:["users"],queryFn:()=>ne.getUsers()}),be=w.useMemo(()=>{if(!L)return[];const Ue=new Set(L.map(bt=>bt.file_type));return Array.from(Ue).sort()},[L]),fe=w.useMemo(()=>{if(!L)return[];let Ue=[...L];if(ue.trim()){const bt=ue.toLowerCase();Ue=Ue.filter(wt=>wt.filename.toLowerCase().includes(bt)||wt.print_name&&wt.print_name.toLowerCase().includes(bt))}if(_e!=="all"&&(Ue=Ue.filter(bt=>bt.file_type===_e)),Oe.trim()){const bt=Oe.toLowerCase();Ue=Ue.filter(wt=>wt.created_by_username&&wt.created_by_username.toLowerCase().includes(bt))}return Ue.sort((bt,wt)=>{let qt=0;switch(X){case"name":qt=(bt.print_name||bt.filename).localeCompare(wt.print_name||wt.filename);break;case"date":qt=new Date(bt.created_at).getTime()-new Date(wt.created_at).getTime();break;case"size":qt=bt.file_size-wt.file_size;break;case"type":qt=bt.file_type.localeCompare(wt.file_type);break;case"prints":qt=bt.print_count-wt.print_count;break}return Z==="asc"?qt:-qt}),Ue},[L,ue,_e,Oe,X,Z]),ze=w.useMemo(()=>{if(!H||!Fe)return!1;const Ue=(Fe.library_disk_warning_gb||5)*1024*1024*1024;return H.disk_free_bytesne.createLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ue=>n(Ue.message,"error")}),qe=ot({mutationFn:Ue=>ne.deleteLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===M?.id&&h(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),tt=ot({mutationFn:Ue=>ne.deleteLibraryFile(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),p(Ue=>Ue.filter(bt=>bt!==M?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),Ee=ot({mutationFn:Ue=>ne.bulkDeleteLibrary(Ue,[]),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:bt.length}),"success"),p([]),C(null)},onError:Ue=>{C(null),n(Ue.message,"error")}}),Se=ot({mutationFn:({fileIds:Ue,folderId:bt})=>ne.moveLibraryFiles(Ue,bt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),p([]),y(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ue=>n(Ue.message,"error")}),Me=ot({mutationFn:({id:Ue,data:bt})=>ne.updateLibraryFolder(Ue,bt),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),A(null);const wt=bt.data.project_id===0&&bt.data.archive_id===0;n(t(wt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ue=>n(Ue.message,"error")}),xe=ot({mutationFn:({id:Ue,filename:bt})=>ne.updateLibraryFile(Ue,{filename:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ue=>{V(null),n(Ue.message,"error")}}),ve=ot({mutationFn:({id:Ue,name:bt})=>ne.updateLibraryFolder(Ue,{name:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ue=>{V(null),n(Ue.message,"error")}}),He=ot({mutationFn:()=>ne.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Date.now(),wt={};Ue.results.forEach(qt=>{qt.success&&(wt[qt.file_id]=bt)}),z(qt=>({...qt,...wt}))}Ue.succeeded>0&&Ue.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ue.succeeded}),"success"):Ue.succeeded>0&&Ue.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ue.succeeded,failed:Ue.failed}),"success"):Ue.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),Pe=ot({mutationFn:Ue=>ne.batchGenerateStlThumbnails({file_ids:[Ue]}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Ue.results[0]?.file_id;bt&&z(wt=>({...wt,[bt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),nt=w.useCallback(Ue=>{const bt=Ue.toLowerCase();return bt.endsWith(".gcode")||bt.includes(".gcode.")},[]),Te=w.useMemo(()=>L?L.filter(Ue=>f.includes(Ue.id)&&nt(Ue.filename)):[],[L,f,nt]),Ge=w.useCallback(Ue=>{p(bt=>bt.includes(Ue)?bt.filter(wt=>wt!==Ue):[...bt,Ue])},[]),Re=w.useCallback(()=>{fe.length>0&&p(fe.map(Ue=>Ue.id))},[fe]),Le=w.useCallback(()=>{p([])},[]),Ke=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ft=Ue=>{ne.downloadLibraryFile(Ue).catch(bt=>{console.error("Library file download failed:",bt)})},kt=()=>{M&&(M.type==="file"?tt.mutate(M.id):M.type==="folder"?qe.mutate(M.id):M.type==="bulk"&&Ee.mutate(f))},Lt=qe.isPending||tt.isPending||Ee.isPending,Kt=Ue=>{$(Ue),localStorage.setItem("library-view-mode",Ue)},Mt=Q||D;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Zl,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>Kt("grid"),className:`p-1.5 rounded transition-colors ${ae==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(c0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>Kt("list"),className:`p-1.5 rounded transition-colors ${ae==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(HC,{className:"w-4 h-4"})})]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>He.mutate(),disabled:He.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[He.isPending?i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ju,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(ume,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ze&&H&&Fe&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ul(H.disk_free_bytes),total:ul(H.disk_total_bytes),threshold:Fe.library_disk_warning_gb})})]})]}),H&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(zC,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:H.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Zl,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:H.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Ub,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:ul(H.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${ze?"text-amber-500":"text-white"}`,children:ul(H.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:Ue=>h(Ue.target.value?parseInt(Ue.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),pe&&(()=>{const Ue=(bt,wt=0)=>{const qt=[];for(const Cn of bt)qt.push({id:Cn.id,name:Cn.name,fileCount:Cn.file_count,depth:wt}),Cn.children.length>0&&qt.push(...Ue(Cn.children,wt+1));return qt};return Ue(pe).map(bt=>i.jsxs("option",{value:bt.id,children:["│ ".repeat(bt.depth),"📂 ",bt.name," ",bt.fileCount>0?`(${bt.fileCount})`:""]},bt.id))})()]})}),i.jsxs("div",{ref:je,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${J}px`},children:[i.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${me?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ue=>{Ue.preventDefault(),te(!0)},onDoubleClick:()=>{ye(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${me?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const Ue=!W;ee(Ue),localStorage.setItem("library-wrap-folders",String(Ue))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>h(null),children:[i.jsx(df,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),pe?.map(Ue=>i.jsx(Bie,{folder:Ue,selectedFolderId:d,onSelect:h,onDelete:bt=>C({type:"folder",id:bt}),onLink:A,onRename:bt=>V({type:"folder",id:bt.id,name:bt.name}),wrapNames:W,hasPermission:r,t},Ue.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[L&&L.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:ue,onChange:Ue=>oe(Ue.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(UC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:_e,onChange:Ue=>se(Ue.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),be.map(Ue=>i.jsx("option",{value:Ue,children:Ue.toUpperCase()},Ue))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:Oe,onChange:Ue=>q(Ue.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${Oe?"pr-7":""}`,style:Oe?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),Oe&&i.jsx("button",{onClick:()=>q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ft,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:he?.map(Ue=>i.jsx("option",{value:Ue.username},Ue.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:X,onChange:Ue=>{const bt=Ue.target.value;de(bt),localStorage.setItem("library-sort-field",bt)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>ie(Ue=>{const bt=Ue==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",bt),bt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(Z==="asc"?"fileManager.ascending":"fileManager.descending"),children:Z==="asc"?i.jsx(Tde,{className:"w-4 h-4 text-white"}):i.jsx(wde,{className:"w-4 h-4 text-white"})})]}),(ue||_e!=="all"||Oe)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:fe.length,total:L.length})})]}),fe.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===fe.length&&f.length>0?i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,children:[i.jsx(vl,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Re,children:[i.jsx(so,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Te.length===1&&i.jsxs(Ce,{variant:"primary",size:"sm",onClick:()=>B(Te[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(io,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Te.length===1&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>U(Te[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Gn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(bfe,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>{f.length===1?C({type:"file",id:f[0]}):C({type:"bulk",id:0,count:f.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(Jt,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,children:[i.jsx(Ft,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Mt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):L?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(df,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):fe.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(kr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(Ce,{variant:"secondary",onClick:()=>{oe(""),se("all")},children:t("fileManager.clearFilters")})]}):ae==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:fe.map(Ue=>i.jsx(aJe,{file:Ue,isSelected:f.includes(Ue.id),isMobile:le,t,onSelect:Ge,onDelete:bt=>C({type:"file",id:bt}),onDownload:ft,onAddToQueue:bt=>{const wt=L?.find(qt=>qt.id===bt);wt&&U(wt)},onPrint:P,onPreview3d:Y,onRename:bt=>V({type:"file",id:bt.id,name:bt.filename}),onGenerateThumbnail:bt=>Pe.mutate(bt.id),thumbnailVersion:G[Ue.id],hasPermission:r,canModify:s,authEnabled:o},Ue.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),fe.map(Ue=>i.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(Ue.id)?"bg-bambu-green/10":""}`,onClick:()=>Ge(Ue.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ue.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ue.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ue.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(df,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ue.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:Ue.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:Ue.print_name||Ue.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ue.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx(td,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:Ue.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ue.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ue.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ue.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ue.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:ul(Ue.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:Ue.print_count>0?`${Ue.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:bt=>bt.stopPropagation(),children:[tF(Ue.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&P(Ue),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:i.jsx(xr,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&U(Ue)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:i.jsx(Gn,{className:"w-4 h-4"})})]}),(Ue.file_type==="3mf"||Ue.file_type==="gcode"||Ue.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&Y(Ue),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:i.jsx(Ja,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&ft(Ue.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:i.jsx(ua,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&V({type:"file",id:Ue.id,name:Ue.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ue.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ue.created_by_id),children:i.jsx($a,{className:"w-4 h-4"})}),Ue.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&Pe.mutate(Ue.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ue.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Pe.isPending||!s("library","update",Ue.created_by_id),children:i.jsx(Ju,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",Ue.created_by_id)&&C({type:"file",id:Ue.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Ue.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ue.created_by_id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},Ue.id))]})})]})]}),x&&i.jsx(JZe,{parentId:d,onClose:()=>v(!1),onSave:Ue=>Ie.mutate(Ue),isLoading:Ie.isPending,t}),g&&pe&&i.jsx(tJe,{folders:pe,selectedFiles:f,currentFolderId:d,onClose:()=>y(!1),onMove:Ue=>Se.mutate({fileIds:f,folderId:Ue}),isLoading:Se.isPending,t}),_&&i.jsx(rJe,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ke,t}),k&&i.jsx(nJe,{folder:k,onClose:()=>A(null),onLink:Ue=>Me.mutate({id:k.id,data:Ue}),isLoading:Me.isPending,t}),M&&i.jsx(gn,{title:M.type==="folder"?t("fileManager.deleteFolder"):M.type==="bulk"?t("fileManager.deleteFilesCount",{count:M.count}):t("fileManager.deleteFile"),message:M.type==="folder"?t("fileManager.deleteFolderConfirm"):M.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:M.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Lt,loadingText:t("fileManager.deleting"),onConfirm:kt,onCancel:()=>C(null)}),j&&i.jsx(Xu,{mode:"reprint",libraryFileId:j.id,archiveName:j.print_name||j.filename,onClose:()=>P(null),onSuccess:()=>{P(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),E&&i.jsx(Xu,{mode:"reprint",libraryFileId:E.id,archiveName:E.print_name||E.filename,onClose:()=>B(null),onSuccess:()=>{B(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),O&&i.jsx(Xu,{mode:"add-to-queue",libraryFileId:O.id,archiveName:O.print_name||O.filename,onClose:()=>U(null),onSuccess:()=>{U(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&i.jsx(hI,{libraryFileId:K.id,title:K.print_name||K.filename,fileType:K.file_type,onClose:()=>Y(null)}),R&&i.jsx(eJe,{type:R.type,currentName:R.name,onClose:()=>V(null),onSave:Ue=>{R.type==="file"?xe.mutate({id:R.id,filename:Ue}):ve.mutate({id:R.id,name:Ue})},isLoading:xe.isPending||ve.isPending,t})]})}const Pj=5,sJe=2e3,oJe=3e4,lJe=5e3;function cJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),{printerId:a}=i0(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,h]=w.useState(!1),[f,p]=w.useState(!0),[x,v]=w.useState(Date.now()),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(0),[M,C]=w.useState(!1),[j,P]=w.useState(0),[E,B]=w.useState(1),[O,U]=w.useState({x:0,y:0}),[R,V]=w.useState(!1),[G,z]=w.useState({x:0,y:0}),[K,Y]=w.useState(null),[ae,$]=w.useState(null),W=w.useRef(null),ee=w.useRef(null),J=w.useRef(null),ye=w.useRef(null),me=w.useRef(null),{data:te}=Je({queryKey:["printer",s],queryFn:()=>ne.getPrinter(s),enabled:s>0}),{data:je}=Je({queryKey:["printerStatus",s],queryFn:()=>ne.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),ue=ot({mutationFn:Se=>ne.setChamberLight(s,Se),onMutate:async Se=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Me=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],xe=>({...xe,chamber_light:Se})),{previousStatus:Me}},onSuccess:(Se,Me)=>{n(`Chamber light ${Me?"on":"off"}`)},onError:(Se,Me,xe)=>{xe?.previousStatus&&e.setQueryData(["printerStatus",s],xe.previousStatus),n(Se.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(je?.state==="RUNNING"||je?.state==="PAUSE")&&(je?.printable_objects_count??0)>=2;w.useEffect(()=>(te&&(document.title=`${te.name} - Camera`),()=>{document.title="Bambuddy"}),[te]);const _e=w.useRef(!1);w.useEffect(()=>{const Se=`/api/v1/printers/${s}/camera/stop`;_e.current=!1;const Me=()=>{if(s>0&&!_e.current){_e.current=!0;const He={},Pe=nd();Pe&&(He.Authorization=`Bearer ${Pe}`),fetch(Se,{method:"POST",keepalive:!0,headers:He}).catch(()=>{})}},xe=()=>{Me()};window.addEventListener("beforeunload",xe);const ve=W.current;return()=>{window.removeEventListener("beforeunload",xe),ve&&(ve.src=""),Me()}},[s]),w.useEffect(()=>{if(f&&!g){const Me=setTimeout(()=>{p(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Me)}},[o,f,x,g]),w.useEffect(()=>{const Se=()=>{const Me=!!document.fullscreenElement;N(Me),B(1),U({x:0,y:0}),o==="stream"&&!g&&(W.current&&(W.current.src=""),setTimeout(()=>{p(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",Se),()=>document.removeEventListener("fullscreenchange",Se)},[o,g]),w.useEffect(()=>{let Se;const Me=()=>{clearTimeout(Se),Se=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Me),()=>{clearTimeout(Se),window.removeEventListener("resize",Me)}},[]),w.useEffect(()=>()=>{J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),me.current&&clearInterval(me.current)},[]);const se=w.useCallback(()=>{if(k>=Pj){C(!1),h(!0);return}const Se=Math.min(sJe*Math.pow(2,k),oJe);C(!0),P(Math.ceil(Se/1e3)),ye.current=setInterval(()=>{P(Me=>Me<=1?(ye.current&&clearInterval(ye.current),0):Me-1)},1e3),J.current=setTimeout(()=>{A(Me=>Me+1),C(!1),p(!0),h(!1),W.current&&(W.current.src=""),v(Date.now())},Se)},[k]);w.useEffect(()=>{if(o!=="stream"||f||M||g){me.current&&(clearInterval(me.current),me.current=null);return}return me.current=setInterval(async()=>{try{const Se=await ne.getCameraStatus(s);(Se.stalled||!Se.active&&!d)&&(console.log(`Stream issue detected: stalled=${Se.stalled}, active=${Se.active}, reconnecting...`),me.current&&(clearInterval(me.current),me.current=null),p(!1),se())}catch{}},lJe),()=>{me.current&&(clearInterval(me.current),me.current=null)}},[o,f,d,M,g,s,se]);const Oe=()=>{p(!1),o==="stream"&&k{if(p(!1),h(!1),A(0),C(!1),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&!localStorage.getItem("cameraWindowState")){const Se=W.current,Me=Se.naturalWidth,xe=Se.naturalHeight;if(Me>0&&xe>0){const Pe=window.outerWidth-window.innerWidth,nt=window.outerHeight-window.innerHeight,Te=Me+16+Pe,Ge=xe+45+16+nt;try{window.resizeTo(Te,Ge)}catch{}}}},X=()=>{if(s>0){const Se={},Me=nd();Me&&(Se.Authorization=`Bearer ${Me}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:Se}).catch(()=>{})}},de=Se=>{o===Se||g||(y(!0),p(!0),h(!1),A(0),C(!1),B(1),U({x:0,y:0}),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&(W.current.src=""),o==="stream"&&X(),setTimeout(()=>{l(Se),v(Date.now()),y(!1)},100))},Z=()=>{g||(y(!0),p(!0),h(!1),A(0),C(!1),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&(W.current.src=""),o==="stream"&&X(),setTimeout(()=>{v(Date.now()),y(!1)},100))},ie=()=>{ee.current&&(document.fullscreenElement?document.exitFullscreen():ee.current.requestFullscreen())},le=()=>{B(Se=>Math.min(Se+.5,4))},Fe=()=>{B(Se=>{const Me=Math.max(Se-.5,1);return Me===1&&U({x:0,y:0}),Me})},pe=Se=>{Se.preventDefault(),Se.deltaY<0?le():Fe()},Q=Se=>{E>1&&(Se.preventDefault(),V(!0),z({x:Se.clientX-O.x,y:Se.clientY-O.y}))},L=w.useCallback(()=>{if(!ee.current)return{x:300,y:200};const Se=ee.current.getBoundingClientRect(),Me=Se.width*(E-1)/2,xe=Se.height*(E-1)/2;return{x:Math.max(50,Me),y:Math.max(50,xe)}},[E]),D=Se=>{if(R&&E>1){const Me=Se.clientX-G.x,xe=Se.clientY-G.y,ve=L();U({x:Math.max(-ve.x,Math.min(ve.x,Me)),y:Math.max(-ve.y,Math.min(ve.y,xe))})}},H=()=>{V(!1)},he=Se=>{if(Se.length<2)return 0;const Me=Se[0].clientX-Se[1].clientX,xe=Se[0].clientY-Se[1].clientY;return Math.sqrt(Me*Me+xe*xe)},be=Se=>Se.length<2?{x:Se[0].clientX,y:Se[0].clientY}:{x:(Se[0].clientX+Se[1].clientX)/2,y:(Se[0].clientY+Se[1].clientY)/2},fe=Se=>{Se.touches.length===2?(Se.preventDefault(),Y(he(Se.touches)),$(be(Se.touches))):Se.touches.length===1&&E>1&&(Se.preventDefault(),V(!0),z({x:Se.touches[0].clientX-O.x,y:Se.touches[0].clientY-O.y}))},ze=Se=>{if(Se.touches.length===2&&K!==null){Se.preventDefault();const Me=he(Se.touches),xe=Me/K;B(He=>{const Pe=Math.max(1,Math.min(4,He*xe));return Pe===1&&U({x:0,y:0}),Pe}),Y(Me);const ve=be(Se.touches);if(ae){const He=L();U(Pe=>({x:Math.max(-He.x,Math.min(He.x,Pe.x+(ve.x-ae.x))),y:Math.max(-He.y,Math.min(He.y,Pe.y+(ve.y-ae.y)))}))}$(ve)}else if(Se.touches.length===1&&R&&E>1){Se.preventDefault();const Me=Se.touches[0].clientX-G.x,xe=Se.touches[0].clientY-G.y,ve=L();U({x:Math.max(-ve.x,Math.min(ve.x,Me)),y:Math.max(-ve.y,Math.min(ve.y,xe))})}},Ie=Se=>{Se.touches.length<2&&(Y(null),$(null)),Se.touches.length===0&&V(!1)},qe=()=>{B(1),U({x:0,y:0})},tt=g?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`,Ee=f||g||M;return s?i.jsxs("div",{ref:ee,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(sb,{className:"w-4 h-4"}),te?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>de("stream"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),i.jsx("button",{onClick:()=>de("snapshot"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),i.jsx("button",{onClick:()=>ue.mutate(!je?.chamber_light),disabled:!je?.connected||ue.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${je?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:i.jsx(aL,{on:je?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!oe||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${oe&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(oe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(lk,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:Z,disabled:Ee,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Cr,{className:`w-4 h-4 text-bambu-gray ${Ee?"animate-spin":""}`})}),i.jsx("button",{onClick:ie,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(oX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(ife,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:D,onMouseUp:H,onMouseLeave:H,onTouchStart:fe,onTouchMove:ze,onTouchEnd:Ie,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(f||g)&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Cr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Pf,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:j,attempt:k+1,max:Pj})}),i.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Tn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:W,src:tt,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${E}) translate(${O.x/E}px, ${O.y/E}px)`,cursor:E>1?R?"grabbing":"grab":"default"},onError:tt?Oe:void 0,onLoad:tt?q:void 0,onMouseDown:Q,draggable:!1},x),i.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[i.jsx("button",{onClick:Fe,disabled:E<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(TF,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:qe,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(E*100),"%"]}),i.jsx("button",{onClick:le,disabled:E>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(AF,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(iL,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function uJe(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),a=t.get("camera"),s=a!=="false"&&a!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function dJe(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function hJe(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function mJe(){const{printerId:t}=i0(),[e]=dF(),{t:n}=Ut(),r=tn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>uJe(e),[e]),c=hJe(l.size),{data:u}=Je({queryKey:["printer",a],queryFn:()=>ne.getPrinter(a),enabled:a>0}),{data:d}=Je({queryKey:["printerStatus",a],queryFn:()=>ne.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:h}=Je({queryKey:["settings"],queryFn:ne.getSettings}),f=h?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=k=>{try{const A=JSON.parse(k.data);A.type==="printer_status"&&A.printer_id===a&&r.setQueryData(["printerStatus",a],A.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const p=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const x=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,g=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:g,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",onError:p},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(xr,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:dJe(d,n)}),l.showProgress&&x&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),x&&(l.showLayers||l.showEta)&&i.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(mi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Lu,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Qs(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Gn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",MF(d.remaining_time,f,n)]})]})]})]}),!x&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function fJe(){const{t}=Ut(),{id:e}=i0(),{mode:n}=Jf(),{data:r,isLoading:a,error:s}=Je({queryKey:["external-link",e],queryFn:()=>ne.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(Tn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function tK(){const{id:t}=i0(),e=rc(),n=tn(),{t:r}=Ut(),{showToast:a}=cn(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,h]=w.useState([]),[f,p]=w.useState(""),[x,v]=w.useState(!1),{data:g,isLoading:y}=Je({queryKey:["group",t],queryFn:()=>ne.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=Je({queryKey:["permissions"],queryFn:()=>ne.getPermissions()});s&&g&&!x&&(l(g.name),u(g.description||""),h(g.permissions),v(!0));const k=ot({mutationFn:z=>ne.createGroup(z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),A=ot({mutationFn:z=>ne.updateGroup(Number(t),z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),M=k.isPending||A.isPending,C=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?A.mutate({name:o!==g?.name?o:void 0,description:c,permissions:d}):k.mutate({name:o,description:c||void 0,permissions:d})},j=z=>{h(K=>K.includes(z)?K.filter(Y=>Y!==z):[...K,z])},P=(z,K)=>{const Y=z.permissions.map(ae=>ae.value);h(ae=>{const $=ae.filter(W=>!Y.includes(W));return K?[...$,...Y]:$})},E=z=>z.permissions.every(K=>d.includes(K.value)),B=z=>{const K=z.permissions.filter(Y=>d.includes(Y.value)).length;return K>0&&K{_&&h(_.all_permissions)},U=()=>{h([])},R=f.toLowerCase(),V=w.useMemo(()=>_?R?_.categories.map(z=>({...z,permissions:z.permissions.filter(K=>K.label.toLowerCase().includes(R))})).filter(z=>z.permissions.length>0):_.categories:[],[_,R]),G=_?.all_permissions.length??0;return y||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:i.jsx(ZK,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&g?.is_system&&i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:z=>l(z.target.value),disabled:s&&g?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:z=>u(z.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",G]}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:O,children:r("groups.editor.selectAll")}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:U,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:f,onChange:z=>p(z.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),V.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:V.map(z=>{const K=_.categories.find(ee=>ee.name===z.name),Y=K.permissions.filter(ee=>d.includes(ee.value)).length,ae=K.permissions.length,$=E(K),W=B(K);return i.jsxs(vt,{children:[i.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>P(K,!$),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${$?"bg-bambu-green border-bambu-green":W?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[$&&i.jsx(ra,{className:"w-3 h-3 text-white"}),W&&!$&&i.jsx(x1,{className:"w-3 h-3 text-white"})]}),i.jsx(i3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:z.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[Y,"/",ae]})]}),i.jsx("div",{className:"p-3 space-y-1",children:z.permissions.map(ee=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(ee.value),onChange:()=>j(ee.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:ee.label})]},ee.value))})]},z.name)})}),i.jsx("div",{className:"h-16"}),i.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(Ce,{onClick:C,disabled:M||!o.trim(),children:M?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const nK={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function pJe(t){const e={};return t.slicer_filament||(e.slicer_filament="Slicer preset is required"),t.material||(e.material="Material is required"),t.brand||(e.brand="Brand is required"),t.subtype||(e.subtype="Subtype is required"),{isValid:Object.keys(e).length===0,errors:e}}const gJe=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],bJe=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],lv=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Hie=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],xJe=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],rK=[...Hie,...xJe],$ie="bambuddy-recent-colors",yJe=8,vJe=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Rb(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PCTG","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of lv)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of lv){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function wJe(t,e){const n=new Set(bJe);for(const r of t){const{brand:a}=Rb(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Rb(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function SJe(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function _Je(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=SJe(n);if(r.length>0)return r}return vJe}function NJe(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function CJe(){try{const t=localStorage.getItem($ie);if(t)return JSON.parse(t)}catch{}return[]}function kJe(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,yJe);try{localStorage.setItem($ie,JSON.stringify(r))}catch{}return r}function Ej(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Rb(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function AJe({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u}){const{t:d}=Ut(),[h,f]=w.useState(!1),[p,x]=w.useState(!1),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(""),[A,M]=w.useState(""),[C,j]=w.useState(""),[P,E]=w.useState(String(t.label_weight)),[B,O]=w.useState(!1),U=w.useRef(null),R=w.useRef(null),V=w.useRef(null),G=w.useRef(null);w.useEffect(()=>{const W=ee=>{U.current&&!U.current.contains(ee.target)&&f(!1),G.current&&!G.current.contains(ee.target)&&_(!1),R.current&&!R.current.contains(ee.target)&&x(!1),V.current&&!V.current.contains(ee.target)&&g(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[]);const z=w.useMemo(()=>{if(!a)return l;const W=a.toLowerCase();return l.filter(ee=>ee.displayName.toLowerCase().includes(W)||ee.code.toLowerCase().includes(W))},[l,a]),K=w.useMemo(()=>{if(!N)return c;const W=N.toLowerCase();return c.filter(J=>J.toLowerCase().includes(W)).sort((J,ye)=>{const me=J.toLowerCase()===W,te=ye.toLowerCase()===W;return me&&!te?-1:!me&&te?1:J.localeCompare(ye)})},[c,N]),Y=w.useMemo(()=>{if(!A)return lv;const W=A.toLowerCase();return lv.filter(ee=>ee.toLowerCase().includes(W))},[A]),ae=w.useMemo(()=>{if(!C)return u;const W=C.toLowerCase();return u.filter(J=>J.toLowerCase().includes(W)).sort((J,ye)=>{const me=J.toLowerCase()===W,te=ye.toLowerCase()===W;return me&&!te?-1:!me&&te?1:J.localeCompare(ye)})},[C,u]);w.useEffect(()=>{B||E(String(t.label_weight))},[t.label_weight,B]);const $=W=>{e("slicer_filament",W.code),s(W.displayName),f(!1);const ee=Rb(W.name);ee.material&&e("material",ee.material),ee.brand&&e("brand",ee.brand),ee.variant&&e("subtype",ee.variant)};return i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-3 h-3 animate-spin"})," ",d("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(zb,{className:"w-3 h-3 text-bambu-green"})," ",d("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(yhe,{className:"w-3 h-3"})," ",d("inventory.cloudNotConnected")]})}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:U,children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:d("inventory.searchPresets"),value:a,onChange:W=>{s(W.target.value),f(!0)},onFocus:()=>{f(!0),s("")}}),h&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:z.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noPresetsFound")}):z.map(W=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${o?.code===W.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>$(W),children:[i.jsx("span",{className:"truncate",children:W.displayName}),i.jsx("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:W.code})]},W.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[d("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:G,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:d("inventory.selectMaterial"),value:y?C:t.material,onChange:W=>{j(W.target.value),_(!0)},onFocus:()=>{_(!0),j("")}}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),y&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ae.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):ae.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",W),_(!1),j("")},children:W},W)),C&&!ae.includes(C)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",C),_(!1),j("")},children:d("inventory.useCustomMaterial",{material:C})})]})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.brand")," *"]}),i.jsxs("div",{className:"relative",ref:R,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:d("inventory.searchBrand"),value:p?N:t.brand,onChange:W=>{k(W.target.value),x(!0)},onFocus:()=>{x(!0),k("")}}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),p&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[K.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):K.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",W),x(!1),k("")},children:W},W)),N&&!K.includes(N)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",N),x(!1),k("")},children:d("inventory.useCustomBrand",{brand:N})})]})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.subtype")," *"]}),i.jsxs("div",{className:"relative",ref:V,children:[i.jsx("input",{type:"text",value:v?A:t.subtype,onChange:W=>{M(W.target.value),g(!0)},onFocus:()=>{g(!0),M("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),v&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[Y.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):Y.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",W),g(!1),M("")},children:W},W)),A&&!lv.some(W=>W.toLowerCase()===A.toLowerCase().trim())&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",A),g(!1),M("")},children:d("inventory.useCustomBrand",{brand:A})})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:d("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:P,min:0,onFocus:()=>O(!0),onChange:W=>E(W.target.value),onBlur:()=>{O(!1);const W=P.trim(),ee=Number(W);if(!W||!Number.isFinite(ee)||ee<0){E(String(t.label_weight));return}const J=Math.round(ee);e("label_weight",J),E(String(J))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]})]})}function TJe({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),h=y=>d.toUpperCase()===y.toUpperCase(),f=(y,_)=>{e("rgba",y.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:y})},p=w.useMemo(()=>{if(a.length===0)return[];const y=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!y&&!_)return[];const k=y?y.toLowerCase().split(/[\s\-_]+/).filter(C=>C.length>=2):[],A=C=>{if(k.length===0)return!0;const j=C.toLowerCase();return k.some(P=>j.includes(P))};if(y&&!_){const C=a.filter(j=>A(j.manufacturer));if(C.length>0)return C.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6),manufacturer:j.manufacturer,material:typeof j.material=="string"?j.material:void 0}))}const M=_&&N?`${_} ${N}`:"";if(M){const C=a.filter(P=>A(P.manufacturer)&&P.material?.toLowerCase()===M);if(C.length>0)return C.map(P=>({name:P.color_name,hex:P.hex_color.replace("#","").substring(0,6),manufacturer:P.manufacturer,material:typeof P.material=="string"?P.material:void 0}));const j=M.replace(/\+$/,"");if(j!==M){const P=a.filter(E=>A(E.manufacturer)&&E.material?.toLowerCase()===j);if(P.length>0)return P.map(E=>({name:E.color_name,hex:E.hex_color.replace("#","").substring(0,6),manufacturer:E.manufacturer,material:typeof E.material=="string"?E.material:void 0}))}}if(_){const C=a.filter(j=>A(j.manufacturer)&&(!j.material||j.material.toLowerCase().startsWith(_)));if(C.length>0)return C.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6),manufacturer:j.manufacturer,material:typeof j.material=="string"?j.material:void 0}))}return[]},[a,t.brand,t.material,t.subtype]),x=w.useMemo(()=>{if(!c)return p;if(p.length===0)return[];const y=c.toLowerCase();return p.filter(N=>N.name.toLowerCase().includes(y)||(N.manufacturer?.toLowerCase().includes(y)??!1)||(N.material?.toLowerCase().includes(y)??!1))},[c,p]),v=p.length>0,g=w.useMemo(()=>c?rK.filter(y=>y.name.toLowerCase().includes(c.toLowerCase())):o?rK:Hie,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Gn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name},y.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:y=>u(y.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[x.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name})},`${y.hex}-${y.name}-${y.manufacturer??""}`)),x.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx(yl,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(Un,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:y.name})},y.hex)),g.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:y=>e("color_name",y.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:y=>{const _=y.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:y=>{const _=y.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function MJe({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),h=w.useRef(null);w.useEffect(()=>{const v=g=>{d.current&&!d.current.contains(g.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(g=>g.weight===e);if(r){const g=t.find(y=>y.id===r);if(g&&g.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const f=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(g=>g.name.toLowerCase().includes(v)||g.weight.toString().includes(v))},[t,c]),p=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),x=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(g=>g.id===r);if(v)return v.name}return p.length>0?p[0].name:""},[o,c,r,t,p]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Bfe,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:h,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:x,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:f.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):f.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const g=parseInt(v.target.value);!isNaN(g)&&g>=0&&n(g)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function PJe({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Ut(),{showToast:s}=cn(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,h]=w.useState(""),[f,p]=w.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+x;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{f||h(String(x))},[f,x]),i.jsxs("div",{className:"space-y-4",children:[i.jsx(MJe,{catalog:n,value:t.core_weight,onChange:g=>e("core_weight",g),catalogId:t.core_weight_catalog_id,onCatalogIdChange:g=>e("core_weight_catalog_id",g)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>p(!0),onChange:g=>{h(g.target.value)},onBlur:()=>{p(!1);const g=d.trim(),y=Number(g);if(!g||!Number.isFinite(y)||y<0||y>t.label_weight){h(String(x));return}const _=Math.round(y);e("weight_used",Math.max(0,t.label_weight-_)),h(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:g=>{l(g.target.value)},onBlur:()=>{u(!1);const g=o.trim(),y=Number(g),_=t.core_weight,N=t.core_weight+t.label_weight;if(!g||!Number.isFinite(y)||y<_||y>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const k=Math.round(y),A=Math.max(0,Math.min(t.label_weight,k-t.core_weight));e("weight_used",Math.max(0,t.label_weight-A)),l(String(k))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:g=>{const y=g.target.value===""?null:parseFloat(g.target.value);e("cost_per_kg",y)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:a("inventory.notePlaceholder"),value:t.note,onChange:g=>e("note",g.target.value)})]})]})}function EJe({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Ut(),l=f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},c=(f,p,x)=>{const v=`${f}:${p}:${x??"null"}`,g=`${f}:${x??"null"}`;r(y=>{const _=new Set(y);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const k=N.split(":");`${k[0]}:${k[2]}`===g&&_.delete(N)}_.add(v)}return _})},u=()=>{const f=new Set;for(const{printer:p,calibrations:x}of e){if(!p.connected)continue;const v=x.filter(y=>Ej(y,t)),g=new Map;for(const y of v){const _=`${y.extruder_id??"null"}`;g.has(_)||g.set(_,[]),g.get(_).push(y)}for(const[y,_]of g)if(_.length>0){const k=[..._].sort((A,M)=>M.k_value-A.k_value)[0];f.add(`${p.id}:${k.cali_idx}:${y}`)}}r(f)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((f,{printer:p,calibrations:x})=>p.connected?f+x.filter(v=>Ej(v,t)).length:f,0),h=(f,p)=>{const x=`${f.id}:${p.cali_idx}:${p.extruder_id??"null"}`,v=n.has(x);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(f.id),p.cali_idx,p.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:p.name||p.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",p.k_value.toFixed(3)]})})]},`${p.cali_idx}-${p.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(lb,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:f,calibrations:p})=>{const x=a.has(String(f.id)),v=p.filter(k=>Ej(k,t)),g=v.length,y=v.some(k=>k.extruder_id!==void 0&&k.extruder_id!==null&&k.extruder_id>0),_=v.filter(k=>k.extruder_id===1),N=v.filter(k=>k.extruder_id===0||k.extruder_id===void 0||k.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(f.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[x?i.jsx(Un,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(pi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:f.name}),g>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[g," ",o(g!==1?"inventory.matches":"inventory.match")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${f.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:f.connected?o("inventory.connected"):o("inventory.offline")})]}),x&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:f.connected?g===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):y?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(k=>h(f,k))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(k=>h(f,k))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(k=>h(f,k))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},f.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function jJe(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const DJe={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function RJe({spoolId:t}){const{t:e}=Ut(),n=tn(),{showToast:r}=cn(),{data:a,isLoading:s}=Je({queryKey:["spool-usage",t],queryFn:()=>ne.getSpoolUsageHistory(t)}),o=ot({mutationFn:()=>ne.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(it,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Gn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:jJe(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:DJe[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function FJe({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Ut(),o=tn(),{showToast:l}=cn(),c=!!n,[u,d]=w.useState(nK),[h,f]=w.useState({}),[p,x]=w.useState("filament"),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),[A,M]=w.useState([]),[C,j]=w.useState(""),[P,E]=w.useState([]),[B,O]=w.useState([]),[U,R]=w.useState([]),[V,G]=w.useState([]),[z,K]=w.useState([]),[Y,ae]=w.useState(new Set),[$,W]=w.useState(new Set),ee=r.length>0?r:z,J=w.useMemo(()=>Y.size,[Y]);w.useEffect(()=>{G(CJe())},[]),w.useEffect(()=>{t&&((async()=>{k(!0);try{const Q=await ne.getCloudStatus();if(_(Q.is_authenticated),Q.is_authenticated){const L=await ne.getFilamentPresets();M(L)}}catch(Q){console.error("Failed to fetch cloud presets:",Q),_(!1)}finally{k(!1)}})(),ne.getSpoolCatalog().then(E).catch(console.error),ne.getColorCatalog().then(R).catch(console.error),ne.getLocalPresets().then(Q=>O(Q.filament)).catch(console.error),r.length===0&&(async()=>{try{const Q=await ne.getPrinters(),L=await Promise.all(Q.map(H=>ne.getPrinterStatus(H.id).catch(()=>null))),D=[];for(let H=0;H({cali_idx:qe.slot_id,filament_id:qe.filament_id,setting_id:qe.setting_id||"",name:qe.name,k_value:parseFloat(qe.k_value)||0,n_coef:parseFloat(qe.n_coef)||0,extruder_id:qe.extruder_id,nozzle_diameter:qe.nozzle_diameter}))}catch{}D.push({printer:{...he,connected:fe},calibrations:ze})}K(D)}catch(Q){console.error("Failed to fetch printer calibrations:",Q)}})())},[t,r.length]);const ye=w.useMemo(()=>_Je(A,new Set,B),[A,B]),me=w.useMemo(()=>{const pe=wJe(A,B),Q=U.map(D=>D.manufacturer?.trim()).filter(D=>!!D),L=new Set([...pe,...Q]);return Array.from(L).sort((D,H)=>D.localeCompare(H))},[A,B,U]),te=w.useMemo(()=>{const pe=U.map(L=>L.material?.trim()).filter(L=>!!L),Q=new Set([...gJe,...pe]);return Array.from(Q).sort((L,D)=>L.localeCompare(D))},[U]),je=w.useMemo(()=>{const pe=[];for(const Q of U){const L=Q.manufacturer?.trim(),D=Q.material?.trim();L&&D&&pe.push({brand:L,material:D})}for(const Q of A){const L=Rb(Q.name);L.brand&&L.material&&pe.push({brand:L.brand,material:L.material})}for(const Q of B){const L=Rb(Q.name),D=Q.filament_vendor?.trim()||L.brand,H=L.material;D&&H&&pe.push({brand:D,material:H})}return pe},[A,U,B]),ue=w.useMemo(()=>{const pe=new Map;for(const Q of je){const L=Q.brand.toLowerCase(),D=Q.material.toLowerCase();pe.has(L)||pe.set(L,new Set),pe.get(L).add(D)}return pe},[je]),oe=w.useMemo(()=>{const pe=new Map;for(const Q of je){const L=Q.brand.toLowerCase(),D=Q.material.toLowerCase();pe.has(D)||pe.set(D,new Set),pe.get(D).add(L)}return pe},[je]),_e=w.useMemo(()=>{if(!u.material)return me;const pe=u.material.toLowerCase(),Q=oe.get(pe);return!Q||Q.size===0?me:me.filter(L=>Q.has(L.toLowerCase()))},[me,u.material,oe]),se=w.useMemo(()=>{if(!u.brand)return te;const pe=u.brand.toLowerCase(),Q=ue.get(pe);return!Q||Q.size===0?te:te.filter(L=>Q.has(L.toLowerCase()))},[te,u.brand,ue]),Oe=w.useMemo(()=>NJe(u.slicer_filament,ye),[u.slicer_filament,ye]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),j(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const pe=new Set;for(const Q of n.k_profiles)Q.cali_idx!==null&&Q.cali_idx!==void 0&&pe.add(`${Q.printer_id}:${Q.cali_idx}:${Q.extruder??"null"}`);ae(pe)}else ae(new Set);else d(nK),j(""),ae(new Set);f({}),x("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&ee.length>0&&W(new Set(ee.map(pe=>String(pe.printer.id))))},[t,ee]);const q=(pe,Q)=>{d(L=>({...L,[pe]:Q})),pe==="weight_used"&&g(!0),h[pe]&&f(L=>({...L,[pe]:void 0}))},X=pe=>{G(Q=>kJe(pe,Q))},de=ot({mutationFn:pe=>ne.createSpool(pe),onSuccess:async pe=>{Y.size>0&&pe?.id&&await ie(pe.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:pe=>{l(pe.message,"error")}}),Z=ot({mutationFn:pe=>ne.updateSpool(n.id,pe),onSuccess:async()=>{n?.id&&await ie(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:pe=>{l(pe.message,"error")}}),ie=async pe=>{if(Y.size===0){try{await ne.saveSpoolKProfiles(pe,[])}catch{}return}const Q=[];for(const L of Y){const[D,H,he]=L.split(":"),be=parseInt(D),fe=parseInt(H),ze=he==="null"?0:parseInt(he),Ie=ee.find(qe=>qe.printer.id===be);if(Ie){const qe=Ie.calibrations.find(tt=>tt.cali_idx===fe);qe&&Q.push({printer_id:be,extruder:ze,nozzle_diameter:qe.nozzle_diameter||"0.4",k_value:qe.k_value,name:qe.name||null,cali_idx:qe.cali_idx,setting_id:qe.setting_id||null})}}if(Q.length>0)try{await ne.saveSpoolKProfiles(pe,Q)}catch(L){console.error("Failed to save K-profiles:",L)}};if(w.useEffect(()=>{if(!t)return;const pe=Q=>{Q.key==="Escape"&&e()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[t,e]),!t)return null;const le=()=>{const pe=pJe(u);if(!pe.isValid){f(pe.errors),(pe.errors.slicer_filament||pe.errors.material||pe.errors.brand||pe.errors.subtype)&&x("filament");return}const Q=Oe?.displayName||C||null,L={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Q,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(L.weight_used=u.weight_used),c?Z.mutate(L):de.mutate(L)},Fe=de.isPending||Z.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>x("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(VC,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),i.jsxs("button",{onClick:()=>x("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Ede,{className:"w-4 h-4"}),s("inventory.paProfileTab"),J>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:J})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:p==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(AJe,{formData:u,updateField:q,cloudAuthenticated:y,loadingCloudPresets:N,presetInputValue:C,setPresetInputValue:j,selectedPresetOption:Oe,filamentOptions:ye,availableBrands:_e,availableMaterials:se}),h.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.slicer_filament}),h.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.material}),h.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.brand}),h.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.subtype})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(TJe,{formData:u,updateField:q,recentColors:V,onColorUsed:X,catalogColors:U})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx(PJe,{formData:u,updateField:q,spoolCatalog:P,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(RJe,{spoolId:n.id})})]}):i.jsx(EJe,{formData:u,updateField:q,printersWithCalibrations:ee,selectedProfiles:Y,setSelectedProfiles:ae,expandedPrinters:$,setExpandedPrinters:W})}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ce,{onClick:le,disabled:Fe,children:Fe?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})}function LJe({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Ut(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(k=>({...k})))},[t,n]),w.useEffect(()=>{if(!t)return;const k=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,e]),!t)return null;const h=k=>{l(A=>A.map((M,C)=>C===k?{...M,visible:!M.visible}:M))},f=(k,A)=>{A<0||A>=o.length||l(M=>{const C=[...M],[j]=C.splice(k,1);return C.splice(A,0,j),C})},p=(k,A)=>{d.current=A,u(A),k.dataTransfer.effectAllowed="move"},x=(k,A)=>{k.preventDefault(),k.dataTransfer.dropEffect="move";const M=d.current;M!==null&&M!==A&&(f(M,A),d.current=A,u(A))},v=k=>{k.preventDefault()},g=()=>{d.current=null,u(null)},y=()=>{l(r.map(k=>({...k})))},_=()=>{a(o),e()},N=o.filter(k=>k.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(vt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:k=>k.stopPropagation(),children:i.jsxs(_t,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((k,A)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===A?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${k.visible?"":"opacity-50"}`,draggable:!0,onDragStart:M=>p(M,A),onDragOver:M=>x(M,A),onDrop:v,onDragEnd:g,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Ph,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:k.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>f(A,A-1),disabled:A===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:i.jsx(yl,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>f(A,A+1),disabled:A===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:i.jsx(Un,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>h(A),className:`p-1.5 rounded transition-colors ${k.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:k.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:k.visible?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(o0,{className:"w-4 h-4"})})]},k.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(Ce,{variant:"secondary",onClick:y,className:"mr-auto",children:[i.jsx(Fo,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(Ce,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(Ce,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}const Vie="bambuddy-inventory-columns",c1=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"cost_per_kg",label:"Cost/kg",visible:!1}];function OJe(){try{const t=localStorage.getItem(Vie);if(t){const e=JSON.parse(t),n=new Set(c1.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=c1.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return c1.map(t=>({...t}))}function IJe(t){try{localStorage.setItem(Vie,JSON.stringify(t))}catch{}}function Ru(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const zJe={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function jj(t,e="system"){if(!t)return"-";const n=di(t);return n?o3(n,e):"-"}const UJe={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",remaining:t=>t("inventory.remaining"),cost_per_kg:t=>t("inventory.costPerKg")},BJe={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:jj(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:jj(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?jj(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:one(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=cI(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:Ru(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:Ru(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:Ru(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Ru(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"})},Dj={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];if(!n)return"";const r=n.ams_id===254||n.ams_id===255,a=!r&&n.ams_id>=128;return`${n.printer_name||""} ${cI(n.ams_id,n.tray_id,a,r)}`},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase(),cost_per_kg:t=>t.cost_per_kg??0},nF="bambuddy-inventory-sort";function HJe(){try{const t=localStorage.getItem(nF);if(t)return JSON.parse(t)}catch{}return null}function $Je(t){try{t?localStorage.setItem(nF,JSON.stringify(t)):localStorage.removeItem(nF)}catch{}}function VJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),[r,a]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[h,f]=w.useState(""),[p,x]=w.useState(""),[v,g]=w.useState(""),[y,_]=w.useState("table"),[N,k]=w.useState(HJe),[A,M]=w.useState(OJe),[C,j]=w.useState(!1),[P,E]=w.useState(0),[B,O]=w.useState(()=>{try{const Q=localStorage.getItem("bambuddy-inventory-pageSize");if(Q){const L=Number(Q);if([15,30,50,100,-1].includes(L))return L}}catch{}return 15}),{data:U}=Je({queryKey:["settings"],queryFn:ne.getSettings}),R=U?.date_format||"system",{data:V,isLoading:G}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!0),refetchInterval:3e4}),{data:z}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),refetchInterval:3e4}),K=ot({mutationFn:Q=>ne.deleteSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),Y=ot({mutationFn:Q=>ne.archiveSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),ae=ot({mutationFn:Q=>ne.restoreSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),$=w.useMemo(()=>{if(!V)return null;let Q=0,L=0,D=0,H=0;const he={};for(const be of V){if(be.archived_at)continue;H++;const fe=Math.max(0,be.label_weight-be.weight_used);Q+=fe,L+=be.weight_used,(be.label_weight>0?fe/be.label_weight*100:0)<20&&D++;const Ie=be.material||"Unknown";he[Ie]||(he[Ie]={count:0,weight:0}),he[Ie].count++,he[Ie].weight+=fe}return{totalWeight:Q,totalConsumed:L,lowStock:D,byMaterial:he,totalSpools:H}},[V]),W=z?.length??0,ee=rl(U?.currency||"USD"),J=w.useMemo(()=>{const Q={};for(const L of z||[])Q[L.spool_id]=L;return Q},[z]),ye=w.useMemo(()=>$?Object.entries($.byMaterial).sort((Q,L)=>L[1].weight-Q[1].weight).slice(0,4):[],[$]),me=w.useMemo(()=>{let Q=V||[];if(l==="active"?Q=Q.filter(L=>!L.archived_at):Q=Q.filter(L=>!!L.archived_at),u==="used"?Q=Q.filter(L=>L.weight_used>0):u==="new"&&(Q=Q.filter(L=>L.weight_used===0)),h&&(Q=Q.filter(L=>L.material===h)),p&&(Q=Q.filter(L=>L.brand===p)),v){const L=v.toLowerCase();Q=Q.filter(D=>D.brand?.toLowerCase().includes(L)||D.material.toLowerCase().includes(L)||D.color_name?.toLowerCase().includes(L)||D.subtype?.toLowerCase().includes(L)||D.note?.toLowerCase().includes(L)||D.slicer_filament_name?.toLowerCase().includes(L))}return Q},[V,l,u,h,p,v]),te=()=>E(0),je=[...new Set(V?.map(Q=>Q.material)||[])].sort(),ue=[...new Set(V?.map(Q=>Q.brand).filter(Boolean)||[])].sort(),oe=l!=="active"||u!=="all"||!!h||!!p||!!v,_e=Q=>{M(Q),IJe(Q)},se=w.useMemo(()=>A.filter(Q=>Q.visible).map(Q=>Q.id),[A]),Oe=Q=>{Dj[Q]&&(k(L=>{let D;return L?.column===Q?D=L.direction==="asc"?{column:Q,direction:"desc"}:null:D={column:Q,direction:"asc"},$Je(D),D}),te())},q=w.useMemo(()=>{if(!N)return me;const Q=Dj[N.column];return Q?[...me].sort((D,H)=>{const he=Q(D,J),be=Q(H,J);return hebe?N.direction==="asc"?1:-1:0}):me},[me,N,J]),X=B===-1,de=X?q.length||1:B,Z=Math.max(1,Math.ceil(q.length/de)),ie=X?0:Math.min(P,Z-1),le=X?q:q.slice(ie*de,(ie+1)*de),Fe=Q=>{O(Q),E(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Q))}catch{}},pe=()=>{c("active"),d("all"),f(""),x(""),g(""),te()};return i.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(fi,{className:"w-6 h-6 text-bambu-green"}),i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),i.jsxs(Ce,{onClick:()=>a({spool:null}),children:[i.jsx(Xn,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),$&&!G&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(fi,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Ru($.totalWeight,!0)}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[$.totalSpools," ",$.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(CF,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Ru($.totalConsumed,!0)}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(mi,{className:"w-4 h-4 text-green-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:ye.map(([Q,L])=>i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${zJe[Q]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Q," ",i.jsx("span",{className:"opacity-70",children:Ru(L.weight,!0)})]},Q))})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(xr,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:W}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),i.jsx("div",{className:`text-xl font-bold ${$.lowStock>0?"text-yellow-400":"text-white"}`,children:$.lowStock}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.lowStockThreshold")})]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[i.jsxs("div",{className:"relative flex-1 max-w-md",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),i.jsx("input",{type:"text",value:v,onChange:Q=>{g(Q.target.value),te()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),v&&i.jsx("button",{onClick:()=>{g(""),te()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[y==="table"&&i.jsxs("button",{onClick:()=>j(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[i.jsx(Ehe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),i.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>_("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(mpe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),i.jsxs("button",{onClick:()=>_("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(c0,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("button",{onClick:()=>{c("active"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(fi,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),i.jsxs("button",{onClick:()=>{c("archived"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(js,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{d("all"),te()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsxs("button",{onClick:()=>{d("used"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),i.jsx("button",{onClick:()=>{d("new"),te()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("select",{value:h,onChange:Q=>{f(Q.target.value),te()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${h?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.material")}),je.map(Q=>i.jsx("option",{value:Q,children:Q},Q))]}),i.jsxs("select",{value:p,onChange:Q=>{x(Q.target.value),te()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${p?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.brand")}),ue.map(Q=>i.jsx("option",{value:Q,children:Q},Q))]}),oe&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("button",{onClick:pe,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[i.jsx(Ft,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),i.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[q.length," ",q.length!==1?t("inventory.spools"):t("inventory.spool")]})]}),G?i.jsx("div",{className:"flex justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):y==="cards"?le.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:le.map(Q=>{const L=Math.max(0,Q.label_weight-Q.weight_used),D=Q.label_weight>0?L/Q.label_weight*100:0,H=Q.rgba?`#${Q.rgba.substring(0,6)}`:"#808080";return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>a({spool:Q}),children:[i.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:H},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:one(Q.color_name,Q.rgba)||"-"})}),i.jsxs("div",{className:"p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[Q.material,Q.subtype?` ${Q.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:Q.brand||"-"})]}),i.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",Q.id]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[i.jsx("span",{children:t("inventory.remaining")}),i.jsxs("span",{children:[Math.round(D),"%"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${D>50?"bg-bambu-green":D>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(D,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(L),"g"]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.labelWeight"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Ru(Q.label_weight)})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.weightUsed"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Q.weight_used>0?Ru(Q.weight_used):"-"})]})]}),Q.note&&i.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:Q.note,children:Q.note})]})]},Q.id)})}),i.jsx(qJe,{pageIndex:ie,pageSize:B,totalRows:q.length,totalPages:Z,onPageChange:E,onPageSizeChange:Fe,t})]}):i.jsx(aK,{hasFilters:oe,onAddSpool:()=>a({spool:null}),t}):le.length>0?i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[se.map(Q=>{const L=!!Dj[Q],D=N?.column===Q;return i.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Q==="remaining"?"min-w-[150px]":""} ${L?"cursor-pointer hover:text-bambu-green transition-colors":""} ${D?"text-bambu-green":"text-bambu-gray"}`,onClick:L?()=>Oe(Q):void 0,children:i.jsxs("span",{className:"inline-flex items-center gap-1",children:[UJe[Q]?.(t)??Q,L&&(D?N.direction==="asc"?i.jsx(Af,{className:"w-3 h-3"}):i.jsx(ib,{className:"w-3 h-3"}):i.jsx(vF,{className:"w-3 h-3 opacity-30"}))]})},Q)}),i.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),i.jsx("tbody",{children:le.map(Q=>{const L=Math.max(0,Q.label_weight-Q.weight_used),D=Q.label_weight>0?L/Q.label_weight*100:0;return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>a({spool:Q}),children:[se.map(H=>i.jsx("td",{className:"py-3 px-4",children:BJe[H]?.({spool:Q,remaining:L,pct:D,assignmentMap:J,currencySymbol:ee,dateFormat:R})},H)),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:H=>H.stopPropagation(),children:[i.jsx("button",{onClick:()=>a({spool:Q}),className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("inventory.editSpool"),children:i.jsx(Jm,{className:"w-4 h-4"})}),Q.archived_at?i.jsx("button",{onClick:()=>ae.mutate(Q.id),className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:t("inventory.restore"),children:i.jsx(Fo,{className:"w-4 h-4"})}):i.jsx("button",{onClick:()=>o({type:"archive",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:t("inventory.archive"),children:i.jsx(js,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>o({type:"delete",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:t("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]},Q.id)})})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:X?`${q.length} ${q.length!==1?t("inventory.spools"):t("inventory.spool")}`:i.jsxs(i.Fragment,{children:[t("inventory.showing")," ",ie*de+1," ",t("inventory.to")," ",Math.min((ie+1)*de,q.length)," ",t("inventory.of")," ",q.length," ",t("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),i.jsxs("select",{value:B,onChange:Q=>Fe(Number(Q.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(Q=>i.jsx("option",{value:Q,children:Q},Q)),i.jsx("option",{value:-1,children:t("inventory.all")})]}),!X&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>E(0),disabled:ie===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:i.jsx(eX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>E(Q=>Math.max(0,Q-1)),disabled:ie===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",ie+1," ",t("inventory.of")," ",Z]}),i.jsx("button",{onClick:()=>E(Q=>Math.min(Z-1,Q+1)),disabled:ie>=Z-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>E(Z-1),disabled:ie>=Z-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:i.jsx(tX,{className:"w-4 h-4"})})]})]})]})]}):i.jsx(aK,{hasFilters:oe,onAddSpool:()=>a({spool:null}),t}),r!==null&&i.jsx(FJe,{isOpen:!0,onClose:()=>a(null),spool:r.spool,currencySymbol:ee}),s&&i.jsx(gn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?K.mutate(s.spoolId):Y.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),i.jsx(LJe,{isOpen:C,onClose:()=>j(!1),columns:A,defaultColumns:c1,onSave:_e})]})}function qJe({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:a,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return i.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),i.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>i.jsx("option",{value:u,children:u},u)),i.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>a(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(eX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),i.jsx("button",{onClick:()=>a(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(tX,{className:"w-4 h-4"})})]})]})]})}function aK({hasFilters:t,onAddSpool:e,t:n}){return i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[i.jsxs("div",{className:"relative mb-6",children:[i.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),i.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[i.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),i.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?i.jsx(kr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:i.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),i.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:i.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),i.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&i.jsxs(Ce,{onClick:e,children:[i.jsx(fi,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const iK=["DEBUG","INFO","WARNING","ERROR"],Rj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},GJe={DEBUG:OC,INFO:Zs,WARNING:Tn,ERROR:Ba};function WJe(){const t=tn(),[e,n]=w.useState(!0),[r,a]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[h,f]=w.useState(!1),p=w.useRef(null),{data:x,isLoading:v,refetch:g}=Je({queryKey:["application-logs",l,s],queryFn:()=>qg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});w.useEffect(()=>{u||f(!1)},[u]);const y=ot({mutationFn:()=>qg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&p.current&&x?.entries&&(p.current.scrollTop=p.current.scrollHeight)},[x?.entries,e]);const _=C=>{a(j=>{const P=new Set(j);return P.has(C)?P.delete(C):P.add(C),P})},N=C=>{const j=C.split(" ");return j.length>=2?j[1]:C},k=w.useMemo(()=>x?.entries??[],[x?.entries]),A=w.useMemo(()=>[...k].reverse(),[k]),M=({level:C})=>{const j=GJe[C]||Zs;return i.jsx(j,{className:`w-3.5 h-3.5 ${Rj[C]||"text-gray-400"}`})};return i.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${h?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(OC,{className:"w-5 h-5"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:h?`Live streaming - ${x?.filtered_count??0} entries`:"View and filter application logs"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[h&&i.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[i.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?i.jsx(yl,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(Un,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h?i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!1)},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded transition-colors",children:[i.jsx(vl,{className:"w-4 h-4"}),"Stop"]}):i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!0),g()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[i.jsx(io,{className:"w-4 h-4"}),"Start"]}),i.jsxs("button",{onClick:()=>y.mutate(),disabled:y.isPending||k.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:[i.jsx(Jt,{className:"w-4 h-4"}),"Clear"]}),i.jsx("button",{onClick:()=>g(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:i.jsx(Cr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:e,onChange:C=>n(C.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[x?.filtered_count??0,"/",x?.total_in_file??0]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:C=>o(C.target.value),className:"w-full pl-8 pr-8 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),s&&i.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>c("ALL"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${l==="ALL"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"All"}),iK.map((C,j)=>i.jsx("button",{onClick:()=>c(C),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${j===iK.length-1?"rounded-r":""} ${l===C?`${Rj[C]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:C},C))]})]})]}),i.jsx("div",{ref:p,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:k.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:"No log entries found"}),i.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:A.map((C,j)=>{const P=r.has(j),E=C.message.includes(` +`+n+"}"}return String(t)}function RZe({setting:t,onClose:e,onDeleted:n,onDuplicate:r,onEdit:a,hasPermission:s,t:o}){const{showToast:l}=cn(),c=tn(),[u,d]=w.useState(!1),{data:h,isLoading:f}=Je({queryKey:["cloudSettingDetail",t.setting_id],queryFn:()=>ne.getCloudSettingDetail(t.setting_id)}),p=ot({mutationFn:()=>ne.deleteCloudSetting(t.setting_id),onSuccess:()=>{l(o("profiles.presets.toast.deleted")),c.invalidateQueries({queryKey:["cloudSettings"]}),n()},onError:g=>l(g.message,"error")}),x=r0(t.setting_id),v=s4(t.name,h?.setting?.inherits);return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-3xl max-h-[90vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h2",{className:"text-xl font-semibold text-white truncate",children:t.name}),x&&i.jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-bambu-green/20 text-bambu-green rounded-full",children:o("profiles.presets.editable")})]}),i.jsxs("div",{className:"flex items-center gap-2 mt-1 text-sm text-bambu-gray",children:[i.jsx("span",{className:"capitalize",children:o(`profiles.presets.types.${t.type}`)}),v.printer&&i.jsxs(i.Fragment,{children:[i.jsx("span",{children:"•"}),i.jsx("span",{children:v.printer})]})]})]}),i.jsx("button",{onClick:e,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto p-4",children:f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.jsx("pre",{className:"text-xs text-bambu-gray font-mono whitespace-pre-wrap break-all bg-bambu-dark p-4 rounded-lg border border-bambu-dark-tertiary overflow-x-auto max-w-full",children:eF(h)}):i.jsx("div",{className:"text-center py-16 text-bambu-gray",children:o("profiles.presets.failedToLoadDetails")})}),u?i.jsxs("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary bg-red-500/5",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 text-red-400",children:[i.jsx(Tn,{className:"w-5 h-5"}),i.jsx("span",{className:"font-medium",children:o("profiles.presets.deleteConfirm")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:o("profiles.presets.deleteWarning",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>d(!1),disabled:p.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(Ce,{variant:"danger",onClick:()=>p.mutate(),disabled:p.isPending,className:"flex-1",children:[p.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):i.jsx(Jt,{className:"w-4 h-4"}),o("common.delete")]})]})]}):i.jsx("div",{className:"flex-shrink-0 p-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(Ce,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(Yl,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&i.jsxs(i.Fragment,{children:[i.jsxs(Ce,{variant:"secondary",onClick:a,disabled:f||!h||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noEditPermission"),children:[i.jsx($a,{className:"w-4 h-4"}),o("common.edit")]}),i.jsx(Ce,{variant:"danger",onClick:()=>d(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDeletePermission"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]})})]})})})}function Oie(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Iie(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function FZe({onClose:t,onApply:e,t:n}){const{showToast:r}=cn(),[a,s]=w.useState(Oie),[o,l]=w.useState("all"),[c,u]=w.useState(null),[d,h]=w.useState(""),[f,p]=w.useState(""),[x,v]=w.useState("{}"),[g,y]=w.useState(null),[_,N]=w.useState(null),k=o==="all"?a:a.filter(U=>U.type===o),A=U=>{s(U),Iie(U)},M=U=>{const R=a.filter(V=>V.id!==U);A(R),N(null),r(n("profiles.templates.toast.deleted"))},C=U=>{u(U.id),h(U.name),p(U.description),v(JSON.stringify(U.settings,null,2)),y(null)},j=()=>{if(!(!c||!d.trim()))try{const U=JSON.parse(x),R=a.map(V=>V.id===c?{...V,name:d.trim(),description:f.trim(),settings:U}:V);A(R),u(null),r(n("profiles.templates.toast.updated"))}catch(U){y(U.message)}},P=()=>{u(null),h(""),p(""),v("{}"),y(null)},E=U=>{const R=a.map(V=>V.id===U?{...V,showInModal:!V.showInModal}:V);A(R)},B={filament:{label:n("profiles.presets.types.filament"),icon:IC,color:"text-amber-400"},print:{label:n("profiles.presets.types.process"),icon:ed,color:"text-blue-400"},printer:{label:n("profiles.presets.types.printer"),icon:xr,color:"text-purple-400"}},O=_?a.find(U=>U.id===_):null;return w.useEffect(()=>{const U=R=>{R.key==="Escape"&&(_?N(null):c?P():t())};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[_,c,t]),i.jsxs("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:[O&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-60",children:i.jsx(vt,{className:"w-full max-w-md",children:i.jsxs(_t,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"p-2 bg-red-500/20 rounded-lg",children:i.jsx(Tn,{className:"w-6 h-6 text-red-400"})}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:n("profiles.templates.deleteTitle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("profiles.templates.deleteWarning")})]})]}),i.jsx("p",{className:"text-white mb-6",children:n("profiles.templates.deleteConfirm",{name:O.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(Ce,{onClick:()=>M(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(Jt,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(vt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(lb,{className:"w-5 h-5 text-amber-400"}),n("profiles.templates.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex items-center gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("profiles.templates.typeFilter")}),["all","filament","print","printer"].map(U=>i.jsx("button",{onClick:()=>l(U),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===U?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:U==="all"?n("common.all"):B[U].label},U))]}),i.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:k.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(lb,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:n("profiles.templates.noTemplates")}),i.jsx("p",{className:"text-sm mt-1",children:n("profiles.templates.createFirst")})]}):i.jsx("div",{className:"space-y-2",children:k.map(U=>{const R=B[U.type],V=R.icon;return c===U.id?i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-green",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3",children:[i.jsx("input",{type:"text",value:d,onChange:G=>h(G.target.value),placeholder:n("profiles.templates.namePlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:f,onChange:G=>p(G.target.value),placeholder:n("profiles.templates.descriptionPlaceholder"),className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"text-xs text-bambu-gray mb-1 block",children:n("profiles.templates.settingsJson")}),i.jsx("textarea",{value:x,onChange:G=>{v(G.target.value),y(null)},rows:6,className:`w-full px-3 py-2 bg-bambu-dark-secondary border rounded text-white text-sm font-mono focus:outline-none ${g?"border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`}),g&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:g})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:j,disabled:!d.trim(),children:[i.jsx(ps,{className:"w-4 h-4"}),"Save"]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:P,children:"Cancel"})]})]},U.id):i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary hover:border-bambu-gray-dark transition-colors",children:[i.jsx(V,{className:`w-5 h-5 ${R.color} flex-shrink-0`}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:U.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:U.description})]}),i.jsx("span",{className:"text-xs text-bambu-gray-dark px-2 py-1 bg-bambu-dark-secondary rounded",children:n("profiles.templates.fieldsCount",{count:Object.keys(U.settings).length})}),i.jsx("button",{onClick:()=>E(U.id),className:`p-1 transition-colors ${U.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:U.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:U.showInModal?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(o0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(U),className:"px-3 py-1 text-xs bg-bambu-green/20 text-bambu-green rounded hover:bg-bambu-green/30 transition-colors",children:n("profiles.templates.apply")}),i.jsx("button",{onClick:()=>C(U),className:"p-1 text-bambu-gray hover:text-white",title:n("common.edit"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>N(U.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]},U.id)})})})]})})]})}function zie({onClose:t,leftPreset:e,rightPreset:n,leftLabel:r,rightLabel:a,t:s}){const[o,l]=w.useState("changes"),[c,u]=w.useState(""),d=w.useMemo(()=>{const x=new Set([...Object.keys(e),...Object.keys(n)]),v=[];for(const g of x){if(g==="inherits"||g==="version")continue;const y=e[g],_=n[g],N=g in e,k=g in n;let A;!N&&k?A="added":N&&!k?A="removed":JSON.stringify(y)!==JSON.stringify(_)?A="changed":A="same",v.push({key:g,left:y,right:_,status:A})}return v.sort((g,y)=>{const _={changed:0,added:1,removed:2,same:3};return _[g.status]!==_[y.status]?_[g.status]-_[y.status]:g.key.localeCompare(y.key)})},[e,n]),h=w.useMemo(()=>{let x=[...d];if(o==="changes"&&(x=x.filter(v=>v.status!=="same")),c){const v=c.toLowerCase();x=x.filter(g=>g.key.toLowerCase().includes(v)||String(g.left).toLowerCase().includes(v)||String(g.right).toLowerCase().includes(v))}return x},[d,o,c]),f=w.useMemo(()=>({added:d.filter(x=>x.status==="added").length,removed:d.filter(x=>x.status==="removed").length,changed:d.filter(x=>x.status==="changed").length,same:d.filter(x=>x.status==="same").length}),[d]),p=x=>{if(x===void 0)return"—";if(x===null)return"null";if(Array.isArray(x))return x.length===0?"[]":x.length===1?String(x[0]):x.join(", ");if(typeof x=="object")return JSON.stringify(x);const v=String(x);if(v.includes("\\n")||v.length>100){const g=v.split("\\n").length;if(g>1)return`[${g} lines of G-code/script]`;if(v.length>100)return v.substring(0,100)+"…"}return v};return w.useEffect(()=>{const x=v=>{v.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsx(vt,{className:"w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden",children:i.jsxs(_t,{className:"p-0 flex flex-col min-h-0 flex-1",children:[i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx($g,{className:"w-5 h-5 text-blue-400"}),s("profiles.diff.title")]}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex-shrink-0 grid grid-cols-2 gap-4 p-4 border-b border-bambu-dark-tertiary bg-bambu-dark",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.left")}),i.jsx("p",{className:"text-white font-medium truncate",children:r})]}),i.jsxs("div",{className:"text-center",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:s("profiles.diff.right")}),i.jsx("p",{className:"text-white font-medium truncate",children:a})]})]}),i.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[i.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[i.jsx(Xn,{className:"w-3.5 h-3.5"}),f.added," ",s("profiles.diff.added")]}),i.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[i.jsx(x1,{className:"w-3.5 h-3.5"}),f.removed," ",s("profiles.diff.removed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-amber-400",children:[i.jsx(Qj,{className:"w-3.5 h-3.5"}),f.changed," ",s("profiles.diff.changed")]}),i.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[i.jsx(LM,{className:"w-3.5 h-3.5"}),f.same," ",s("profiles.diff.same")]})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:c,onChange:x=>u(x.target.value),placeholder:s("profiles.diff.searchFields"),className:"pl-8 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none w-48"})]}),f.same>0&&i.jsxs("div",{className:"flex rounded overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>l("changes"),className:`px-3 py-1.5 text-sm transition-colors ${o==="changes"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("profiles.diff.changes")}),i.jsx("button",{onClick:()=>l("all"),className:`px-3 py-1.5 text-sm transition-colors ${o==="all"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:s("common.all")})]})]})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:h.length===0?i.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[i.jsx(LM,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),i.jsx("p",{children:s(o==="changes"?"profiles.diff.noDifferences":"profiles.diff.noFieldsMatch")})]}):i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{className:"sticky top-0 bg-bambu-dark-secondary",children:i.jsxs("tr",{className:"text-sm text-bambu-gray border-b border-bambu-dark-tertiary",children:[i.jsx("th",{className:"text-left p-3 w-1/3",children:s("profiles.diff.field")}),i.jsx("th",{className:"text-left p-3 w-1/3",children:r}),i.jsx("th",{className:"text-left p-3 w-1/3",children:a})]})}),i.jsx("tbody",{children:h.map(x=>{const v={added:"bg-green-500/10",removed:"bg-red-500/10",changed:"bg-amber-500/10",same:""}[x.status],g={added:i.jsx(Xn,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(x1,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(Qj,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx(LM,{className:"w-3.5 h-3.5 text-bambu-gray-dark"})}[x.status];return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary ${v}`,children:[i.jsx("td",{className:"p-3",children:i.jsxs("div",{className:"flex items-center gap-2",children:[g,i.jsx("span",{className:"text-sm text-white font-mono",children:x.key})]})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="removed"?"text-red-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.left)})}),i.jsx("td",{className:"p-3",children:i.jsx("span",{className:`text-sm font-mono break-all ${x.status==="added"?"text-green-300":x.status==="changed"?"text-white":"text-bambu-gray"}`,children:p(x.right)})})]},x.key)})})]})})]})})})}function LZe({onClose:t,initialData:e,allPresets:n,t:r}){const{showToast:a}=cn(),s=tn(),o=!!e?.setting_id,[l,c]=w.useState("common"),[u,d]=w.useState(e?.type||"filament"),[h,f]=w.useState(e?.name?o?e.name:`${e.name} (Copy)`:""),[p,x]=w.useState(e?.base_id||""),[v,g]=w.useState(""),[y,_]=w.useState(e?.setting||{inherits:""}),[N,k]=w.useState(JSON.stringify(e?.setting||{inherits:""},null,2)),[A,M]=w.useState(null),[C,j]=w.useState(""),[P,E]=w.useState(!1),[B,O]=w.useState(""),[U,R]=w.useState(!1),[V,G]=w.useState(Oie),[z,K]=w.useState(!1),[Y,ae]=w.useState(""),[$,W]=w.useState(""),[ee,J]=w.useState(!0),[ye,me]=w.useState(null),[te,je]=w.useState(!1),ue=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),oe=w.useMemo(()=>ue.filter(Me=>r0(Me.setting_id)),[ue]),{data:_e}=Je({queryKey:["cloudFields",u],queryFn:()=>ne.getCloudFields(u==="print"?"process":u),staleTime:1e3*60*60}),{data:se}=Je({queryKey:["allPresetDetails",u,oe.map(Me=>Me.setting_id).join(",")],queryFn:async()=>{const Me={};for(let ve=0;ve{try{const Te=await ne.getCloudSettingDetail(nt.setting_id);return{id:nt.setting_id,detail:Te}}catch{return null}}))).forEach(nt=>{nt&&(Me[nt.id]=nt.detail)})}return Me},enabled:oe.length>0,staleTime:1e3*60*10}),{data:Oe,isLoading:q}=Je({queryKey:["cloudSettingDetail",p],queryFn:()=>ne.getCloudSettingDetail(p),enabled:!!p});w.useEffect(()=>{l!=="json"&&k(JSON.stringify(y,null,2))},[y,l]);const X=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(xe=>!r0(xe.setting_id)).sort((xe,ve)=>xe.name.localeCompare(ve.name)),[n,u]);w.useEffect(()=>{if(!p)return;const Me=X.find(xe=>xe.setting_id===p);Me&&(g(Me.name),o||(_({inherits:Me.name}),k(JSON.stringify({inherits:Me.name},null,2))))},[p,X,o]);const de=w.useMemo(()=>{const Me=_e?.fields||[],xe=new Set(Me.map(nt=>nt.key)),ve=new Set,He=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);se&&Object.values(se).forEach(nt=>{nt?.setting&&Object.keys(nt.setting).forEach(Te=>{!xe.has(Te)&&!He.has(Te)&&ve.add(Te)})}),Object.keys(y).forEach(nt=>{!xe.has(nt)&&!He.has(nt)&&ve.add(nt)});const Pe=Array.from(ve).sort().map(nt=>({key:nt,label:nt.replace(/_/g," ").replace(/\b\w/g,Te=>Te.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Me,...Pe]},[_e,se,y,r]),Z=de.filter(Me=>Me.label.toLowerCase().includes(C.toLowerCase())||Me.key.toLowerCase().includes(C.toLowerCase())),ie=()=>{if(B.trim()){const Me=B.trim().toLowerCase().replace(/\s+/g,"_");le(Me,""),O(""),R(!1),a(r("profiles.presets.toast.fieldAdded",{key:Me}))}},le=(Me,xe)=>{_(ve=>{const He={...ve};return xe===""||xe===void 0?delete He[Me]:He[Me]=xe,He})},Fe=Me=>{_(xe=>({...xe,...Me.settings})),me(Me.name),a(r("profiles.templates.toast.applied"))},pe=()=>{if(!Y.trim())return;const Me={...y};if(delete Me.inherits,Object.keys(Me).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const xe={id:Date.now().toString(),name:Y.trim(),description:$.trim()||r("profiles.presets.customTemplate"),type:u,settings:Me,showInModal:ee},ve=[...V,xe];G(ve),Iie(ve),K(!1),ae(""),W(""),J(!0),a(r("profiles.templates.toast.created"))},Q=w.useMemo(()=>V.filter(Me=>Me.type===u&&Me.showInModal),[u,V]),L=Me=>{k(Me);try{const xe=JSON.parse(Me);_(xe),M(null)}catch(xe){M(xe.message)}},D=Me=>{Me.preventDefault(),E(!1);const xe=Me.dataTransfer.files[0];if(xe&&xe.name.endsWith(".json")){const ve=new FileReader;ve.onload=He=>{try{const Pe=He.target?.result,nt=JSON.parse(Pe),Te=nt.setting||nt;_(Ge=>({...Ge,...Te})),k(JSON.stringify({...y,...Te},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},ve.readAsText(xe)}},H=ot({mutationFn:()=>{const Me={...y},xe=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Me[xe]=`"${h}"`;const ve={type:u,name:h,base_id:p,setting:Me};return ne.createCloudSetting(ve)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>a(Me.message,"error")}),he=ot({mutationFn:()=>{if(!e?.setting_id)throw new Error(r("profiles.presets.noSettingId"));return ne.updateCloudSetting(e.setting_id,{name:h,setting:y})},onSuccess:async()=>{a(r("profiles.presets.toast.updated")),s.removeQueries({queryKey:["cloudSettingDetail"]}),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Me=>a(Me.message,"error")}),be=o?he:H,fe=Oe?.setting?.inherits,ze=fe?X.find(Me=>Me.name===fe):void 0,{data:Ie}=Je({queryKey:["cloudSettingDetail",ze?.setting_id],queryFn:()=>ne.getCloudSettingDetail(ze.setting_id),enabled:!!ze?.setting_id}),qe=w.useMemo(()=>{const Me=Ie?.setting||{},xe=Oe?.setting||{},ve=p&&se?.[p]?.setting?se[p].setting:{};return{...Me,...xe,...ve}},[p,Oe,Ie,se]),tt=Me=>{if(Me==null)return"";if(Array.isArray(Me)){const xe=[...new Set(Me.map(ve=>String(ve)))];return xe.length===1?xe[0]:Me.join(", ")}return String(Me)},Ee=Me=>{const xe=y[Me.key],ve=qe[Me.key],He=tt(ve),Pe=q?r("common.loading"):He||"",nt="w-full px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none";if(Me.type==="boolean"){const Te=xe==="1"||xe===void 0&&ve==="1";return i.jsx("button",{type:"button",onClick:()=>le(Me.key,xe==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${Te?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${Te?"translate-x-3.5":"translate-x-0.5"}`})})}return Me.type==="select"?i.jsxs("select",{value:xe||"",onChange:Te=>le(Me.key,Te.target.value),className:nt,children:[i.jsx("option",{value:"",children:Pe}),Me.options?.map(Te=>i.jsx("option",{value:Te.value,children:Te.label},Te.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Me.type==="number"?"number":"text",value:xe!==void 0?String(xe):"",onChange:Te=>le(Me.key,Te.target.value),step:Me.step,min:Me.min,max:Me.max,placeholder:Pe,className:nt}),Me.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Me.unit})]})},Se=w.useMemo(()=>Oe?.setting?Oe.setting:{},[Oe]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Me=>{Me.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:D,children:[te&&p&&i.jsx(zie,{onClose:()=>je(!1),leftPreset:Se,rightPreset:y,leftLabel:r("profiles.presets.baseLabel",{name:v||p}),rightLabel:r("profiles.presets.currentLabel",{name:h||r("profiles.presets.newPreset")}),t:r}),i.jsx(vt,{className:"w-full max-w-6xl max-h-[90vh] flex flex-col overflow-y-auto",children:i.jsxs(_t,{className:"p-0 flex flex-col h-full",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:r(o?"profiles.presets.editPreset":e?"profiles.presets.duplicatePreset":"profiles.presets.createNewPreset")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("profiles.presets.customizeSettings")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[p&&i.jsxs("button",{onClick:()=>je(!0),className:"flex items-center gap-2 px-3 py-2 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",title:r("profiles.presets.compareWithBase"),children:[i.jsx($g,{className:"w-4 h-4"}),r("profiles.presets.compare")]}),i.jsx("button",{onClick:t,className:"p-2 text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]})]}),P&&i.jsx("div",{className:"absolute inset-0 bg-bambu-green/10 border-2 border-dashed border-bambu-green rounded-lg flex items-center justify-center z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Ra,{className:"w-12 h-12 text-bambu-green mx-auto mb-2"}),i.jsx("p",{className:"text-bambu-green font-medium",children:r("profiles.presets.dropJsonToImport")})]})}),i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-3 gap-4 max-[640px]:grid-cols-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("common.type")}),i.jsxs("select",{value:u,onChange:Me=>{d(Me.target.value),x("")},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:[i.jsx("option",{value:"filament",children:r("profiles.presets.types.filament")}),i.jsx("option",{value:"print",children:r("profiles.presets.types.process")}),i.jsx("option",{value:"printer",children:r("profiles.presets.types.printer")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.basePreset")}),i.jsxs("select",{value:p,onChange:Me=>x(Me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("profiles.presets.selectBasePreset")}),X.map(Me=>i.jsx("option",{value:Me.setting_id,children:Me.name},Me.setting_id))]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("profiles.presets.presetName")}),i.jsx("input",{type:"text",value:h,onChange:Me=>f(Me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("profiles.presets.myCustomPreset")})]})]}),v&&i.jsx("div",{className:"text-xs text-bambu-gray",children:i.jsxs("p",{className:"flex items-center gap-1",children:[i.jsx(ra,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),q&&i.jsx(it,{className:"w-3 h-3 animate-spin ml-1"})]})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary max-[640px]:flex-wrap max-[640px]:items-center",children:[i.jsxs("button",{onClick:()=>c("common"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="common"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(jB,{className:"w-4 h-4"}),r("profiles.presets.tabs.common")]}),i.jsxs("button",{onClick:()=>c("fields"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="fields"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(HC,{className:"w-4 h-4"}),r("profiles.presets.tabs.allFields")]}),i.jsxs("button",{onClick:()=>c("json"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${l==="json"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(nX,{className:"w-4 h-4"}),"JSON",A&&i.jsx(Ba,{className:"w-3 h-3 text-red-400"})]}),i.jsx("div",{className:"flex-1 max-[640px]:hidden"}),i.jsxs("button",{onClick:()=>{const Me={name:h,type:u,base_id:p,setting:y},xe=new Blob([JSON.stringify(Me,null,2)],{type:"application/json"}),ve=URL.createObjectURL(xe),He=document.createElement("a");He.href=ve,He.download=`${h||"preset"}.json`,document.body.appendChild(He),He.click(),document.body.removeChild(He),URL.revokeObjectURL(ve),a(r("profiles.presets.toast.exported"))},className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.exportToJson"),children:[i.jsx(ua,{className:"w-4 h-4"}),r("common.download")]}),i.jsxs("button",{onClick:()=>document.getElementById("file-import")?.click(),className:"flex items-center gap-2 px-4 py-3 text-sm text-bambu-gray hover:text-white transition-colors",title:r("profiles.presets.importFromJson"),children:[i.jsx(Ra,{className:"w-4 h-4"}),r("common.upload")]}),i.jsx("input",{id:"file-import",type:"file",accept:".json",className:"hidden",onChange:Me=>{const xe=Me.target.files?.[0];if(xe){const ve=new FileReader;ve.onload=He=>{try{const Pe=JSON.parse(He.target?.result),nt=Pe.setting||Pe;_(Te=>({...Te,...nt})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},ve.readAsText(xe)}}})]}),i.jsxs("div",{className:"flex-1 p-4",children:[l==="common"&&i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(lb,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(y).filter(Me=>Me!=="inherits").length>0&&i.jsxs("button",{onClick:()=>K(!z),className:"text-xs text-bambu-gray hover:text-white flex items-center gap-1 transition-colors",children:[i.jsx(ps,{className:"w-3 h-3"}),r("profiles.presets.saveAsTemplate")]})]}),z&&i.jsxs("div",{className:"mb-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-2 mb-2",children:[i.jsx("input",{type:"text",value:Y,onChange:Me=>ae(Me.target.value),placeholder:r("profiles.templates.namePlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx("input",{type:"text",value:$,onChange:Me=>W(Me.target.value),placeholder:r("profiles.templates.descriptionPlaceholder"),className:"px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{size:"sm",onClick:pe,disabled:!Y.trim(),children:[i.jsx(ps,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>K(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>J(!ee),className:`flex items-center gap-1.5 text-xs transition-colors ${ee?"text-bambu-green":"text-bambu-gray hover:text-white"}`,children:[ee?i.jsx(Ql,{className:"w-3.5 h-3.5"}):i.jsx(o0,{className:"w-3.5 h-3.5"}),r(ee?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),ye&&i.jsxs("div",{className:"mb-3 px-3 py-2 bg-bambu-green/10 border border-bambu-green/30 rounded-lg flex items-center gap-2",children:[i.jsx(ra,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-sm text-bambu-green",children:[r("profiles.presets.templateApplied")," ",i.jsx("span",{className:"font-medium",children:ye})]}),i.jsx("button",{onClick:()=>me(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[Q.map(Me=>i.jsxs("button",{onClick:()=>Fe(Me),className:"p-3 text-left bg-bambu-dark border border-bambu-dark-tertiary rounded-lg hover:border-bambu-gray-dark transition-colors",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:Me.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Me.description})]},Me.id)),Q.length===0&&i.jsx("p",{className:"col-span-3 text-center text-bambu-gray text-sm py-4",children:r("profiles.presets.noTemplatesSelected")})]}),i.jsx("p",{className:"text-xs text-bambu-gray-dark mt-2 text-center",children:r("profiles.presets.manageTemplatesHint")})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.commonSettings")}),i.jsx("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:de.slice(0,10).map(Me=>i.jsxs("div",{className:"flex items-center justify-between gap-4 max-[640px]:flex-col max-[640px]:items-start",children:[i.jsx("label",{className:"text-sm text-bambu-gray flex-shrink-0",children:Me.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:Ee(Me)})]},Me.key))})]}),Object.keys(y).length>1&&i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:r("profiles.presets.currentOverrides")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(y).filter(([Me])=>Me!=="inherits").map(([Me,xe])=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-green/10 text-bambu-green text-xs rounded",children:[Me,": ",String(xe).slice(0,20),i.jsx("button",{onClick:()=>le(Me,void 0),className:"hover:text-white",children:i.jsx(Ft,{className:"w-3 h-3"})})]},Me))})]})]}),l==="fields"&&i.jsxs("div",{className:"grid grid-cols-2 gap-6",style:{height:"400px"},children:[i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.availableFields")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:se?r("profiles.templates.fieldsCount",{count:de.length}):r("common.loading")})]}),i.jsxs("div",{className:"relative mb-3 flex-shrink-0",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:C,onChange:Me=>j(Me.target.value),placeholder:r("profiles.presets.searchFieldsPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-1 pr-2 min-h-0",children:[Z.filter(Me=>!(Me.key in y)).map(Me=>{const xe=qe[Me.key],ve=tt(xe);return i.jsxs("div",{onClick:()=>{_(He=>({...He,[Me.key]:ve||""}))},className:"flex items-center justify-between gap-2 p-2 rounded-lg hover:bg-bambu-dark-tertiary transition-colors cursor-pointer group",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm text-white truncate",children:Me.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Me.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[ve&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:ve,children:[ve.slice(0,20),ve.length>20?"...":""]}),i.jsx("div",{className:"w-6 h-6 flex items-center justify-center rounded bg-bambu-dark-tertiary group-hover:bg-bambu-green/20 transition-colors",children:i.jsx(Xn,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Me.key)}),Z.filter(Me=>!(Me.key in y)).length===0&&i.jsx("p",{className:"text-center text-bambu-gray py-4 text-sm",children:r(C?"profiles.presets.noMatchingFields":"profiles.presets.allFieldsAdded")})]}),i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:U?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:B,onChange:Me=>O(Me.target.value),onKeyDown:Me=>Me.key==="Enter"&&ie(),placeholder:"custom_field_name",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",autoFocus:!0}),i.jsx(Ce,{size:"sm",onClick:ie,disabled:!B.trim(),children:i.jsx(Xn,{className:"w-4 h-4"})}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>{R(!1),O("")},children:i.jsx(Ft,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>R(!0),className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(Xn,{className:"w-4 h-4"}),r("profiles.presets.addCustomField")]})})]}),i.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3 flex-shrink-0",children:[i.jsx("h3",{className:"text-sm font-medium text-white",children:r("profiles.presets.yourOverrides")}),i.jsx("span",{className:"text-xs text-bambu-gray",children:r("profiles.templates.fieldsCount",{count:Object.keys(y).filter(Me=>Me!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([Me])=>Me!=="inherits").map(([Me,xe])=>{const ve=de.find(He=>He.key===Me);return i.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium text-white",children:ve?.label||Me}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Me})]}),i.jsx("button",{onClick:()=>le(Me,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),ve?Ee(ve):i.jsx("input",{type:"text",value:String(xe),onChange:He=>le(Me,He.target.value),className:"w-full px-3 py-1.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"})]},Me)}),Object.keys(y).filter(Me=>Me!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(jB,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),i.jsx("p",{className:"text-sm",children:r("profiles.presets.noOverridesYet")}),i.jsx("p",{className:"text-xs mt-1",children:r("profiles.presets.clickFieldsToAdd")})]})]}),Object.keys(y).filter(Me=>Me!=="inherits").length>0&&i.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary flex-shrink-0",children:i.jsxs("button",{onClick:()=>{K(!0),c("common")},className:"w-full flex items-center justify-center gap-2 p-2 text-sm text-bambu-gray hover:text-white border border-dashed border-bambu-dark-tertiary hover:border-bambu-gray-dark rounded-lg transition-colors",children:[i.jsx(ps,{className:"w-4 h-4"}),r("profiles.presets.saveAsTemplate")]})})]})]}),l==="json"&&i.jsxs("div",{className:"space-y-2",children:[A&&i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(Ba,{className:"w-4 h-4"}),A]}),i.jsx("textarea",{value:N,onChange:Me=>L(Me.target.value),className:`w-full h-80 px-3 py-2 bg-bambu-dark border rounded-lg text-white text-xs font-mono focus:outline-none resize-none ${A?"border-red-500 focus:border-red-500":"border-bambu-dark-tertiary focus:border-bambu-green"}`,spellCheck:!1}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("profiles.presets.jsonTip")})]})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(Ce,{onClick:()=>be.mutate(),disabled:be.isPending||!h.trim()||!o&&!p||!!A,className:"flex-1",children:[be.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o?i.jsx(ps,{className:"w-4 h-4"}):i.jsx(Xn,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function OZe({settings:t,lastSyncTime:e,onRefresh:n,isRefreshing:r,printers:a,hasPermission:s,t:o}){const[l,c]=w.useState(""),[u,d]=w.useState("all"),[h,f]=w.useState("all"),[p,x]=w.useState("all"),[v,g]=w.useState("all"),[y,_]=w.useState("all"),[N,k]=w.useState("all"),[A,M]=w.useState(null),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[B,O]=w.useState(null),[U,R]=w.useState(null),[V,G]=w.useState(null),[z,K]=w.useState(!1),[Y,ae]=w.useState([null,null]),[$,W]=w.useState(!1),[ee,J]=w.useState(null),ye=tn(),me=w.useMemo(()=>[...t.filament.map(ie=>({...ie,type:"filament"})),...t.printer.map(ie=>({...ie,type:"printer"})),...t.process.map(ie=>({...ie,type:"process"}))].map(ie=>({...ie,meta:s4(ie.name)})),[t]),te=w.useMemo(()=>{const Z=new Set,ie=new Set,le=new Set;return me.forEach(Fe=>{Fe.meta.nozzle&&Z.add(Fe.meta.nozzle),Fe.meta.filamentType&&ie.add(Fe.meta.filamentType),Fe.meta.layerHeight&&le.add(Fe.meta.layerHeight)}),{printers:a.map(Fe=>({id:Fe.id.toString(),name:Fe.name})),nozzles:Array.from(Z).sort((Fe,pe)=>parseFloat(Fe)-parseFloat(pe)),filaments:Array.from(ie).sort(),layerHeights:Array.from(le).sort((Fe,pe)=>parseFloat(Fe)-parseFloat(pe))}},[me,a]),je=w.useMemo(()=>p==="all"?null:a.find(ie=>ie.id.toString()===p)?.model||null,[p,a]),ue=w.useMemo(()=>me.filter(Z=>u==="all"||Z.type===u).filter(Z=>{if(h==="all")return!0;const ie=r0(Z.setting_id);return h==="custom"?ie:!ie}).filter(Z=>{if(p==="all"||!je)return!0;const ie=Z.meta.printer?.toLowerCase()||"",le=je.toLowerCase();return ie.includes(le)||le.includes(ie)}).filter(Z=>v==="all"||Z.meta.nozzle===v).filter(Z=>y==="all"||Z.meta.filamentType===y).filter(Z=>N==="all"||Z.meta.layerHeight===N).filter(Z=>l===""||Z.name.toLowerCase().includes(l.toLowerCase())).sort((Z,ie)=>Z.name.localeCompare(ie.name)),[me,u,h,p,je,v,y,N,l]),oe=Z=>{if(z){const ie=Y[0]?.setting_id===Z.setting_id,le=Y[1]?.setting_id===Z.setting_id;if(ie)ae([Y[1],null]);else if(le)ae([Y[0],null]);else if(!Y[0])ae([Z,null]);else if(Y[1]){if(Y[0].type!==Z.type)return;ae([Y[0],Z])}else{if(Y[0].type!==Z.type)return;ae([Y[0],Z])}}else M(Z)},_e=Z=>{if(Y[0]?.setting_id===Z.setting_id)return 0;if(Y[1]?.setting_id===Z.setting_id)return 1},se=async Z=>{try{const ie=await ne.getCloudSettingDetail(Z.setting_id),le=Z.type==="process"?"print":Z.type;O({type:le,name:Z.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{}}),M(null)}catch(ie){console.error("Failed to fetch preset details for duplication:",ie)}},Oe=async Z=>{try{ye.removeQueries({queryKey:["cloudSettingDetail",Z.setting_id]});const ie=await ne.getCloudSettingDetail(Z.setting_id),le=Z.type==="process"?"print":Z.type;R({type:le,name:Z.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{},setting_id:Z.setting_id}),M(null)}catch(ie){console.error("Failed to fetch preset details for editing:",ie)}},q=()=>{d("all"),f("all"),x("all"),g("all"),_("all"),k("all"),c("")},X=u!=="all"||h!=="all"||p!=="all"||v!=="all"||y!=="all"||N!=="all"||l!=="",de=t.filament.length+t.printer.length+t.process.length;return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"space-y-4 mb-6",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",value:l,onChange:Z=>c(Z.target.value),placeholder:o("profiles.cloudView.searchPlaceholder"),className:"w-full pl-10 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none"})]}),i.jsxs("div",{className:"flex gap-2 max-[550px]:flex-wrap max-[550px]:items-center",children:[i.jsxs(Ce,{variant:z?"primary":"secondary",onClick:()=>{z?(K(!1),ae([null,null])):K(!0)},children:[i.jsx($g,{className:"w-4 h-4"}),o(z?"common.cancel":"profiles.presets.compare")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(lb,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(Ce,{variant:"secondary",onClick:n,disabled:r||!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noRefreshPermission"),children:[i.jsx(Cr,{className:`w-4 h-4 ${r?"animate-spin":""}`}),o("profiles.cloudView.refresh")]}),i.jsxs(Ce,{onClick:()=>j(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx(UC,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(Ag,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:de},{value:"filament",label:o("profiles.cloudView.filters.filament"),count:t.filament.length},{value:"printer",label:o("profiles.cloudView.filters.printer"),count:t.printer.length},{value:"process",label:o("profiles.cloudView.filters.process"),count:t.process.length}],onChange:Z=>d(Z)}),i.jsx(Ag,{label:o("profiles.cloudView.filters.owner"),value:h,options:[{value:"all",label:o("profiles.cloudView.filters.all")},{value:"custom",label:o("profiles.cloudView.filters.myPresets")},{value:"builtin",label:o("profiles.cloudView.filters.builtIn")}],onChange:Z=>f(Z)}),te.printers.length>0&&i.jsx(Ag,{label:o("profiles.cloudView.filters.printer"),value:p,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.printers.map(Z=>({value:Z.id,label:Z.name}))],onChange:x}),te.nozzles.length>0&&i.jsx(Ag,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.nozzles.map(Z=>({value:Z,label:Z}))],onChange:g}),te.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(Ag,{label:o("profiles.cloudView.filters.filament"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.filaments.map(Z=>({value:Z,label:Z}))],onChange:_}),te.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(Ag,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...te.layerHeights.map(Z=>({value:Z,label:Z}))],onChange:k}),X&&i.jsx("button",{onClick:q,className:"px-3 py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:o("profiles.cloudView.clearFilters")})]})]}),z&&i.jsx("div",{className:"mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx($g,{className:"w-5 h-5 text-blue-400"}),i.jsx("span",{className:"text-white font-medium",children:o("profiles.cloudView.compareMode")}),i.jsx("span",{className:"text-bambu-gray",children:Y[0]?o("profiles.cloudView.selectAnotherPreset",{type:Y[0].type}):o("profiles.cloudView.clickTwoPresets")})]}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[0]?Y[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(Qj,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${Y[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:Y[1]?Y[1].name:o("profiles.cloudView.selectSecond")})]}),Y[0]&&Y[1]&&i.jsxs(Ce,{size:"sm",onClick:async()=>{try{const[Z,ie]=await Promise.all([ne.getCloudSettingDetail(Y[0].setting_id),ne.getCloudSettingDetail(Y[1].setting_id)]);J([Z.setting||{},ie.setting||{}]),W(!0)}catch{}},children:[i.jsx($g,{className:"w-4 h-4"}),o("profiles.cloudView.compareNow")]})]})]})}),i.jsxs("div",{className:"flex flex-wrap items-center gap-4 mb-4 text-sm text-bambu-gray",children:[e&&i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx(Gn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",gv(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:ue.length,total:de})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-bambu-green"}),i.jsxs("span",{children:["= ",o("profiles.presets.myPreset")]})]})]}),ue.length===0?i.jsxs("div",{className:"text-center py-16",children:[i.jsx(mi,{className:"w-12 h-12 text-bambu-gray-dark mx-auto mb-4"}),i.jsx("p",{className:"text-bambu-gray",children:o("profiles.cloudView.noPresetsFound")}),X&&i.jsx("button",{onClick:q,className:"mt-2 text-sm text-bambu-green hover:text-bambu-green-light",children:o("profiles.cloudView.clearFilters")})]}):i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-6",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(IC,{className:"w-4 h-4 text-amber-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.filament")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="filament").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="filament").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noFilamentPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(ed,{className:"w-4 h-4 text-blue-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.process")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="process").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="process").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noProcessPresets")})]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 mb-3 px-1",children:[i.jsx(xr,{className:"w-4 h-4 text-purple-400"}),i.jsx("h3",{className:"text-sm font-medium text-bambu-gray",children:o("profiles.cloudView.columns.printer")}),i.jsxs("span",{className:"text-xs text-bambu-gray-dark",children:["(",ue.filter(Z=>Z.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[ue.filter(Z=>Z.type==="printer").map(Z=>i.jsx(Aj,{setting:Z,onClick:()=>oe(Z),onDuplicate:()=>se(Z),compareMode:z,isCompareSelected:_e(Z)!==void 0,compareIndex:_e(Z),compareDisabled:z&&!!Y[0]&&Y[0].type!==Z.type,t:o},Z.setting_id)),ue.filter(Z=>Z.type==="printer").length===0&&i.jsx("p",{className:"text-xs text-bambu-gray-dark px-3 py-2",children:o("profiles.cloudView.noPrinterPresets")})]})]})]}),A&&i.jsx(RZe,{setting:A,onClose:()=>M(null),onDeleted:()=>M(null),onDuplicate:()=>se(A),onEdit:()=>Oe(A),hasPermission:s,t:o}),(C||B||U||V)&&i.jsx(LZe,{onClose:()=>{j(!1),O(null),R(null),G(null)},initialData:U||B||(V?{type:V.type,name:"",base_id:"",setting:V.setting}:void 0),allPresets:t,t:o}),P&&i.jsx(FZe,{onClose:()=>E(!1),onApply:Z=>{G({type:Z.type,setting:Z.settings}),E(!1)},t:o}),$&&ee&&Y[0]&&Y[1]&&i.jsx(zie,{onClose:()=>{W(!1),J(null)},leftPreset:ee[0],rightPreset:ee[1],leftLabel:Y[0].name,rightLabel:Y[1].name,t:o})]})}function IZe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),[a,s]=w.useState("cloud"),[o,l]=w.useState(),{data:c,isLoading:u}=Je({queryKey:["cloudStatus"],queryFn:ne.getCloudStatus}),{data:d=[]}=Je({queryKey:["printers"],queryFn:ne.getPrinters}),{data:h,isLoading:f,refetch:p,dataUpdatedAt:x}=Je({queryKey:["cloudSettings"],queryFn:()=>ne.getCloudSettings(),enabled:!!c?.is_authenticated,retry:!1,staleTime:1e3*60*5});w.useEffect(()=>{x&&l(new Date(x))},[x]);const v=ot({mutationFn:ne.cloudLogout,onSuccess:()=>{e.invalidateQueries({queryKey:["cloudStatus"]}),e.removeQueries({queryKey:["cloudSettings"]}),n(t("profiles.toast.loggedOut"))}}),g=()=>{e.invalidateQueries({queryKey:["cloudStatus"]})};return u?i.jsx("div",{className:"p-4 md:p-8 flex items-center justify-center min-h-[400px]",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"p-6 lg:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("profiles.title")}),i.jsx("p",{className:"text-bambu-gray",children:t("profiles.subtitle")})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary mb-6",children:[i.jsxs("button",{onClick:()=>s("cloud"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="cloud"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(zb,{className:"w-4 h-4"}),t("profiles.tabs.cloud")]}),i.jsxs("button",{onClick:()=>s("local"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="local"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(Ub,{className:"w-4 h-4"}),t("profiles.tabs.local")]}),i.jsxs("button",{onClick:()=>s("kprofiles"),className:`flex items-center gap-2 px-4 py-3 text-sm font-medium transition-colors border-b-2 -mb-px ${a==="kprofiles"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-white border-transparent"}`,children:[i.jsx(BC,{className:"w-4 h-4"}),t("profiles.tabs.kprofiles")]})]}),a==="cloud"&&i.jsxs(i.Fragment,{children:[c?.is_authenticated&&i.jsxs("div",{className:"flex items-center justify-between p-3 mb-6 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green animate-pulse"}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("profiles.connectedAs")," ",i.jsx("span",{className:"text-white",children:c.email})]})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending||!r("cloud:auth"),title:r("cloud:auth")?void 0:t("profiles.noLogoutPermission"),children:[i.jsx(r3,{className:"w-4 h-4"}),t("profiles.logout")]})]}),c?.is_authenticated?f?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):h?i.jsx(OZe,{settings:h,lastSyncTime:o,onRefresh:()=>p(),isRefreshing:f,printers:d,hasPermission:r,t}):i.jsxs("div",{className:"text-center py-16",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("profiles.failedToLoad")}),i.jsx(Ce,{onClick:()=>p(),children:t("profiles.retry")})]}):i.jsx(jZe,{onSuccess:g,t})]}),a==="local"&&i.jsx(EZe,{}),a==="kprofiles"&&i.jsx(AZe,{}),i.jsx(DZe,{})]})}const Oy={Droplet:IC,Flame:sme,Ruler:Ife,Sparkles:lb,Square:vl,Cable:$de,Wrench:Ef,Calendar:na,Timer:Lu,Cog:Mhe,Fan:rX,Zap:Vh,Wind:fX,Thermometer:XC,Layers:mi,Box:Ja,Target:dX,RefreshCw:Cr,Settings:KC,Filter:UC,CircleDot:uhe};function ov(t){return t&&Oy[t]||Ef}function Tg(t,e,n){if(e==="days"){if(t<1)return n?n("common.today"):"Today";if(t===1)return n?n("maintenance.day"):"1 day";if(t<7){const a=Math.round(t);return n?n("maintenance.days",{count:a}):`${a} days`}if(t<180){const a=Math.round(t/7);return a===1?n?n("maintenance.week"):"1 week":n?n("maintenance.weeks",{count:a}):`${a} weeks`}const r=Math.round(t/30);return r===1?n?n("maintenance.month"):"1 month":n?n("maintenance.months",{count:r}):`${r} months`}else{if(t<1)return`${Math.round(t*60)}m`;if(t<24)return`${t<10?t.toFixed(1):Math.round(t)}h`;const r=t/24;if(r<7)return`${r<2?r.toFixed(1):Math.round(r)}d`;const a=r/7;return a<12?`${a<2?a.toFixed(1):Math.round(a)}w`:`${Math.round(a/4)}mo`}}function Tj(t,e,n){return e==="days"?t===1?n?n("maintenance.day"):"1 day":t===7?n?n("maintenance.week"):"1 week":t===14?n?n("maintenance.weeks",{count:2}):"2 weeks":t===30?n?n("maintenance.month"):"1 month":t===60?n?n("maintenance.months",{count:2}):"2 months":t===90?n?n("maintenance.months",{count:3}):"3 months":t===180?n?n("maintenance.months",{count:6}):"6 months":t===365?n?n("maintenance.year"):"1 year":n?n("maintenance.days",{count:t}):`${t} days`:`${t}h`}function zZe(t,e){const n=(e||"").toUpperCase().replace(/[- ]/g,""),r=n.includes("X1"),a=n.includes("P1"),s=n.includes("A1MINI"),o=n.includes("A1")&&!s,l=n.includes("H2D"),c=n.includes("H2C"),u=n.includes("H2S"),d=l||c||u,h=n.includes("P2S");switch(t){case"Lubricate Carbon Rods":return r?"https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Nozzle/Hotend":return r||a?"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog":s||o?"https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog":d?"https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning":h?"https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend":"https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog";case"Check Belt Tension":return r?"https://wiki.bambulab.com/en/x1/maintenance/belt-tension":a?"https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance":s?"https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension":o?"https://wiki.bambulab.com/en/a1/maintenance/belt_tension":l?"https://wiki.bambulab.com/en/h2/maintenance/belt-tension":c?"https://wiki.bambulab.com/en/h2c/maintenance/belt-tension":u?"https://wiki.bambulab.com/en/h2s/maintenance/belt-tension":h?"https://wiki.bambulab.com/en/p2s/maintenance/belt-tension":"https://wiki.bambulab.com/en/x1/maintenance/belt-tension";case"Clean Carbon Rods":return r||a||h?"https://wiki.bambulab.com/en/general/carbon-rods-clearance":null;case"Clean Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;case"Clean Build Plate":return"https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide";case"Check PTFE Tube":return r||a?"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube":s||o?"https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube":l?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":u?"https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer":c?"https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer":"https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube";case"Replace HEPA Filter":case"HEPA Filter":case"Replace Carbon Filter":case"Carbon Filter":return d?"https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte":"https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter";case"Lubricate Left Nozzle Rail":case"Left Nozzle Rail":return d?"https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication":null;default:return null}}function UZe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=ov(t.maintenance_type_icon),o=t.interval_type||"hours",c=(()=>{if(o==="days"){const p=t.days_since_maintenance??0;return Math.max(0,Math.min(100,p/t.interval_hours*100))}return Math.max(0,Math.min(100,(t.interval_hours-t.hours_until_due)/t.interval_hours*100))})(),u=()=>t.enabled?t.is_due?"text-red-400":t.is_warning?"text-amber-400":"text-bambu-green":"text-bambu-gray",d=()=>t.enabled?t.is_due?"bg-red-500":t.is_warning?"bg-amber-500":"bg-bambu-green":"bg-bambu-gray/30",h=()=>t.enabled?t.is_due?"bg-red-500/5 border-red-500/20":t.is_warning?"bg-amber-500/5 border-amber-500/20":"bg-bambu-dark-secondary border-bambu-dark-tertiary":"bg-bambu-dark-secondary/50",f=()=>{if(!t.enabled)return a("common.disabled");if(o==="days"){const p=t.days_until_due??0;return t.is_due?a("maintenance.overdueBy",{duration:Tg(Math.abs(p),"days",a)}):t.is_warning?a("maintenance.dueIn",{duration:Tg(p,"days",a)}):a("maintenance.timeLeft",{duration:Tg(p,"days",a)})}else return t.is_due?a("maintenance.overdueBy",{duration:Tg(Math.abs(t.hours_until_due),"hours",a)}):t.is_warning?a("maintenance.dueIn",{duration:Tg(t.hours_until_due,"hours",a)}):a("maintenance.timeLeft",{duration:Tg(t.hours_until_due,"hours",a)})};return i.jsx("div",{className:`rounded-xl border p-4 transition-all ${h()}`,children:i.jsxs("div",{className:"flex items-start gap-3 max-[550px]:flex-wrap",children:[i.jsxs("div",{className:`relative p-2.5 rounded-lg shrink-0 ${t.is_due?"bg-red-500/20":t.is_warning?"bg-amber-500/20":t.enabled?"bg-bambu-dark":"bg-bambu-dark/50"}`,children:[i.jsx(s,{className:`w-5 h-5 ${u()}`}),t.enabled&&(t.is_due||t.is_warning)&&i.jsx("span",{className:`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${t.is_due?"bg-red-500":"bg-amber-500"} animate-pulse`})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("h3",{className:`font-medium truncate ${t.enabled?"text-white":"text-bambu-gray"}`,children:t.maintenance_type_name}),o==="days"&&i.jsx("span",{title:a("maintenance.timeBasedInterval"),children:i.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const p=t.maintenance_type_wiki_url||zZe(t.maintenance_type_name,t.printer_model);return p?i.jsx("a",{href:p,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-bambu-green transition-colors shrink-0",title:a("maintenance.viewDocumentation"),onClick:x=>x.stopPropagation(),children:i.jsx(Kr,{className:"w-3.5 h-3.5"})}):null})()]}),i.jsx("div",{className:"mt-2 mb-1.5",children:i.jsx("div",{className:"w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${d()}`,style:{width:`${c}%`}})})}),i.jsxs("div",{className:`text-xs flex items-center gap-1 ${u()}`,children:[t.is_due&&i.jsx(Tn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Gn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(ra,{className:"w-3 h-3"}),f()]})]}),i.jsxs("div",{className:"flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1",children:[i.jsx("span",{title:r("maintenance:update")?void 0:a("maintenance.noPermissionUpdate"),children:i.jsx(On,{checked:t.enabled,onChange:p=>n(t.id,p),disabled:!r("maintenance:update")})}),i.jsxs(Ce,{size:"sm",variant:t.is_due?"primary":"secondary",onClick:()=>e(t.id),disabled:!t.enabled||!r("maintenance:update"),title:r("maintenance:update")?void 0:a("maintenance.noPermissionPerform"),className:"!px-3",children:[i.jsx(Fo,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function BZe({overview:t,onPerform:e,onToggle:n,onSetHours:r,hasPermission:a,t:s}){const[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(t.total_print_hours.toFixed(1)),f=[...t.maintenance_items].sort((v,g)=>v.is_due&&!g.is_due?-1:!v.is_due&&g.is_due?1:v.is_warning&&!g.is_warning?-1:!v.is_warning&&g.is_warning?1:v.maintenance_type_id-g.maintenance_type_id),p=f.find(v=>v.enabled&&(v.is_due||v.is_warning)),x=()=>{const v=parseFloat(d);!isNaN(v)&&v>=0&&(r(t.printer_id,v),u(!1))};return i.jsxs(vt,{className:"overflow-hidden",children:[i.jsxs("div",{className:"p-5",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("h2",{className:"text-xl font-semibold text-white",children:t.printer_name}),i.jsxs("div",{className:"flex items-center gap-2",children:[t.due_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Tn,{className:"w-3 h-3"}),s("maintenance.overdueCount",{count:t.due_count})]}),t.warning_count>0&&i.jsxs("span",{className:"px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(Gn,{className:"w-3 h-3"}),s("maintenance.dueSoonCount",{count:t.warning_count})]}),t.due_count===0&&t.warning_count===0&&i.jsxs("span",{className:"px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5",children:[i.jsx(ra,{className:"w-3 h-3"}),s("maintenance.allGood")]})]})]}),i.jsxs("button",{onClick:()=>l(!o),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors",children:[o?i.jsx(yl,{className:"w-4 h-4"}):i.jsx(Un,{className:"w-4 h-4"}),s(o?"common.collapse":"common.expand")]})]}),i.jsxs("div",{className:"flex items-center gap-6 mt-4",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 bg-bambu-dark/50 rounded-lg",children:i.jsx(Lu,{className:"w-4 h-4 text-bambu-gray"})}),c?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"number",value:d,onChange:v=>h(v.target.value),onKeyDown:v=>{v.key==="Enter"&&x(),v.key==="Escape"&&u(!1)},className:"w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm",min:"0",step:"1",autoFocus:!0}),i.jsx("span",{className:"text-xs text-bambu-gray",children:s("common.hours")}),i.jsx(Ce,{size:"sm",onClick:x,children:s("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>u(!1),children:s("common.cancel")})]}):i.jsxs("button",{onClick:()=>{a("maintenance:update")&&(h(Math.round(t.total_print_hours).toString()),u(!0))},className:`group ${a("maintenance:update")?"":"cursor-not-allowed opacity-60"}`,title:a("maintenance:update")?void 0:s("maintenance.noPermissionEditHours"),children:[i.jsxs("div",{className:`text-sm font-medium text-white ${a("maintenance:update")?"group-hover:text-bambu-green":""} transition-colors flex items-center gap-1`,children:[Math.round(t.total_print_hours)," ",s("common.hours"),i.jsx(Tf,{className:`w-3 h-3 text-bambu-gray ${a("maintenance:update")?"group-hover:text-bambu-green":""}`})]}),i.jsx("div",{className:"text-xs text-bambu-gray",children:s("maintenance.totalPrintTime")})]})]}),i.jsx("div",{className:"w-px h-10 bg-bambu-dark-tertiary"}),p&&i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.is_due?"bg-red-500/20":"bg-amber-500/20"}`,children:(()=>{const v=ov(p.maintenance_type_icon);return i.jsx(v,{className:`w-4 h-4 ${p.is_due?"text-red-400":"text-amber-400"}`})})()}),i.jsxs("div",{children:[i.jsx("div",{className:`text-sm font-medium ${p.is_due?"text-red-400":"text-amber-400"}`,children:p.maintenance_type_name}),i.jsx("div",{className:`text-xs ${p.is_due?"text-red-400/70":"text-amber-400/70"}`,children:p.is_due?s("common.overdue"):s("maintenance.dueSoon")})]})]})]})]}),o&&i.jsx(_t,{className:"pt-0 border-t border-bambu-dark-tertiary",children:i.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4",children:f.map(v=>i.jsx(UZe,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function HZe({overview:t,types:e,onUpdateInterval:n,onAddType:r,onUpdateType:a,onDeleteType:s,onRestoreDefaults:o,isRestoringDefaults:l,onAssignType:c,onRemoveItem:u,hasPermission:d,t:h}){const[f,p]=w.useState(null),[x,v]=w.useState(""),[g,y]=w.useState("hours"),[_,N]=w.useState(!1),[k,A]=w.useState(""),[M,C]=w.useState("100"),[j,P]=w.useState("hours"),[E,B]=w.useState("Wrench"),[O,U]=w.useState(""),[R,V]=w.useState(new Set),[G,z]=w.useState(null),[K,Y]=w.useState(null),ae=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),$=L=>t?t.filter(D=>D.maintenance_items.some(H=>H.maintenance_type_id===L)).map(D=>({printerId:D.printer_id,printerName:D.printer_name,itemId:D.maintenance_items.find(H=>H.maintenance_type_id===L)?.id})):[],W=L=>{if(!t)return[];const D=new Set($(L).map(H=>H.printerId));return ae.filter(H=>!D.has(H.id))},[ee,J]=w.useState(null),[ye,me]=w.useState(""),[te,je]=w.useState(""),[ue,oe]=w.useState("hours"),[_e,se]=w.useState("Wrench"),[Oe,q]=w.useState(""),X=L=>{J(L),me(L.name),je(L.default_interval_hours.toString()),oe(L.interval_type||"hours"),se(L.icon||"Wrench"),q(L.wiki_url||"")},de=()=>{ee&&ye.trim()&&parseFloat(te)>0&&(a(ee.id,{name:ye.trim(),default_interval_hours:parseFloat(te),interval_type:ue,icon:_e,wiki_url:Oe.trim()||null}),J(null))},Z=(L,D,H)=>{const he=parseFloat(x);if(!isNaN(he)&&he>0){const be=Math.abs(he-D)<.01?null:he;n(L,{custom_interval_hours:be,custom_interval_type:g!==H?g:null})}p(null)},ie=L=>{L.preventDefault(),k.trim()&&parseFloat(M)>0&&R.size>0&&(r({name:k.trim(),default_interval_hours:parseFloat(M),interval_type:j,icon:E,wiki_url:O.trim()||null},Array.from(R)),A(""),C("100"),P("hours"),U(""),V(new Set),N(!1))},le=L=>{V(D=>{const H=new Set(D);return H.has(L)?H.delete(L):H.add(L),H})},Fe=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((D,H)=>D.maintenance_type_id-H.maintenance_type_id)})).sort((L,D)=>L.printerName.localeCompare(D.printerName))||[],pe=e.filter(L=>L.is_system),Q=e.filter(L=>!L.is_system);return i.jsxs("div",{className:"space-y-8",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.maintenanceTypes")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.maintenanceTypesDescription")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),children:h("maintenance.restoreDefaults")}),i.jsxs(Ce,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionEditTypes"),children:[i.jsx(Xn,{className:"w-4 h-4"}),h("maintenance.addCustomType")]})]})]}),_&&i.jsx(vt,{className:"mb-6",children:i.jsx(_t,{className:"py-4",children:i.jsxs("form",{onSubmit:ie,children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[i.jsxs("div",{className:"lg:col-span-2",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("common.name")}),i.jsx("input",{type:"text",value:k,onChange:L=>A(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.exampleName"),autoFocus:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalType")}),i.jsxs("select",{value:j,onChange:L=>{P(L.target.value),L.target.value==="days"?C("30"):C("100")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.intervalValue",{type:j==="days"?h("maintenance.calendarDays").toLowerCase():h("common.hours")})}),i.jsx("input",{type:"number",value:M,onChange:L=>C(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]})]}),i.jsx("div",{className:"mt-4 flex items-end justify-between",children:i.jsxs("div",{children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.icon")}),i.jsx("div",{className:"flex gap-1",children:Object.keys(Oy).map(L=>{const D=Oy[L];return i.jsx("button",{type:"button",onClick:()=>B(L),className:`p-2 rounded-lg transition-colors ${E===L?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:i.jsx(D,{className:"w-4 h-4"})},L)})})]})}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.documentationLink")}),i.jsx("input",{type:"url",value:O,onChange:L=>U(L.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:"https://wiki.bambulab.com/..."})]}),i.jsxs("div",{className:"mt-4",children:[i.jsx("label",{className:"block text-xs text-bambu-gray mb-1.5",children:h("maintenance.assignToPrinters")}),i.jsx("div",{className:"flex flex-wrap gap-2",children:ae.map(L=>i.jsx("button",{type:"button",onClick:()=>le(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${R.has(L.id)?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary"}`,children:L.name},L.id))}),R.size===0&&i.jsx("p",{className:"text-xs text-orange-400 mt-1",children:h("maintenance.selectAtLeastOnePrinter")})]}),i.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:()=>{N(!1),V(new Set)},children:h("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!k.trim()||R.size===0,children:h("maintenance.addType")})]})]})})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[pe.map(L=>{const D=ov(L.icon),H=L.interval_type||"hours";return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-dark rounded-lg",children:i.jsx(D,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[H==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(L.default_interval_hours,H,h)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&Y(L)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]})},L.id)}),Q.map(L=>{const D=ov(L.icon),H=L.interval_type||"hours";if(ee?.id===L.id)return i.jsx("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx("input",{type:"text",value:ye,onChange:Ie=>me(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("common.name"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("select",{value:ue,onChange:Ie=>oe(Ie.target.value),className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:te,onChange:Ie=>je(Ie.target.value),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",min:"1"})]}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Object.keys(Oy).map(Ie=>{const qe=Oy[Ie];return i.jsx("button",{type:"button",onClick:()=>se(Ie),className:`p-1.5 rounded transition-colors ${_e===Ie?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:i.jsx(qe,{className:"w-3.5 h-3.5"})},Ie)})}),i.jsx("input",{type:"url",value:Oe,onChange:Ie=>q(Ie.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",placeholder:h("maintenance.documentationLink")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{size:"sm",onClick:de,disabled:!ye.trim(),children:h("common.save")}),i.jsx(Ce,{size:"sm",variant:"secondary",onClick:()=>J(null),children:h("common.cancel")})]})]})},L.id);const be=$(L.id),fe=W(L.id),ze=G===L.id;return i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/20 rounded-lg",children:i.jsx(D,{className:"w-5 h-5 text-bambu-green"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm font-medium text-white truncate",children:L.name}),i.jsx("span",{className:"px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded",children:h("maintenance.custom")})]}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-0.5 flex items-center gap-1",children:[H==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(L.default_interval_hours,H,h)]})]}),i.jsxs("button",{onClick:()=>z(ze?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${be.length>0?"border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20":"border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20"}`,title:h("maintenance.printersAssignedClick",{count:be.length}),children:[i.jsx(xr,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:be.length}),i.jsx(Un,{className:`w-3 h-3 transition-transform ${ze?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>X(L),disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${d("maintenance:update")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Tf,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{confirm(h("maintenance.deleteTypeConfirm",{name:L.name}))&&s(L.id)},disabled:!d("maintenance:delete"),title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),className:`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${d("maintenance:delete")?"":"opacity-50 cursor-not-allowed"}`,children:i.jsx(Jt,{className:"w-4 h-4"})})]}),ze&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:h("maintenance.assignedToPrinters")}),be.length===0?i.jsx("p",{className:"text-xs text-orange-400",children:h("maintenance.noPrintersAssigned")}):i.jsx("div",{className:"flex flex-wrap gap-1 mb-2",children:be.map(Ie=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white",children:[Ie.printerName,i.jsx("button",{onClick:()=>Ie.itemId&&u(Ie.itemId),disabled:!d("maintenance:delete"),title:d("maintenance:delete")?h("maintenance.removeFromPrinter"):h("maintenance.noPermissionRemovePrinter"),className:`ml-1 ${d("maintenance:delete")?"hover:text-red-400":"opacity-50 cursor-not-allowed"}`,children:"×"})]},Ie.printerId))}),fe.length>0&&i.jsxs("div",{className:"flex flex-wrap gap-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray mr-1",children:h("maintenance.addPrinterShort")}),fe.map(Ie=>i.jsxs("button",{onClick:()=>c(Ie.id,L.id),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionAssignPrinter"),className:`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${d("maintenance:create")?"hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green":"opacity-50 cursor-not-allowed text-bambu-gray"}`,children:["+ ",Ie.name]},Ie.id))]})]})]},L.id)})]})]}),Fe.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"mb-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:h("maintenance.intervalOverrides")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:h("maintenance.intervalOverridesDescription")})]}),i.jsx("div",{className:"space-y-4",children:Fe.map(L=>i.jsx(vt,{children:i.jsxs(_t,{className:"py-4",children:[i.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:L.printerName}),i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:L.items.map(D=>{const H=ov(D.maintenance_type_icon),he=e.find(qe=>qe.id===D.maintenance_type_id),be=he?.default_interval_hours||D.interval_hours,fe=he?.interval_type||"hours",ze=D.interval_type||"hours",Ie=f===D.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(H,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:D.maintenance_type_name}),Ie?i.jsxs("div",{className:"flex items-center gap-1",children:[g==="days"?i.jsx(na,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}):i.jsx(Lu,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"}),i.jsxs("select",{value:g,onChange:qe=>y(qe.target.value),className:"px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",children:[i.jsx("option",{value:"hours",children:h("maintenance.printHours")}),i.jsx("option",{value:"days",children:h("maintenance.calendarDays")})]}),i.jsx("input",{type:"number",value:x,onChange:qe=>v(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"&&Z(D.id,be,fe),qe.key==="Escape"&&p(null)},className:"w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs",min:"1"}),i.jsx(Ce,{size:"sm",onClick:()=>Z(D.id,be,fe),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(p(D.id),v(D.interval_hours.toString()),y(ze))},disabled:!d("maintenance:update"),title:d("maintenance:update")?void 0:h("maintenance.noPermissionEditIntervals"),className:`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${d("maintenance:update")?"hover:bg-bambu-dark-secondary hover:border-bambu-green":"opacity-50 cursor-not-allowed"}`,children:[ze==="days"?i.jsx(na,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Tj(D.interval_hours,ze,h),i.jsx(Tf,{className:"w-3 h-3 text-bambu-gray"})]})]},D.id)})})]})},L.printerId))})]}),Fe.length===0&&i.jsx(vt,{children:i.jsxs(_t,{className:"text-center py-12",children:[i.jsx(Gn,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-bambu-gray",children:h("common.noPrinters")}),i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1",children:h("maintenance.intervalOverridesDescription")})]})}),K&&i.jsx(gn,{title:h("maintenance.deleteSystemTypeTitle"),message:h("maintenance.deleteSystemTypeMessage",{name:K.name}),confirmText:h("common.delete"),cancelText:h("common.cancel"),variant:"danger",cancelVariant:"primary",cardClassName:"bg-red-950/70 border border-red-800/70",onConfirm:()=>{s(K.id),Y(null)},onCancel:()=>Y(null)})]})}function $Ze(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),[a,s]=w.useState("status"),{data:o,isLoading:l}=Je({queryKey:["maintenanceOverview"],queryFn:ne.getMaintenanceOverview}),{data:c}=Je({queryKey:["maintenanceTypes"],queryFn:ne.getMaintenanceTypes}),u=ot({mutationFn:({id:M,notes:C})=>ne.performMaintenance(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:M=>{n(M.message,"error")}}),d=ot({mutationFn:({id:M,data:C})=>ne.updateMaintenanceItem(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:M=>{n(M.message,"error")}}),h=ot({mutationFn:({id:M,data:C})=>ne.updateMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:M=>{n(M.message,"error")}}),f=ot({mutationFn:ne.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:M=>{n(M.message,"error")}}),p=ot({mutationFn:ne.restoreDefaultMaintenanceTypes,onSuccess:M=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:M.restored}))},onError:M=>{n(M.message,"error")}}),x=ot({mutationFn:({printerId:M,hours:C})=>ne.setPrinterHours(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:M=>{n(M.message,"error")}}),v=ot({mutationFn:({printerId:M,typeId:C})=>ne.assignMaintenanceType(M,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:M=>{n(M.message,"error")}}),g=ot({mutationFn:ne.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:M=>{n(M.message,"error")}}),y=M=>{u.mutate({id:M})},_=(M,C)=>{d.mutate({id:M,data:{enabled:C}})},N=(M,C)=>{x.mutate({printerId:M,hours:C})};if(l)return i.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});const k=o?.reduce((M,C)=>M+C.due_count,0)||0,A=o?.reduce((M,C)=>M+C.warning_count,0)||0;return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"mb-6",children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("maintenance.title")}),i.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:a==="status"?i.jsxs(i.Fragment,{children:[k>0&&i.jsx("span",{className:"text-red-400",children:t("maintenance.dueCount",{count:k})}),k>0&&A>0&&" · ",A>0&&i.jsx("span",{className:"text-amber-400",children:t("maintenance.warningCount",{count:A})}),k===0&&A===0&&i.jsx("span",{className:"text-bambu-green",children:t("maintenance.allOk")})]}):t("maintenance.configureSettings")})]}),i.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>s("status"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="status"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.statusTab")}),i.jsx("button",{onClick:()=>s("settings"),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${a==="settings"?"text-bambu-green border-bambu-green":"text-bambu-gray border-transparent hover:text-white"}`,children:t("maintenance.settingsTab")})]}),a==="status"?i.jsx("div",{className:"space-y-6",children:o&&o.length>0?[...o].sort((M,C)=>{const j=M.due_count*10+M.warning_count,P=C.due_count*10+C.warning_count;return j!==P?P-j:M.printer_name.localeCompare(C.printer_name)}).map(M=>i.jsx(BZe,{overview:M,onPerform:y,onToggle:_,onSetHours:N,hasPermission:r,t},M.printer_id)):i.jsx(vt,{children:i.jsxs(_t,{className:"text-center py-16",children:[i.jsx(Ef,{className:"w-16 h-16 mx-auto mb-4 text-bambu-gray/30"}),i.jsx("p",{className:"text-lg font-medium text-white mb-2",children:t("common.noPrinters")}),i.jsx("p",{className:"text-bambu-gray",children:t("maintenance.configureSettings")})]})})}):i.jsx(HZe,{overview:o,types:c||[],onUpdateInterval:(M,C)=>d.mutate({id:M,data:C}),onAddType:async(M,C)=>{const j=await ne.createMaintenanceType(M);for(const P of C)await ne.assignMaintenanceType(P,j.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(M,C)=>h.mutate({id:M,data:C}),onDeleteType:M=>f.mutate(M),onRestoreDefaults:()=>p.mutate(),isRestoringDefaults:p.isPending,onAssignType:(M,C)=>v.mutate({printerId:M,typeId:C}),onRemoveItem:M=>g.mutate(M),hasPermission:r,t})]})}const JW=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Uie({project:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(t?.name||""),[l,c]=w.useState(t?.description||""),[u,d]=w.useState(t?.color||JW[0]),[h,f]=w.useState(t?.target_count?.toString()||""),[p,x]=w.useState(t?.target_parts_count?.toString()||""),[v,g]=w.useState(t?.status||"active"),[y,_]=w.useState(t?.tags||""),[N,k]=w.useState(t?.due_date?.split("T")[0]||""),[A,M]=w.useState(t?.priority||"normal"),C=j=>{j.preventDefault(),n({name:s.trim(),description:l.trim()||void 0,color:u,target_count:h?parseInt(h,10):void 0,target_parts_count:p?parseInt(p,10):void 0,tags:y.trim()||void 0,due_date:N||void 0,priority:A,...t&&{status:v}})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a(t?"projects.editProject":"projects.newProject")})}),i.jsxs("form",{onSubmit:C,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.name")}),i.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.namePlaceholder"),required:!0})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.description")}),i.jsx("textarea",{value:l,onChange:j=>c(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green resize-none",placeholder:a("projects.descriptionPlaceholder"),rows:2})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.color")}),i.jsx("div",{className:"flex gap-2 flex-wrap",children:JW.map(j=>i.jsx("button",{type:"button",onClick:()=>d(j),className:`w-8 h-8 rounded-full transition-transform ${u===j?"ring-2 ring-white ring-offset-2 ring-offset-bambu-dark-secondary scale-110":""}`,style:{backgroundColor:j}},j))})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetPlates")}),i.jsx("input",{type:"number",value:h,onChange:j=>f(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.targetPlatesPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPlatesHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.targetParts")}),i.jsx("input",{type:"number",value:p,onChange:j=>x(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.targetPartsPlaceholder"),min:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("projects.targetPartsHelp")})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.tagsLabel")}),i.jsx("input",{type:"text",value:y,onChange:j=>_(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("projects.tagsPlaceholder")})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.dueDate")}),i.jsx("input",{type:"date",value:N,onChange:j=>k(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("projects.priority")}),i.jsxs("select",{value:A,onChange:j=>M(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"low",children:a("projects.priorityLow")}),i.jsx("option",{value:"normal",children:a("projects.priorityNormal")}),i.jsx("option",{value:"high",children:a("projects.priorityHigh")}),i.jsx("option",{value:"urgent",children:a("projects.priorityUrgent")})]})]})]}),t&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("common.status")}),i.jsxs("select",{value:v,onChange:j=>g(j.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"active",children:a("projects.statusActive")}),i.jsx("option",{value:"completed",children:a("projects.statusCompleted")}),i.jsx("option",{value:"archived",children:a("projects.statusArchived")})]})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a(t?"common.save":"projects.create")})]})]})]})})}function VZe({project:t,onClick:e,onEdit:n,onDelete:r,hasPermission:a,t:s}){const o=t.target_count?Math.round(t.archive_count/t.target_count*100):0,l=t.target_parts_count?Math.round(t.completed_count/t.target_parts_count*100):0,c=t.status==="completed",u=t.status==="archived",[d,h]=w.useState(!1),p=c?{icon:ob,color:"text-bambu-green",bg:"bg-bambu-green/10"}:u?{icon:js,color:"text-bambu-gray",bg:"bg-bambu-gray/10"}:t.queue_count>0?{icon:Gn,color:"text-blue-400",bg:"bg-blue-400/10"}:{icon:gs,color:"text-bambu-gray",bg:"bg-bambu-gray/10"};return i.jsxs("div",{className:"group relative bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary hover:border-bambu-green/50 hover:shadow-lg hover:shadow-bambu-green/5 transition-all duration-300 cursor-pointer overflow-hidden",onClick:e,children:[i.jsx("div",{className:"absolute top-0 left-0 w-1.5 h-full",style:{backgroundColor:t.color||"#6b7280",boxShadow:`0 0 12px ${t.color||"#6b7280"}40`}}),i.jsxs("div",{className:"p-5 pl-6",children:[i.jsxs("div",{className:"flex items-start justify-between mb-4",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[i.jsx("div",{className:`p-2 rounded-lg ${p.bg} flex-shrink-0`,children:i.jsx(p.icon,{className:`w-5 h-5 ${p.color}`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[i.jsx("h3",{className:"font-semibold text-white truncate",children:t.name}),t.target_parts_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${l>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.completed_count,"/",t.target_parts_count," ",s("projects.parts")]}):t.target_count?i.jsxs("span",{className:`text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium ${o>=100?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray"}`,children:[t.archive_count,"/",t.target_count," ",s("projects.plates")]}):t.completed_count>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full whitespace-nowrap font-medium bg-bambu-dark text-bambu-gray",children:[t.completed_count," ",s("projects.parts")]}):null,c&&i.jsx("span",{className:"text-xs bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.done")}),u&&i.jsx("span",{className:"text-xs bg-bambu-gray/20 text-bambu-gray px-2 py-0.5 rounded-full whitespace-nowrap",children:s("projects.statusArchived")})]}),t.description&&i.jsx("p",{className:"text-sm text-bambu-gray/70 mt-1 line-clamp-1",children:t.description}),t.archives&&t.archives.length>0&&(()=>{const x=t.archives.map(_=>_.filament_type).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(Boolean),v=[...new Set(x)],g=t.archives.map(_=>_.filament_color).filter(Boolean).flatMap(_=>_.split(",").map(N=>N.trim())).filter(_=>_.startsWith("#")||/^[0-9A-Fa-f]{6}$/.test(_)),y=[...new Set(g)];return v.length===0&&y.length===0?null:i.jsxs("div",{className:"flex items-center gap-2 mt-1.5",children:[v.slice(0,3).map(_=>i.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-bambu-dark text-bambu-gray rounded",children:_},_)),y.length>0&&i.jsxs("div",{className:"flex items-center gap-0.5",children:[y.slice(0,5).map(_=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:_.startsWith("#")?_:`#${_}`},title:_},_)),y.length>5&&i.jsxs("span",{className:"text-[10px] text-bambu-gray ml-0.5",children:["+",y.length-5]})]})]})})()]})]}),i.jsxs("div",{className:"relative",onClick:x=>x.stopPropagation(),children:[i.jsx("button",{className:"p-1.5 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors opacity-0 group-hover:opacity-100",onClick:()=>h(!d),children:i.jsx(Ah,{className:"w-4 h-4"})}),d&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>h(!1)}),i.jsxs("div",{className:"absolute right-0 top-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:update")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:update")&&(n(),h(!1))},disabled:!a("projects:update"),title:a("projects:update")?void 0:s("projects.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4"}),s("common.edit")]}),i.jsxs("button",{className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 ${a("projects:delete")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{a("projects:delete")&&(r(),h(!1))},disabled:!a("projects:delete"),title:a("projects:delete")?void 0:s("projects.noDeletePermission"),children:[i.jsx(Jt,{className:"w-4 h-4"}),s("common.delete")]})]})]})]})]}),i.jsx("div",{className:"mb-4",children:t.target_count||t.target_parts_count?i.jsxs("div",{className:"space-y-3",children:[t.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.plates")}),i.jsxs("span",{className:o>=100?"text-bambu-green font-medium":"text-white",children:[t.archive_count," / ",t.target_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(o,100)}%`,background:o>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${o>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:s("projects.parts")}),i.jsxs("span",{className:l>=100?"text-bambu-green font-medium":"text-white",children:[t.completed_count," / ",t.target_parts_count]})]}),i.jsx("div",{className:"h-2 bg-bambu-dark/80 rounded-full overflow-hidden backdrop-blur-sm",children:i.jsx("div",{className:"h-full transition-all duration-500 ease-out rounded-full relative",style:{width:`${Math.min(l,100)}%`,background:l>=100?"linear-gradient(90deg, #22c55e, #4ade80)":`linear-gradient(90deg, ${t.color||"#6b7280"}, ${t.color||"#6b7280"}cc)`,boxShadow:`0 0 8px ${l>=100?"#22c55e":t.color||"#6b7280"}60`}})})]}),t.failed_count>0&&i.jsxs("div",{className:"text-xs text-red-400",children:[t.failed_count," ",s("projects.failed")]})]}):t.completed_count>0||t.failed_count>0?i.jsxs("div",{className:"flex items-center gap-4 text-xs",children:[t.completed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-bambu-gray",children:[i.jsx(js,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.completed")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.failed_count," ",s("projects.failed")]})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-blue-400",children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),i.jsxs("span",{children:[t.queue_count," ",s("projects.inQueue")]})]})]}):i.jsx("div",{className:"text-xs text-bambu-gray/60 italic",children:s("projects.noPrintsYet")})}),t.archives&&t.archives.length>0&&i.jsxs("div",{className:"mb-4",children:[i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t.archives.slice(0,4).map(x=>i.jsxs("div",{className:"relative aspect-square rounded-lg bg-bambu-dark overflow-hidden border border-bambu-dark-tertiary",title:x.print_name||"Unknown",children:[x.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(x.id),alt:x.print_name||"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray/50",children:i.jsx(fi,{className:"w-6 h-6"})}),x.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/40 flex items-center justify-center",children:i.jsx(Tn,{className:"w-4 h-4 text-white"})})]},x.id))}),t.archive_count>4&&i.jsx("p",{className:"text-xs text-bambu-gray mt-1.5 text-center",children:s("common.more",{count:t.archive_count-4})})]}),i.jsxs("div",{className:"flex items-center justify-between pt-3 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-4 text-xs text-bambu-gray",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.printJobs"),children:[i.jsx(mi,{className:"w-3.5 h-3.5 text-blue-400"}),i.jsxs("span",{children:[t.archive_count," ",s("projects.plates")]})]}),i.jsxs("div",{className:"flex items-center gap-1.5",title:s("projects.partsPrinted"),children:[i.jsx(fi,{className:"w-3.5 h-3.5 text-bambu-green"}),i.jsxs("span",{children:[t.completed_count," ",s("projects.parts")]})]}),t.failed_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-red-400",title:s("projects.failedParts"),children:[i.jsx(Tn,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.failed_count})]}),t.queue_count>0&&i.jsxs("div",{className:"flex items-center gap-1.5 text-yellow-400",title:s("projects.inQueue"),children:[i.jsx(n3,{className:"w-3.5 h-3.5"}),i.jsx("span",{children:t.queue_count})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray/50 group-hover:text-bambu-gray transition-colors"})]})]})]})}function qZe(){const{t}=Ut(),e=rc(),n=tn(),{showToast:r}=cn(),{hasPermission:a}=Or(),[s,o]=w.useState(!1),[l,c]=w.useState(),[u,d]=w.useState("active"),[h,f]=w.useState(null),{data:p,isLoading:x}=Je({queryKey:["projects",u==="all"?void 0:u],queryFn:()=>ne.getProjects(u==="all"?void 0:u)}),v=ot({mutationFn:U=>ne.createProject(U),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:U=>{r(U.message,"error")}}),g=ot({mutationFn:({id:U,data:R})=>ne.updateProject(U,R),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:U=>{r(U.message,"error")}}),y=ot({mutationFn:U=>ne.deleteProject(U),onSuccess:()=>{f(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:U=>{f(null),r(U.message,"error")}}),_=ot({mutationFn:U=>ne.importProject(U),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:U=>{r(U.message,"error")}}),N=w.useRef(null),k=async()=>{try{const U=await ne.getProjects(),R=await Promise.all(U.map(async K=>await ne.exportProjectJson(K.id))),V=new Blob([JSON.stringify(R,null,2)],{type:"application/json"}),G=URL.createObjectURL(V),z=document.createElement("a");z.href=G,z.download=`bambuddy_projects_${new Date().toISOString().split("T")[0]}.json`,z.click(),URL.revokeObjectURL(G),r(t("projects.toast.exported"),"success")}catch(U){r(U.message,"error")}},A=()=>{N.current?.click()},M=async U=>{const R=U.target.files?.[0];if(R){try{if(R.name.toLowerCase().endsWith(".zip"))await ne.importProjectFile(R),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const G=await R.text(),z=JSON.parse(G),K=Array.isArray(z)?z:[z];for(const Y of K)await _.mutateAsync(Y);K.length>1&&r(t("projects.toast.multipleImported",{count:K.length}),"success")}}catch(V){r(`${t("projects.toast.importFailed")}: ${V.message}`,"error")}U.target.value=""}},C=U=>{l?g.mutate({id:l.id,data:U}):v.mutate(U)},j=U=>{c(U),o(!0)},P=U=>{e(`/projects/${U.id}`)},E=U=>{f(U)},B=()=>{h!==null&&y.mutate(h)},O=p?.reduce((U,R)=>(U[R.status]=(U[R.status]||0)+1,U.all=(U.all||0)+1,U),{})||{};return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsx("input",{ref:N,type:"file",accept:".json,.zip",onChange:M,className:"hidden"}),i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(gs,{className:"w-6 h-6 text-bambu-green"})}),t("projects.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("projects.subtitle")})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:A,disabled:!a("projects:create"),title:a("projects:create")?t("projects.importProject"):t("projects.noImportPermission"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("projects.import")]}),i.jsxs(Ce,{variant:"secondary",onClick:k,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(ua,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(Ce,{onClick:()=>o(!0),className:"sm:w-auto w-full",disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("projects.newProject")]})]})]}),i.jsx("div",{className:"flex gap-1 p-1 bg-bambu-dark rounded-xl w-fit",children:[{key:"active",label:t("projects.statusActive"),icon:Gn},{key:"completed",label:t("projects.statusCompleted"),icon:ob},{key:"archived",label:t("projects.statusArchived"),icon:js},{key:"all",label:t("common.all"),icon:gs}].map(({key:U,label:R,icon:V})=>i.jsxs("button",{onClick:()=>d(U),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===U?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx(V,{className:"w-4 h-4"}),i.jsx("span",{children:R}),O[U]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===U?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:O[U]})]},U))}),x?i.jsx("div",{className:"flex items-center justify-center py-20",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("projects.loading")})]})}):p?.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center py-20 px-4",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(gs,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:u==="all"?t("projects.noProjects"):t("projects.noProjectsFiltered",{status:u})}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:u==="all"?t("projects.createFirst"):t("projects.noProjectsFilteredHelp",{status:u})}),u==="all"&&i.jsxs(Ce,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("projects.createFirstButton")]})]}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-8",children:p?.map(U=>i.jsx(VZe,{project:U,onClick:()=>P(U),onEdit:()=>j(U),onDelete:()=>E(U.id),hasPermission:a,t},U.id))}),h!==null&&i.jsx(gn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:B,onCancel:()=>f(null)}),s&&i.jsx(Uie,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:v.isPending||g.isPending,t})]})}function GZe(t){if(t<1)return`${Math.round(t*60)}m`;const e=Math.floor(t),n=Math.round((t-e)*60);return n>0?`${e}h ${n}m`:`${e}h`}function WZe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function KZe({status:t,t:e}){const n={active:"bg-bambu-green/20 text-bambu-green",completed:"bg-blue-500/20 text-blue-400",archived:"bg-bambu-gray/20 text-bambu-gray"},r=n[t]||n.active,a={active:e("projectDetail.status.active"),completed:e("projectDetail.status.completed"),archived:e("projectDetail.status.archived")};return i.jsx("span",{className:`px-2 py-1 rounded text-sm font-medium ${r}`,children:a[t]||t.charAt(0).toUpperCase()+t.slice(1)})}function eK({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(vt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",title:a,children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${s}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-xl font-semibold text-white",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray/70",children:r})]})]})})})}function XZe({archives:t,t:e}){return t.length===0?i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(fi,{className:"w-12 h-12 mx-auto mb-2 opacity-50"}),i.jsx("p",{children:e("projectDetail.noPrints")})]}):i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3",children:t.map(n=>i.jsxs(Ks,{to:`/archives?search=${encodeURIComponent(n.print_name||"")}`,className:"group relative aspect-square rounded-lg bg-bambu-dark border border-bambu-dark-tertiary overflow-hidden hover:border-bambu-green transition-colors",children:[n.thumbnail_path?i.jsx("img",{src:ne.getArchiveThumbnail(n.id),alt:n.print_name||"Print",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:i.jsx(fi,{className:"w-8 h-8"})}),n.status==="failed"&&i.jsx("div",{className:"absolute inset-0 bg-red-500/30 flex items-center justify-center",children:i.jsx(hi,{className:"w-8 h-8 text-white"})}),n.status==="completed"&&i.jsx("div",{className:"absolute top-1 right-1",children:i.jsx(pr,{className:"w-4 h-4 text-bambu-green"})}),i.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-2 opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx("p",{className:"text-xs text-white truncate",children:n.print_name||"Unknown"})})]},n.id))})}function YZe({priority:t,t:e}){const n={low:{color:"bg-gray-500/20 text-gray-400",label:e("projectDetail.priority.low")},normal:{color:"bg-blue-500/20 text-blue-400",label:e("projectDetail.priority.normal")},high:{color:"bg-orange-500/20 text-orange-400",label:e("projectDetail.priority.high")},urgent:{color:"bg-red-500/20 text-red-400",label:e("projectDetail.priority.urgent")}},{color:r,label:a}=n[t]||n.normal;return i.jsxs("span",{className:`px-2 py-1 rounded text-xs font-medium flex items-center gap-1 ${r}`,children:[t==="urgent"&&i.jsx(Tn,{className:"w-3 h-3"}),a]})}function QZe(t){return t?cb(t,{year:"numeric",month:"short",day:"numeric"}):""}function Mj(t,e){if(!t)return null;const n=di(t);if(!n)return null;const r=new Date,a=Math.ceil((n.getTime()-r.getTime())/(1e3*60*60*24));return a<0?{color:"text-red-400",label:e("projectDetail.dueDate.overdue")}:a===0?{color:"text-orange-400",label:e("projectDetail.dueDate.today")}:a<=3?{color:"text-yellow-400",label:e("projectDetail.dueDate.daysLeft",{count:a})}:{color:"text-bambu-gray",label:e("projectDetail.dueDate.daysLeft",{count:a})}}function ZZe(){const{id:t}=i0(),e=rc(),{t:n}=Ut(),r=tn(),{showToast:a}=cn(),{hasPermission:s}=Or(),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(""),f=parseInt(t||"0",10),{data:p,isLoading:x,error:v}=Je({queryKey:["project",f],queryFn:()=>ne.getProject(f),enabled:f>0}),{data:g,isLoading:y}=Je({queryKey:["project-archives",f],queryFn:()=>ne.getProjectArchives(f),enabled:f>0}),{data:_,isLoading:N}=Je({queryKey:["project-bom",f],queryFn:()=>ne.getProjectBOM(f),enabled:f>0}),{data:k,isLoading:A}=Je({queryKey:["project-timeline",f],queryFn:()=>ne.getProjectTimeline(f,20),enabled:f>0}),{data:M}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:C}=Je({queryKey:["project-folders",f],queryFn:()=>ne.getLibraryFoldersByProject(f),enabled:f>0}),j=rl(M?.currency||"USD"),P=M?.time_format||"system",E=ot({mutationFn:ve=>ne.updateProject(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project",f]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:ve=>{a(ve.message,"error")}}),B=()=>{h(p?.notes||""),u(!0)},O=()=>{E.mutate({notes:d})},U=()=>{u(!1),h("")},[R,V]=w.useState(""),[G,z]=w.useState(1),[K,Y]=w.useState(""),[ae,$]=w.useState(""),[W,ee]=w.useState(""),[J,ye]=w.useState(!1),[me,te]=w.useState(!1),[je,ue]=w.useState(null),[oe,_e]=w.useState(""),[se,Oe]=w.useState(1),[q,X]=w.useState(""),[de,Z]=w.useState(""),[ie,le]=w.useState(""),[Fe,pe]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),Q=ot({mutationFn:ve=>ne.createBOMItem(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),V(""),z(1),Y(""),$(""),ee(""),ye(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:ve=>a(ve.message,"error")}),L=ot({mutationFn:({itemId:ve,data:He})=>ne.updateBOMItem(f,ve,He),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),ue(null)},onError:ve=>a(ve.message,"error")}),D=ot({mutationFn:ve=>ne.deleteBOMItem(f,ve),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:ve=>a(ve.message,"error")}),H=ve=>{ve.preventDefault(),R.trim()&&Q.mutate({name:R.trim(),quantity_needed:G,unit_price:K?parseFloat(K):void 0,sourcing_url:ae.trim()||void 0,remarks:W.trim()||void 0})},he=ve=>{const He=ve.is_complete?0:ve.quantity_needed;L.mutate({itemId:ve.id,data:{quantity_acquired:He}})},be=(ve,He)=>{pe({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:He}),onConfirm:()=>{pe(Pe=>({...Pe,isOpen:!1})),D.mutate(ve)}})},fe=ve=>{ue(ve),_e(ve.name),Oe(ve.quantity_needed),X(ve.unit_price?.toString()||""),Z(ve.sourcing_url||""),le(ve.remarks||"")},ze=ve=>{ve.preventDefault(),!(!je||!oe.trim())&&L.mutate({itemId:je.id,data:{name:oe.trim(),quantity_needed:se,unit_price:q?parseFloat(q):void 0,sourcing_url:de.trim()||void 0,remarks:ie.trim()||void 0}})},Ie=()=>{ue(null)},qe=async()=>{try{const{blob:ve,filename:He}=await ne.exportProjectZip(Number(f)),Pe=URL.createObjectURL(ve),nt=document.createElement("a");nt.href=Pe,nt.download=He||`${p?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,nt.click(),URL.revokeObjectURL(Pe),a(n("projectDetail.toast.projectExported"),"success")}catch(ve){a(ve.message,"error")}},tt=ot({mutationFn:()=>ne.createTemplateFromProject(f),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:ve=>a(ve.message,"error")}),Ee=ve=>jf(ve,P,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});if(x)return i.jsx("div",{className:"flex items-center justify-center py-24",children:i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})});if(v||!p)return i.jsxs("div",{className:"text-center py-24",children:[i.jsx("p",{className:"text-bambu-gray",children:v?`${n("common.error")}: ${v.message}`:n("projectDetail.notFound")}),i.jsx(Ce,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const Se=p.stats,Me=Se?.progress_percent??0,xe=Se?.parts_progress_percent??0;return i.jsxs("div",{className:"p-4 md:p-8 space-y-8",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[i.jsx(Ks,{to:"/projects",className:"hover:text-white transition-colors",children:n("navigation.projects")}),i.jsx(pi,{className:"w-4 h-4"}),i.jsx("span",{className:"text-white",children:p.name})]}),i.jsxs("div",{className:"flex items-start justify-between",children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsx("button",{onClick:()=>e("/projects"),className:"p-2 rounded-lg bg-bambu-card hover:bg-bambu-dark-tertiary transition-colors",children:i.jsx(ZK,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-4 h-4 rounded-full flex-shrink-0",style:{backgroundColor:p.color||"#6b7280"}}),i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:p.name}),p.description&&i.jsx("p",{className:"text-bambu-gray mt-1",children:p.description})]})]}),i.jsx(KZe,{status:p.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",onClick:qe,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(ua,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(Ce,{onClick:()=>l(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4 mr-2"}),n("common.edit")]})]})]}),(p.target_count||p.target_parts_count)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4 space-y-4",children:[p.target_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.platesProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.total_archives||0," / ",p.target_count," ",n("projectDetail.progress.printJobs")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(Me,100)}%`,backgroundColor:Me>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:Me.toFixed(0)})}),Se?.remaining_prints!=null&&Se.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_prints})})]})]}),p.target_parts_count&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:n("projectDetail.progress.partsProgress")}),i.jsxs("span",{className:"text-sm font-medium text-white",children:[Se?.completed_prints||0," / ",p.target_parts_count," ",n("projectDetail.progress.parts")]})]}),i.jsx("div",{className:"h-3 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full transition-all duration-500",style:{width:`${Math.min(xe,100)}%`,backgroundColor:xe>=100?"#22c55e":p.color||"#6b7280"}})}),i.jsxs("div",{className:"flex justify-between mt-1",children:[i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.percentComplete",{percent:xe.toFixed(0)})}),Se?.remaining_parts!=null&&Se.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:Se.remaining_parts})})]})]})]})}),Se&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(vt,{children:i.jsx(_t,{className:"p-4",children:i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:i.jsx(fi,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.printJobs")}),i.jsxs("p",{className:"text-xl font-semibold text-white",children:[Se.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),Se.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:Se.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:Se.completed_prints})})]})]})})}),i.jsx(eK,{icon:Gn,label:n("projectDetail.stats.printTime"),value:GZe(Se.total_print_time_hours),color:"text-yellow-400"}),i.jsx(eK,{icon:xr,label:n("projectDetail.stats.filamentUsed"),value:WZe(Se.total_filament_grams),color:"text-purple-400"})]}),Se&&(Se.estimated_cost>0||p.budget)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white mb-3",children:n("projectDetail.cost.title")}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.filamentCost")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,Se.estimated_cost.toFixed(2)]})]}),Se.total_energy_kwh>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.energy")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[Se.total_energy_kwh.toFixed(3)," kWh",Se.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",j,Se.total_energy_cost.toFixed(2),")"]})]})]}),p.budget&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.budget")}),i.jsxs("p",{className:"text-lg font-semibold text-white",children:[j,p.budget.toFixed(2)]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.cost.remaining")}),i.jsxs("p",{className:`text-lg font-semibold ${p.budget-Se.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[j,(p.budget-Se.estimated_cost).toFixed(2)]})]})]})]})]})}),p.children&&p.children.length>0&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-3",children:[i.jsx(hme,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:p.children.length})]}),i.jsx("div",{className:"space-y-2",children:p.children.map(ve=>i.jsxs(Ks,{to:`/projects/${ve.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:ve.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:ve.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${ve.status==="completed"?"bg-status-ok/20 text-status-ok":ve.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:ve.status})]}),ve.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[ve.progress_percent.toFixed(0),"%"]})]},ve.id))})]})}),p.parent_id&&p.parent_name&&i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(mi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.partOf")}),i.jsx(Ks,{to:`/projects/${p.parent_id}`,className:"text-bambu-green hover:underline",children:p.parent_name})]}),(p.tags||p.due_date||p.priority!=="normal")&&i.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[p.priority&&p.priority!=="normal"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-bambu-gray uppercase",children:n("projectDetail.priorityLabel")}),i.jsx(YZe,{priority:p.priority,t:n})]}),p.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(na,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:QZe(p.due_date)}),Mj(p.due_date,n)&&i.jsxs("span",{className:`text-xs ${Mj(p.due_date,n).color}`,children:["(",Mj(p.due_date,n).label,")"]})]}),p.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx($h,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:p.tags.split(",").map((ve,He)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:ve.trim()},He))})]})]}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Ms,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:U,disabled:E.isPending,children:[i.jsx(Ft,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(Ce,{size:"sm",onClick:O,disabled:E.isPending,children:[E.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-1"}):i.jsx(ps,{className:"w-4 h-4 mr-1"}),n("common.save")]})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:B,disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.notes.noEditPermission"),children:[i.jsx(Tf,{className:"w-4 h-4 mr-1"}),n("common.edit")]})]}),c?i.jsx(KR,{content:d,onChange:h,placeholder:n("projectDetail.notes.placeholder")}):p.notes?i.jsx("div",{className:"prose prose-invert prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.notes}}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.notes.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Zl,{className:"w-5 h-5"}),n("projectDetail.files.title")]})}),i.jsxs("p",{className:"text-xs text-bambu-gray mb-3",children:[i.jsx(Ks,{to:"/files",className:"text-bambu-green hover:underline",children:n("projectDetail.files.linkFolders")})," ",n("projectDetail.files.forQuickAccess")]}),C&&C.length>0?i.jsx("div",{className:"space-y-2",children:C.map(ve=>i.jsxs(Ks,{to:`/files?folder=${ve.id}`,className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsx(Zl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:ve.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:ve.file_count})})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},ve.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(cX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),Se&&Se.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:Se.bom_completed_items,total:Se.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(ve=>ve.is_complete)&&i.jsx("button",{onClick:()=>te(!me),className:`text-xs px-2 py-1 rounded transition-colors ${me?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(me?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!J&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>ye(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),J&&i.jsxs("form",{onSubmit:H,className:"bg-bambu-dark rounded-lg p-4 mb-4 space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:R,onChange:ve=>V(ve.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partNamePlaceholder"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:G,onChange:ve=>z(parseInt(ve.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:K,onChange:ve=>Y(ve.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),i.jsx("input",{type:"url",value:ae,onChange:ve=>$(ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:W,onChange:ve=>ee(ve.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:()=>ye(!1),children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!R.trim()||Q.isPending,children:Q.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("projectDetail.bom.addPart")})]})]}),N?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):_&&_.length>0?i.jsxs("div",{className:"space-y-2",children:[_.filter(ve=>!me||!ve.is_complete).map(ve=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${ve.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:je?.id===ve.id?i.jsxs("form",{onSubmit:ze,className:"space-y-3",children:[i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[i.jsx("input",{type:"text",value:oe,onChange:He=>_e(He.target.value),className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.partName"),autoFocus:!0}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"number",value:se,onChange:He=>Oe(parseInt(He.target.value)||1),className:"w-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white focus:outline-none focus:border-bambu-green",min:"1",placeholder:n("projectDetail.bom.qty")}),i.jsx("input",{type:"number",step:"0.01",value:q,onChange:He=>X(He.target.value),className:"flex-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.price",{currency:j})})]})]}),i.jsx("input",{type:"url",value:de,onChange:He=>Z(He.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.sourcingUrlPlaceholder")}),i.jsx("input",{type:"text",value:ie,onChange:He=>le(He.target.value),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded px-3 py-2 text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:n("projectDetail.bom.remarksPlaceholder")}),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",size:"sm",onClick:Ie,children:n("common.cancel")}),i.jsx(Ce,{type:"submit",size:"sm",disabled:!oe.trim()||L.isPending,children:L.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):n("common.save")})]})]}):i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("button",{onClick:()=>s("projects:update")&&he(ve),disabled:L.isPending||!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noUpdatePermission"),className:`w-5 h-5 mt-0.5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${ve.is_complete?"bg-status-ok border-status-ok text-white":s("projects:update")?"border-bambu-gray hover:border-bambu-green":"border-bambu-gray/50 cursor-not-allowed"}`,children:ve.is_complete&&i.jsx(pr,{className:"w-3 h-3"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsxs("p",{className:`text-sm font-medium ${ve.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[ve.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",ve.quantity_needed]})]}),ve.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[j,(ve.unit_price*ve.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&fe(ve),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.edit"):n("projectDetail.bom.noEditPermission"),children:i.jsx($a,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("projects:update")&&be(ve.id,ve.name),disabled:!s("projects:update"),className:`p-1 rounded transition-colors flex-shrink-0 ${s("projects:update")?"hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("projects:update")?n("common.delete"):n("projectDetail.bom.noDeletePermission"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]}),ve.sourcing_url&&i.jsxs("a",{href:ve.sourcing_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 mt-1 text-xs text-blue-400 hover:text-blue-300 transition-colors",onClick:He=>He.stopPropagation(),children:[i.jsx(Kr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(ve.sourcing_url).hostname.replace("www.","")}catch{return ve.sourcing_url}})()})]}),ve.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:ve.remarks})]})]})},ve.id)),_.some(ve=>ve.unit_price!==null)&&i.jsxs("div",{className:"pt-2 mt-2 border-t border-bambu-dark-tertiary flex justify-between text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.bom.totalCost")}),i.jsxs("span",{className:"text-white font-medium",children:[j,_.reduce((ve,He)=>ve+(He.unit_price||0)*He.quantity_needed,0).toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsx("div",{className:"flex items-center justify-between mb-3",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(mv,{className:"w-5 h-5"}),n("projectDetail.timeline.title")]})}),A?i.jsx("div",{className:"flex items-center justify-center py-4",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):k&&k.length>0?i.jsx("div",{className:"space-y-3",children:k.slice(0,10).map((ve,He)=>i.jsxs("div",{className:"flex gap-3",children:[i.jsxs("div",{className:`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${ve.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":ve.event_type==="print_failed"?"bg-status-error/20 text-status-error":ve.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[ve.event_type==="print_completed"&&i.jsx(pr,{className:"w-4 h-4"}),ve.event_type==="print_failed"&&i.jsx(hi,{className:"w-4 h-4"}),ve.event_type==="print_started"&&i.jsx(xr,{className:"w-4 h-4"}),ve.event_type==="queued"&&i.jsx(n3,{className:"w-4 h-4"}),ve.event_type==="project_created"&&i.jsx(Xn,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:ve.title}),ve.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:ve.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:Ee(ve.timestamp)})]})]},He))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.timeline.empty")})]})}),!p.is_template&&i.jsx("div",{className:"flex justify-end",children:i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>tt.mutate(),disabled:tt.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[tt.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(Yl,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),Se&&(Se.queued_prints>0||Se.in_progress_prints>0)&&i.jsx(vt,{children:i.jsxs(_t,{className:"p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(n3,{className:"w-5 h-5"}),n("projectDetail.queue.title")]}),i.jsx(Ks,{to:`/queue?project=${f}`,className:"text-sm text-bambu-green hover:underline",children:n("projectDetail.queue.viewAll")})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[Se.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:Se.in_progress_prints})}),Se.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:Se.queued_prints})})]})]})}),i.jsxs("div",{children:[i.jsx("div",{className:"flex items-center justify-between mb-4",children:i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(fi,{className:"w-5 h-5"}),n("projectDetail.prints.title",{count:g?.length||0})]})}),y?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})}):i.jsx(XZe,{archives:g||[],t:n})]}),o&&i.jsx(Uie,{t:n,project:{...p,archive_count:Se?.total_archives||0,total_items:Se?.total_items||0,completed_count:Se?.completed_prints||0,failed_count:Se?.failed_prints||0,queue_count:Se?.queued_prints||0,progress_percent:Se?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:ve=>E.mutate(ve),isLoading:E.isPending}),Fe.isOpen&&i.jsx(gn,{title:Fe.title,message:Fe.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Fe.onConfirm,onCancel:()=>pe(ve=>({...ve,isOpen:!1}))})]})}function JZe({parentId:t,onClose:e,onSave:n,isLoading:r,t:a}){const[s,o]=w.useState(""),l=c=>{c.preventDefault(),n({name:s.trim(),parent_id:t})};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:a("fileManager.newFolder")})}),i.jsxs("form",{onSubmit:l,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:a("fileManager.folderName")}),i.jsx("input",{type:"text",value:s,onChange:c=>o(c.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",placeholder:a("fileManager.folderNamePlaceholder"),autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function eJe({type:t,currentName:e,onClose:n,onSave:r,isLoading:a,t:s}){const[o,l]=w.useState(e),c=u=>{u.preventDefault(),o.trim()&&o.trim()!==e&&r(o.trim())};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(t==="file"?"fileManager.renameFile":"fileManager.renameFolder")})}),i.jsxs("form",{onSubmit:c,className:"p-4 space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:s("common.name")}),i.jsx("input",{type:"text",value:o,onChange:u=>l(u.target.value),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded px-3 py-2 text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green",autoFocus:!0,required:!0})]}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(Ce,{type:"submit",disabled:!o.trim()||o.trim()===e||a,children:a?i.jsx(it,{className:"w-4 h-4 animate-spin"}):s("common.rename")})]})]})]})})}function tJe({folders:t,selectedFiles:e,currentFolderId:n,onClose:r,onMove:a,isLoading:s,t:o}){const[l,c]=w.useState(null),u=(h,f=0)=>{const p=[];for(const x of h)p.push({id:x.id,name:x.name,depth:f}),x.children.length>0&&p.push(...u(x.children,f+1));return p},d=[{id:null,name:o("fileManager.rootNoFolder"),depth:0},...u(t)];return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-sm border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"p-4 border-b border-bambu-dark-tertiary",children:i.jsx("h2",{className:"text-lg font-semibold text-white",children:o("fileManager.moveFiles",{count:e.length})})}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1",children:d.map(h=>i.jsxs("button",{onClick:()=>c(h.id),disabled:h.id===n,className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===h.id?"bg-bambu-green/20 text-bambu-green":h.id===n?"opacity-50 cursor-not-allowed text-bambu-gray":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${12+h.depth*16}px`},children:[i.jsx(Zl,{className:"w-4 h-4"}),h.name,h.id===n&&i.jsxs("span",{className:"text-xs text-bambu-gray ml-auto",children:["(",o("fileManager.current"),")"]})]},h.id??"root"))}),i.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(Ce,{onClick:()=>a(l),disabled:s,children:s?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function nJe({folder:t,onClose:e,onLink:n,isLoading:r,t:a}){const[s,o]=w.useState("project"),[l,c]=w.useState(t.project_id||t.archive_id||null);w.useState(()=>{t.archive_id&&o("archive")});const{data:u}=Je({queryKey:["projects"],queryFn:()=>ne.getProjects()}),{data:d}=Je({queryKey:["archives-for-link"],queryFn:()=>ne.getArchives(void 0,void 0,100)}),h=()=>{n(s==="project"?{project_id:l,archive_id:0}:{project_id:0,archive_id:l})},f=()=>{n({project_id:0,archive_id:0})},p=t.project_id||t.archive_id;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-md border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[i.jsx(Eh,{className:"w-5 h-5 text-bambu-green"}),a("fileManager.linkFolder")]}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:a("fileManager.linkFolderDescription",{name:t.name})}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("button",{onClick:()=>{o("project"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="project"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(JK,{className:"w-4 h-4"}),a("fileManager.project")]}),i.jsxs("button",{onClick:()=>{o("archive"),c(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${s==="archive"?"border-bambu-green bg-bambu-green/10 text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,children:[i.jsx(js,{className:"w-4 h-4"}),a("fileManager.archive")]})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto space-y-1 bg-bambu-dark rounded-lg p-2",children:s==="project"?u&&u.length>0?u.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx("div",{className:"w-3 h-3 rounded-full flex-shrink-0",style:{backgroundColor:x.color||"#00ae42"}}),i.jsx("span",{className:"truncate",children:x.name})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noProjectsFound")}):d&&d.length>0?d.map(x=>i.jsxs("button",{onClick:()=>c(x.id),className:`w-full text-left px-3 py-2 rounded transition-colors flex items-center gap-2 ${l===x.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark-tertiary text-white"}`,children:[i.jsx(df,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"truncate",children:x.print_name||x.filename})]},x.id)):i.jsx("p",{className:"text-sm text-bambu-gray text-center py-4",children:a("fileManager.noArchivesFound")})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-between",children:[p&&i.jsxs(Ce,{variant:"danger",onClick:f,disabled:r,children:[i.jsx(YC,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${p?"":"ml-auto"}`,children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Ce,{onClick:h,disabled:!l||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function rJe({folderId:t,onClose:e,onUploadComplete:n,t:r}){const[a,s]=w.useState([]),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,h]=w.useState(!0),[f,p]=w.useState(!1),[x,v]=w.useState(!0),g=w.useRef(null),y=V=>{V.preventDefault(),l(!0)},_=V=>{V.preventDefault(),l(!1)},N=V=>{V.preventDefault(),l(!1);const G=Array.from(V.dataTransfer.files);A(G)},k=V=>{V.target.files&&A(Array.from(V.target.files))},A=V=>{const G=V.map(z=>({file:z,status:"pending",isZip:z.name.toLowerCase().endsWith(".zip"),is3mf:z.name.toLowerCase().endsWith(".3mf")}));s(z=>[...z,...G])},M=V=>{s(G=>G.filter((z,K)=>K!==V))},C=a.some(V=>V.isZip&&V.status==="pending"),j=a.some(V=>V.file.name.toLowerCase().endsWith(".stl")&&V.status==="pending"),P=a.some(V=>V.is3mf&&V.status==="pending"),E=async()=>{if(a.length!==0){u(!0);for(let V=0;VG.map((z,K)=>K===V?{...z,status:"uploading"}:z));try{if(a[V].isZip){const G=await ne.extractZipFile(a[V].file,t,d,f,x);s(z=>z.map((K,Y)=>Y===V?{...K,status:G.errors.length>0&&G.extracted===0?"error":"success",extractedCount:G.extracted,error:G.errors.length>0?`${G.errors.length} files failed`:void 0}:K))}else await ne.uploadLibraryFile(a[V].file,t,x),s(G=>G.map((z,K)=>K===V?{...z,status:"success"}:z))}catch(G){s(z=>z.map((K,Y)=>Y===V?{...K,status:"error",error:G instanceof Error?G.message:"Upload failed"}:K))}}u(!1),n(),e()}},B=a.filter(V=>V.status==="pending").length,O=a.filter(V=>V.status==="success").length,U=a.filter(V=>V.status==="error").length,R=a.length>0&&B===0&&!c;return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("fileManager.uploadFiles")}),i.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark rounded",children:i.jsx(Ft,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("div",{onDragOver:y,onDragLeave:_,onDrop:N,onClick:()=>g.current?.click(),className:`border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors ${o?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,children:[i.jsx(Ra,{className:`w-10 h-10 mx-auto mb-3 ${o?"text-bambu-green":"text-bambu-gray"}`}),i.jsx("p",{className:"text-white font-medium",children:r(o?"fileManager.dropFilesHere":"fileManager.dragDropFiles")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("fileManager.orClickToBrowse")}),i.jsx("p",{className:"text-xs text-bambu-gray/70 mt-2",children:r("fileManager.allFileTypesSupported")})]}),i.jsx("input",{ref:g,type:"file",multiple:!0,className:"hidden",onChange:k}),C&&i.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(js,{className:"w-5 h-5 text-blue-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-blue-300 font-medium",children:r("fileManager.zipFilesDetected")}),i.jsx("p",{className:"text-xs text-blue-300/70 mt-1",children:r("fileManager.zipExtractOptions")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d,onChange:V=>h(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.preserveZipStructure")})]}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:f,onChange:V=>p(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.createFolderFromZip")})]})]})]})}),P&&i.jsx("div",{className:"p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(xr,{className:"w-5 h-5 text-purple-400 mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-purple-300 font-medium",children:r("fileManager.threemfDetected")}),i.jsx("p",{className:"text-xs text-purple-300/70 mt-1",children:r("fileManager.threemfExtractionInfo")})]})]})}),(j||C)&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx(Ju,{className:"w-5 h-5 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium",children:r("fileManager.stlThumbnailGeneration")}),i.jsx("p",{className:"text-xs text-bambu-green/70 mt-1",children:r(C&&!j?"fileManager.zipMayContainStl":"fileManager.thumbnailsCanBeGenerated")}),i.jsxs("label",{className:"flex items-center gap-2 mt-2 cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:x,onChange:V=>v(V.target.checked),className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("span",{className:"text-sm text-white",children:r("fileManager.generateThumbnailsForStl")})]})]})]})}),a.length>0&&i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-2",children:a.map((V,G)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[V.isZip?i.jsx(js,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(zC,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:V.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[(V.file.size/1024/1024).toFixed(2)," MB",V.isZip&&V.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),V.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:V.extractedCount})]})]})]}),V.status==="pending"&&i.jsx("button",{onClick:()=>M(G),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ft,{className:"w-4 h-4 text-bambu-gray"})}),V.status==="uploading"&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),V.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),V.status==="error"&&i.jsx("span",{title:V.error,children:i.jsx(hi,{className:"w-4 h-4 text-red-500"})})]},G))}),R&&i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[r("fileManager.uploadComplete",{succeeded:O}),U>0&&i.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:U})]})]})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:r(R?"common.close":"common.cancel")}),!R&&i.jsx(Ce,{onClick:E,disabled:B===0||c,children:c?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),r("fileManager.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),r("common.upload")," ",B>0?`(${B})`:""]})})]})]})})}function Bie({folder:t,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o=0,wrapNames:l=!1,hasPermission:c,t:u}){const[d,h]=w.useState(!0),[f,p]=w.useState(!1),x=t.children.length>0,v=t.project_id||t.archive_id;return i.jsxs("div",{children:[i.jsxs("div",{className:`group flex items-center gap-1 px-2 py-1.5 rounded cursor-pointer transition-colors ${e===t.id?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,style:{paddingLeft:`${8+o*12}px`},onClick:()=>n(t.id),children:[x?i.jsx("button",{onClick:g=>{g.stopPropagation(),h(!d)},className:"p-0.5 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(pi,{className:`w-3.5 h-3.5 transition-transform ${d?"rotate-90":""}`})}):i.jsx("div",{className:"w-4.5"}),i.jsx(Zl,{className:"w-4 h-4 text-bambu-green flex-shrink-0"}),i.jsx("span",{className:`text-sm flex-1 min-w-0 ${l?"break-all":"truncate"}`,title:t.name,children:t.name}),v&&i.jsxs("button",{onClick:g=>{g.stopPropagation(),a(t)},className:"flex-shrink-0 flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 transition-colors",title:`${t.project_name?`Project: ${t.project_name}`:`Archive: ${t.archive_name}`} (click to change)`,children:[i.jsx(Eh,{className:"w-3 h-3"}),t.project_name?i.jsx(JK,{className:"w-3 h-3"}):i.jsx(js,{className:"w-3 h-3"})]}),t.file_count>0&&i.jsx("span",{className:"flex-shrink-0 text-xs text-bambu-gray",children:t.file_count}),!v&&i.jsx("button",{onClick:g=>{g.stopPropagation(),a(t)},className:"flex-shrink-0 p-1 rounded hover:bg-bambu-dark-tertiary",title:u("fileManager.linkToProjectOrArchive"),children:i.jsx(Eh,{className:"w-3.5 h-3.5 text-bambu-gray hover:text-bambu-green"})}),i.jsx("div",{className:`flex-shrink-0 flex items-center gap-0.5 transition-opacity ${l?"":"opacity-0 group-hover:opacity-100"}`,onClick:g=>g.stopPropagation(),children:i.jsxs("div",{className:"relative",children:[i.jsx("button",{onClick:()=>p(!f),className:"p-1 rounded hover:bg-bambu-dark-tertiary",children:i.jsx(Ah,{className:"w-3.5 h-3.5 text-bambu-gray"})}),f&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>p(!1)}),i.jsxs("div",{className:"absolute right-0 top-full mt-1 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[120px]",children:[i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(s(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionRenameFolder"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),u("common.rename")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:update_all")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:update_all")&&(a(t),p(!1))},disabled:!c("library:update_all"),title:c("library:update_all")?void 0:u("fileManager.noPermissionLinkFolder"),children:[i.jsx(Eh,{className:"w-3.5 h-3.5"}),u(v?"fileManager.changeLink":"fileManager.linkTo")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${c("library:delete_all")?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{c("library:delete_all")&&(r(t.id),p(!1))},disabled:!c("library:delete_all"),title:c("library:delete_all")?void 0:u("fileManager.noPermissionDeleteFolder"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),u("common.delete")]})]})]})]})})]}),x&&d&&i.jsx("div",{children:t.children.map(g=>i.jsx(Bie,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},g.id))})]})}function tF(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function aJe({file:t,isSelected:e,isMobile:n,onSelect:r,onDelete:a,onDownload:s,onAddToQueue:o,onPrint:l,onPreview3d:c,onRename:u,onGenerateThumbnail:d,thumbnailVersion:h,hasPermission:f,canModify:p,authEnabled:x,t:v}){const[g,y]=w.useState(!1);return i.jsxs("div",{className:`group relative bg-bambu-dark-secondary rounded-lg border transition-all cursor-pointer overflow-hidden ${e?"border-bambu-green ring-1 ring-bambu-green":"border-bambu-dark-tertiary hover:border-bambu-green/50"}`,onClick:()=>r(t.id),children:[i.jsxs("div",{className:"aspect-square bg-bambu-dark flex items-center justify-center overflow-hidden",children:[t.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(t.id)}${h?`?v=${h}`:""}`,alt:t.filename,className:"w-full h-full object-cover"}):i.jsx(df,{className:"w-12 h-12 text-bambu-gray/30"}),i.jsx("div",{className:`absolute top-2 right-2 text-xs px-1.5 py-0.5 rounded font-medium ${t.file_type==="3mf"?"bg-bambu-green/90 text-white":t.file_type==="gcode"?"bg-blue-500/90 text-white":t.file_type==="stl"?"bg-purple-500/90 text-white":"bg-bambu-gray/90 text-white"}`,children:t.file_type.toUpperCase()})]}),i.jsxs("div",{className:"p-3",children:[i.jsx("h3",{className:"text-sm font-medium text-white truncate",title:t.print_name||t.filename,children:t.print_name||t.filename}),i.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-bambu-gray",children:[i.jsx("span",{children:ul(t.file_size)}),t.print_time_seconds&&i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(Gn,{className:"w-3 h-3"}),Qs(t.print_time_seconds)]})]}),t.sliced_for_model&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(xr,{className:"w-3 h-3"}),t.sliced_for_model]}),t.print_count>0&&i.jsx("div",{className:"mt-1 text-xs text-bambu-green",children:v("fileManager.printedCount",{count:t.print_count})}),x&&t.created_by_username&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray flex items-center gap-1",children:[i.jsx(td,{className:"w-3 h-3"}),t.created_by_username]})]}),i.jsxs("div",{className:`absolute bottom-2 right-2 transition-opacity ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`,onClick:_=>_.stopPropagation(),children:[i.jsx("button",{onClick:()=>y(!g),className:"p-1.5 rounded bg-bambu-dark-secondary/90 hover:bg-bambu-dark-tertiary",children:i.jsx(Ah,{className:"w-4 h-4 text-bambu-gray"})}),g&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>y(!1)}),i.jsxs("div",{className:"absolute right-0 bottom-8 z-20 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 min-w-[140px]",children:[l&&tF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("printers:control")?"text-bambu-green hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("printers:control")&&(l(t),y(!1))},disabled:!f("printers:control"),title:f("printers:control")?void 0:v("fileManager.noPermissionPrint"),children:[i.jsx(xr,{className:"w-3.5 h-3.5"}),v("common.print")]}),o&&tF(t.filename)&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("queue:create")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("queue:create")&&(o(t.id),y(!1))},disabled:!f("queue:create"),title:f("queue:create")?void 0:v("fileManager.noPermissionAddToQueue"),children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),v("fileManager.schedulePrint")]}),c&&(t.file_type==="3mf"||t.file_type==="gcode"||t.file_type==="stl")&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(c(t),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:"You do not have permission to preview files",children:[i.jsx(Ja,{className:"w-3.5 h-3.5"}),"3D Preview"]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${f("library:read")?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{f("library:read")&&(s(t.id),y(!1))},disabled:!f("library:read"),title:f("library:read")?void 0:v("fileManager.noPermissionDownload"),children:[i.jsx(ua,{className:"w-3.5 h-3.5"}),v("common.download")]}),u&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(u(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionRenameFile"),children:[i.jsx($a,{className:"w-3.5 h-3.5"}),v("common.rename")]}),d&&t.file_type==="stl"&&i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","update",t.created_by_id)?"text-white hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","update",t.created_by_id)&&(d(t),y(!1))},disabled:!p("library","update",t.created_by_id),title:p("library","update",t.created_by_id)?void 0:v("fileManager.noPermissionGenerateThumbnail"),children:[i.jsx(Ju,{className:"w-3.5 h-3.5"}),v("fileManager.generateThumbnail")]}),i.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-sm flex items-center gap-2 ${p("library","delete",t.created_by_id)?"text-red-400 hover:bg-bambu-dark":"text-bambu-gray cursor-not-allowed"}`,onClick:()=>{p("library","delete",t.created_by_id)&&(a(t.id),y(!1))},disabled:!p("library","delete",t.created_by_id),title:p("library","delete",t.created_by_id)?void 0:v("fileManager.noPermissionDeleteFile"),children:[i.jsx(Jt,{className:"w-3.5 h-3.5"}),v("common.delete")]})]})]})]}),i.jsx("div",{className:`absolute top-2 left-2 w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${e?"bg-bambu-green border-bambu-green":`border-white/30 bg-black/30 ${n?"opacity-100":"opacity-0 group-hover:opacity-100"}`}`,children:e&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})})]})}function iJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Or(),[l]=dF(),c=l.get("folder"),u=c?parseInt(c,10):null,[d,h]=w.useState(u),[f,p]=w.useState([]),[x,v]=w.useState(!1),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(null),[M,C]=w.useState(null),[j,P]=w.useState(null),[E,B]=w.useState(null),[O,U]=w.useState(null),[R,V]=w.useState(null),[G,z]=w.useState({}),[K,Y]=w.useState(null),[ae,$]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[W,ee]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[J,ye]=w.useState(()=>{const Ue=localStorage.getItem("library-sidebar-width");return Ue?parseInt(Ue,10):256}),[me,te]=w.useState(!1),je=w.useRef(null);w.useEffect(()=>{if(!me)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Ue=wt=>{if(!je.current)return;const qt=je.current.parentElement?.getBoundingClientRect();if(!qt)return;const Cn=wt.clientX-qt.left,yr=Math.min(500,Math.max(200,Cn));ye(yr)},bt=()=>{te(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(J))};return document.addEventListener("mousemove",Ue),document.addEventListener("mouseup",bt),()=>{document.removeEventListener("mousemove",Ue),document.removeEventListener("mouseup",bt),document.body.style.userSelect="",document.body.style.cursor=""}},[me,J]);const[ue,oe]=w.useState(""),[_e,se]=w.useState("all"),[Oe,q]=w.useState(""),[X,de]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[Z,ie]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),le=sne();w.useEffect(()=>{const Ue=l.get("folder");if(Ue){const bt=parseInt(Ue,10);h(bt)}},[l]);const{data:Fe}=Je({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:pe,isLoading:Q}=Je({queryKey:["library-folders"],queryFn:()=>ne.getLibraryFolders()}),{data:L,isLoading:D}=Je({queryKey:["library-files",d],queryFn:()=>ne.getLibraryFiles(d,d===null)}),{data:H}=Je({queryKey:["library-stats"],queryFn:()=>ne.getLibraryStats()}),{data:he}=Je({queryKey:["users"],queryFn:()=>ne.getUsers()}),be=w.useMemo(()=>{if(!L)return[];const Ue=new Set(L.map(bt=>bt.file_type));return Array.from(Ue).sort()},[L]),fe=w.useMemo(()=>{if(!L)return[];let Ue=[...L];if(ue.trim()){const bt=ue.toLowerCase();Ue=Ue.filter(wt=>wt.filename.toLowerCase().includes(bt)||wt.print_name&&wt.print_name.toLowerCase().includes(bt))}if(_e!=="all"&&(Ue=Ue.filter(bt=>bt.file_type===_e)),Oe.trim()){const bt=Oe.toLowerCase();Ue=Ue.filter(wt=>wt.created_by_username&&wt.created_by_username.toLowerCase().includes(bt))}return Ue.sort((bt,wt)=>{let qt=0;switch(X){case"name":qt=(bt.print_name||bt.filename).localeCompare(wt.print_name||wt.filename);break;case"date":qt=new Date(bt.created_at).getTime()-new Date(wt.created_at).getTime();break;case"size":qt=bt.file_size-wt.file_size;break;case"type":qt=bt.file_type.localeCompare(wt.file_type);break;case"prints":qt=bt.print_count-wt.print_count;break}return Z==="asc"?qt:-qt}),Ue},[L,ue,_e,Oe,X,Z]),ze=w.useMemo(()=>{if(!H||!Fe)return!1;const Ue=(Fe.library_disk_warning_gb||5)*1024*1024*1024;return H.disk_free_bytesne.createLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Ue=>n(Ue.message,"error")}),qe=ot({mutationFn:Ue=>ne.deleteLibraryFolder(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===M?.id&&h(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),tt=ot({mutationFn:Ue=>ne.deleteLibraryFile(Ue),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),p(Ue=>Ue.filter(bt=>bt!==M?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Ue=>{C(null),n(Ue.message,"error")}}),Ee=ot({mutationFn:Ue=>ne.bulkDeleteLibrary(Ue,[]),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),n(t("fileManager.toast.filesDeleted",{count:bt.length}),"success"),p([]),C(null)},onError:Ue=>{C(null),n(Ue.message,"error")}}),Se=ot({mutationFn:({fileIds:Ue,folderId:bt})=>ne.moveLibraryFiles(Ue,bt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),p([]),y(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Ue=>n(Ue.message,"error")}),Me=ot({mutationFn:({id:Ue,data:bt})=>ne.updateLibraryFolder(Ue,bt),onSuccess:(Ue,bt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),A(null);const wt=bt.data.project_id===0&&bt.data.archive_id===0;n(t(wt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Ue=>n(Ue.message,"error")}),xe=ot({mutationFn:({id:Ue,filename:bt})=>ne.updateLibraryFile(Ue,{filename:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Ue=>{V(null),n(Ue.message,"error")}}),ve=ot({mutationFn:({id:Ue,name:bt})=>ne.updateLibraryFolder(Ue,{name:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),V(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Ue=>{V(null),n(Ue.message,"error")}}),He=ot({mutationFn:()=>ne.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Date.now(),wt={};Ue.results.forEach(qt=>{qt.success&&(wt[qt.file_id]=bt)}),z(qt=>({...qt,...wt}))}Ue.succeeded>0&&Ue.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Ue.succeeded}),"success"):Ue.succeeded>0&&Ue.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Ue.succeeded,failed:Ue.failed}),"success"):Ue.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),Pe=ot({mutationFn:Ue=>ne.batchGenerateStlThumbnails({file_ids:[Ue]}),onSuccess:Ue=>{if(e.invalidateQueries({queryKey:["library-files"]}),Ue.succeeded>0){const bt=Ue.results[0]?.file_id;bt&&z(wt=>({...wt,[bt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Ue.results[0]?.error||"Unknown error"}),"error")},onError:Ue=>n(Ue.message,"error")}),nt=w.useCallback(Ue=>{const bt=Ue.toLowerCase();return bt.endsWith(".gcode")||bt.includes(".gcode.")},[]),Te=w.useMemo(()=>L?L.filter(Ue=>f.includes(Ue.id)&&nt(Ue.filename)):[],[L,f,nt]),Ge=w.useCallback(Ue=>{p(bt=>bt.includes(Ue)?bt.filter(wt=>wt!==Ue):[...bt,Ue])},[]),Re=w.useCallback(()=>{fe.length>0&&p(fe.map(Ue=>Ue.id))},[fe]),Le=w.useCallback(()=>{p([])},[]),Ke=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ft=Ue=>{ne.downloadLibraryFile(Ue).catch(bt=>{console.error("Library file download failed:",bt)})},kt=()=>{M&&(M.type==="file"?tt.mutate(M.id):M.type==="folder"?qe.mutate(M.id):M.type==="bulk"&&Ee.mutate(f))},Lt=qe.isPending||tt.isPending||Ee.isPending,Kt=Ue=>{$(Ue),localStorage.setItem("library-view-mode",Ue)},Mt=Q||D;return i.jsxs("div",{className:"p-4 md:p-8 min-h-[calc(100vh-64px)] lg:h-[calc(100vh-64px)] flex flex-col",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[i.jsx("div",{className:"p-2.5 bg-bambu-green/10 rounded-xl",children:i.jsx(Zl,{className:"w-6 h-6 text-bambu-green"})}),t("fileManager.title")]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-2 ml-14",children:t("fileManager.subtitle")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center bg-bambu-dark rounded-lg p-1",children:[i.jsx("button",{onClick:()=>Kt("grid"),className:`p-1.5 rounded transition-colors ${ae==="grid"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.gridView"),children:i.jsx(c0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>Kt("list"),className:`p-1.5 rounded transition-colors ${ae==="list"?"bg-bambu-dark-secondary text-white":"text-bambu-gray hover:text-white"}`,title:t("fileManager.listView"),children:i.jsx(HC,{className:"w-4 h-4"})})]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>He.mutate(),disabled:He.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[He.isPending?i.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}):i.jsx(Ju,{className:"w-4 h-4 mr-2"}),t("fileManager.generateThumbnails")]}),i.jsxs(Ce,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(ume,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Ra,{className:"w-4 h-4 mr-2"}),t("common.upload")]})]})]}),ze&&H&&Fe&&i.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-amber-500/10 border border-amber-500/30 rounded-lg",children:[i.jsx(Tn,{className:"w-5 h-5 text-amber-500 flex-shrink-0"}),i.jsxs("div",{className:"flex-1",children:[i.jsx("p",{className:"text-sm text-amber-500 font-medium",children:t("fileManager.lowDiskSpaceWarning")}),i.jsx("p",{className:"text-xs text-amber-500/80",children:t("fileManager.lowDiskSpaceDetails",{free:ul(H.disk_free_bytes),total:ul(H.disk_total_bytes),threshold:Fe.library_disk_warning_gb})})]})]}),H&&i.jsxs("div",{className:"flex flex-wrap items-center gap-3 sm:gap-6 mb-6 p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(zC,{className:"w-4 h-4 text-bambu-green"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.files"),":"]}),i.jsx("span",{className:"text-white font-medium",children:H.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Zl,{className:"w-4 h-4 text-blue-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.folders"),":"]}),i.jsx("span",{className:"text-white font-medium",children:H.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Ub,{className:"w-4 h-4 text-amber-400"}),i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.size"),":"]}),i.jsx("span",{className:"text-white font-medium",children:ul(H.total_size_bytes)})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm sm:ml-auto",children:[i.jsxs("span",{className:"text-bambu-gray",children:[t("fileManager.free"),":"]}),i.jsx("span",{className:`font-medium ${ze?"text-amber-500":"text-white"}`,children:ul(H.disk_free_bytes)})]})]}),i.jsxs("div",{className:"flex-1 flex flex-col lg:flex-row gap-4 lg:gap-6 min-h-0",children:[i.jsx("div",{className:"lg:hidden",children:i.jsxs("select",{value:d??"",onChange:Ue=>h(Ue.target.value?parseInt(Ue.target.value,10):null),className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg px-3 py-2.5 text-white focus:outline-none focus:border-bambu-green",children:[i.jsxs("option",{value:"",children:["📁 ",t("fileManager.allFiles")]}),pe&&(()=>{const Ue=(bt,wt=0)=>{const qt=[];for(const Cn of bt)qt.push({id:Cn.id,name:Cn.name,fileCount:Cn.file_count,depth:wt}),Cn.children.length>0&&qt.push(...Ue(Cn.children,wt+1));return qt};return Ue(pe).map(bt=>i.jsxs("option",{value:bt.id,children:["│ ".repeat(bt.depth),"📂 ",bt.name," ",bt.fileCount>0?`(${bt.fileCount})`:""]},bt.id))})()]})}),i.jsxs("div",{ref:je,className:"hidden lg:flex flex-shrink-0 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden flex-col relative",style:{width:`${J}px`},children:[i.jsx("div",{className:`absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize z-10 group/resize flex items-center justify-center transition-colors ${me?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Ue=>{Ue.preventDefault(),te(!0)},onDoubleClick:()=>{ye(256),localStorage.setItem("library-sidebar-width","256")},title:t("fileManager.dragToResizeTooltip"),children:i.jsxs("div",{className:`flex flex-col gap-1 opacity-0 group-hover/resize:opacity-100 transition-opacity ${me?"opacity-100":""}`,children:[i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"}),i.jsx("div",{className:"w-0.5 h-0.5 rounded-full bg-white/70"})]})}),i.jsxs("div",{className:"p-3 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[i.jsx("h2",{className:"text-sm font-medium text-white",children:t("fileManager.folders")}),i.jsx("button",{onClick:()=>{const Ue=!W;ee(Ue),localStorage.setItem("library-wrap-folders",String(Ue))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${W?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(W?"fileManager.disableTextWrapping":"fileManager.enableTextWrapping"),children:t("fileManager.wrap")})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[i.jsxs("div",{className:`flex items-center gap-2 px-2 py-1.5 rounded cursor-pointer transition-colors ${d===null?"bg-bambu-green/20 text-bambu-green":"hover:bg-bambu-dark text-white"}`,onClick:()=>h(null),children:[i.jsx(df,{className:"w-4 h-4"}),i.jsx("span",{className:"text-sm",children:t("fileManager.allFiles")})]}),pe?.map(Ue=>i.jsx(Bie,{folder:Ue,selectedFolderId:d,onSelect:h,onDelete:bt=>C({type:"folder",id:bt}),onLink:A,onRename:bt=>V({type:"folder",id:bt.id,name:bt.name}),wrapNames:W,hasPermission:r,t},Ue.id))]})]}),i.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[L&&L.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-4 p-2 sm:p-3 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-0 z-10 lg:static",children:[i.jsxs("div",{className:"relative w-full sm:w-auto sm:flex-1 sm:max-w-xs",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:t("fileManager.searchFiles"),value:ue,onChange:Ue=>oe(Ue.target.value),className:"w-full pl-9 pr-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(UC,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:_e,onChange:Ue=>se(Ue.target.value),className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"all",children:t("fileManager.allTypes")}),be.map(Ue=>i.jsx("option",{value:Ue,children:Ue.toUpperCase()},Ue))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:Oe,onChange:Ue=>q(Ue.target.value),list:"usernames-list",className:`w-32 sm:w-40 px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green ${Oe?"pr-7":""}`,style:Oe?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),Oe&&i.jsx("button",{onClick:()=>q(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ft,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:he?.map(Ue=>i.jsx("option",{value:Ue.username},Ue.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:X,onChange:Ue=>{const bt=Ue.target.value;de(bt),localStorage.setItem("library-sort-field",bt)},className:"bg-bambu-dark border border-bambu-dark-tertiary rounded px-2 py-1.5 text-sm text-white focus:outline-none focus:border-bambu-green",children:[i.jsx("option",{value:"name",children:t("common.name")}),i.jsx("option",{value:"date",children:t("common.date")}),i.jsx("option",{value:"size",children:t("fileManager.size")}),i.jsx("option",{value:"type",children:t("common.type")}),i.jsx("option",{value:"prints",children:t("fileManager.prints")})]}),i.jsx("button",{onClick:()=>ie(Ue=>{const bt=Ue==="asc"?"desc":"asc";return localStorage.setItem("library-sort-direction",bt),bt}),className:"p-1.5 rounded bg-bambu-dark border border-bambu-dark-tertiary hover:border-bambu-green transition-colors",title:t(Z==="asc"?"fileManager.ascending":"fileManager.descending"),children:Z==="asc"?i.jsx(Tde,{className:"w-4 h-4 text-white"}):i.jsx(wde,{className:"w-4 h-4 text-white"})})]}),(ue||_e!=="all"||Oe)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:fe.length,total:L.length})})]}),fe.length>0&&i.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-4 p-2 bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary sticky top-[52px] z-10 lg:static",children:[f.length===fe.length&&f.length>0?i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,children:[i.jsx(vl,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.deselectAll")})]}):i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Re,children:[i.jsx(so,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.selectAll")})]}),f.length>0&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-sm text-bambu-gray ml-2",children:t("fileManager.selected",{count:f.length})}),i.jsx("div",{className:"hidden sm:block flex-1"}),i.jsxs("div",{className:"w-full sm:w-auto flex flex-wrap items-center gap-2 mt-2 sm:mt-0",children:[Te.length===1&&i.jsxs(Ce,{variant:"primary",size:"sm",onClick:()=>B(Te[0]),disabled:!r("printers:control"),title:r("printers:control")?void 0:t("fileManager.noPermissionPrint"),children:[i.jsx(io,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.print")})]}),Te.length===1&&i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>U(Te[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Gn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:()=>y(!0),disabled:!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?void 0:t("fileManager.noPermissionMoveFiles"),children:[i.jsx(bfe,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(Ce,{variant:"danger",size:"sm",onClick:()=>{f.length===1?C({type:"file",id:f[0]}):C({type:"bulk",id:0,count:f.length})},disabled:!a("library:delete_own","library:delete_all"),title:a("library:delete_own","library:delete_all")?void 0:t("fileManager.noPermissionDeleteFiles"),children:[i.jsx(Jt,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.delete")})]}),i.jsxs(Ce,{variant:"secondary",size:"sm",onClick:Le,children:[i.jsx(Ft,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),Mt?i.jsx("div",{className:"flex-1 flex items-center justify-center",children:i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("fileManager.loadingFiles")})]})}):L?.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(df,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t(d!==null?"fileManager.folderIsEmpty":"fileManager.noFilesYet")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t(d!==null?"fileManager.folderEmptyDescription":"fileManager.noFilesDescription")}),i.jsxs(Ce,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Xn,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):fe.length===0?i.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center",children:[i.jsx("div",{className:"p-4 bg-bambu-dark rounded-2xl mb-4",children:i.jsx(kr,{className:"w-12 h-12 text-bambu-gray/50"})}),i.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:t("fileManager.noMatchingFiles")}),i.jsx("p",{className:"text-bambu-gray text-center max-w-md mb-6",children:t("fileManager.noMatchingFilesDescription")}),i.jsx(Ce,{variant:"secondary",onClick:()=>{oe(""),se("all")},children:t("fileManager.clearFilters")})]}):ae==="grid"?i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4",children:fe.map(Ue=>i.jsx(aJe,{file:Ue,isSelected:f.includes(Ue.id),isMobile:le,t,onSelect:Ge,onDelete:bt=>C({type:"file",id:bt}),onDownload:ft,onAddToQueue:bt=>{const wt=L?.find(qt=>qt.id===bt);wt&&U(wt)},onPrint:P,onPreview3d:Y,onRename:bt=>V({type:"file",id:bt.id,name:bt.filename}),onGenerateThumbnail:bt=>Pe.mutate(bt.id),thumbnailVersion:G[Ue.id],hasPermission:r,canModify:s,authEnabled:o},Ue.id))})}):i.jsx("div",{className:"flex-1 lg:overflow-y-auto",children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("div",{className:`hidden sm:grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary text-xs text-bambu-gray font-medium`,children:[i.jsx("div",{className:"w-6"}),i.jsx("div",{children:t("common.name")}),o&&i.jsx("div",{children:t("fileManager.uploadedBy",{defaultValue:"Uploaded By"})}),i.jsx("div",{children:t("common.type")}),i.jsx("div",{children:t("fileManager.size")}),i.jsx("div",{children:t("fileManager.prints")}),i.jsx("div",{})]}),fe.map(Ue=>i.jsxs("div",{className:`grid ${o?"grid-cols-[auto_1fr_120px_100px_100px_100px_80px]":"grid-cols-[auto_1fr_100px_100px_100px_80px]"} gap-4 px-4 py-3 items-center border-b border-bambu-dark-tertiary last:border-b-0 cursor-pointer hover:bg-bambu-dark/50 transition-colors ${f.includes(Ue.id)?"bg-bambu-green/10":""}`,onClick:()=>Ge(Ue.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Ue.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Ue.id)&&i.jsx("div",{className:"w-2 h-2 bg-white rounded-sm"})}),i.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[i.jsxs("div",{className:"relative group/thumb",children:[i.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark flex-shrink-0 overflow-hidden",children:Ue.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:"",className:"w-full h-full object-cover"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(df,{className:"w-5 h-5 text-bambu-gray/50"})})}),Ue.thumbnail_path&&i.jsx("div",{className:"absolute left-0 top-full mt-2 z-50 hidden group-hover/thumb:block",children:i.jsx("div",{className:"w-48 h-48 rounded-lg bg-bambu-dark-secondary border border-bambu-dark-tertiary shadow-xl overflow-hidden",children:i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Ue.id)}${G[Ue.id]?`?v=${G[Ue.id]}`:""}`,alt:Ue.filename,className:"w-full h-full object-contain"})})})]}),i.jsx("div",{className:"min-w-0",children:i.jsx("div",{className:"text-sm text-white truncate",children:Ue.print_name||Ue.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Ue.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx(td,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:Ue.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Ue.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Ue.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Ue.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Ue.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:ul(Ue.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:Ue.print_count>0?`${Ue.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:bt=>bt.stopPropagation(),children:[tF(Ue.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&P(Ue),className:`p-1.5 rounded transition-colors ${r("printers:control")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("printers:control")?t("common.print"):t("fileManager.noPermissionPrint"),disabled:!r("printers:control"),children:i.jsx(xr,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>{r("queue:create")&&U(Ue)},className:`p-1.5 rounded transition-colors ${r("queue:create")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("queue:create")?t("fileManager.schedulePrint"):t("fileManager.noPermissionAddToQueue"),disabled:!r("queue:create"),children:i.jsx(Gn,{className:"w-4 h-4"})})]}),(Ue.file_type==="3mf"||Ue.file_type==="gcode"||Ue.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&Y(Ue),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?"3D Preview":"You do not have permission to preview files",disabled:!r("library:read"),children:i.jsx(Ja,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>r("library:read")&&ft(Ue.id),className:`p-1.5 rounded transition-colors ${r("library:read")?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:r("library:read")?t("common.download"):t("fileManager.noPermissionDownload"),disabled:!r("library:read"),children:i.jsx(ua,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&V({type:"file",id:Ue.id,name:Ue.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ue.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Ue.created_by_id),children:i.jsx($a,{className:"w-4 h-4"})}),Ue.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",Ue.created_by_id)&&Pe.mutate(Ue.id),className:`p-1.5 rounded transition-colors ${s("library","update",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-bambu-green":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Ue.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:Pe.isPending||!s("library","update",Ue.created_by_id),children:i.jsx(Ju,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",Ue.created_by_id)&&C({type:"file",id:Ue.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Ue.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-red-400":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","delete",Ue.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Ue.created_by_id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},Ue.id))]})})]})]}),x&&i.jsx(JZe,{parentId:d,onClose:()=>v(!1),onSave:Ue=>Ie.mutate(Ue),isLoading:Ie.isPending,t}),g&&pe&&i.jsx(tJe,{folders:pe,selectedFiles:f,currentFolderId:d,onClose:()=>y(!1),onMove:Ue=>Se.mutate({fileIds:f,folderId:Ue}),isLoading:Se.isPending,t}),_&&i.jsx(rJe,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ke,t}),k&&i.jsx(nJe,{folder:k,onClose:()=>A(null),onLink:Ue=>Me.mutate({id:k.id,data:Ue}),isLoading:Me.isPending,t}),M&&i.jsx(gn,{title:M.type==="folder"?t("fileManager.deleteFolder"):M.type==="bulk"?t("fileManager.deleteFilesCount",{count:M.count}):t("fileManager.deleteFile"),message:M.type==="folder"?t("fileManager.deleteFolderConfirm"):M.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:M.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Lt,loadingText:t("fileManager.deleting"),onConfirm:kt,onCancel:()=>C(null)}),j&&i.jsx(Xu,{mode:"reprint",libraryFileId:j.id,archiveName:j.print_name||j.filename,onClose:()=>P(null),onSuccess:()=>{P(null),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),E&&i.jsx(Xu,{mode:"reprint",libraryFileId:E.id,archiveName:E.print_name||E.filename,onClose:()=>B(null),onSuccess:()=>{B(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["archives"]})}}),O&&i.jsx(Xu,{mode:"add-to-queue",libraryFileId:O.id,archiveName:O.print_name||O.filename,onClose:()=>U(null),onSuccess:()=>{U(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),K&&i.jsx(hI,{libraryFileId:K.id,title:K.print_name||K.filename,fileType:K.file_type,onClose:()=>Y(null)}),R&&i.jsx(eJe,{type:R.type,currentName:R.name,onClose:()=>V(null),onSave:Ue=>{R.type==="file"?xe.mutate({id:R.id,filename:Ue}):ve.mutate({id:R.id,name:Ue})},isLoading:xe.isPending||ve.isPending,t})]})}const Pj=5,sJe=2e3,oJe=3e4,lJe=5e3;function cJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Or(),{printerId:a}=i0(),s=parseInt(a||"0",10),[o,l]=w.useState("stream"),[c,u]=w.useState(!1),[d,h]=w.useState(!1),[f,p]=w.useState(!0),[x,v]=w.useState(Date.now()),[g,y]=w.useState(!1),[_,N]=w.useState(!1),[k,A]=w.useState(0),[M,C]=w.useState(!1),[j,P]=w.useState(0),[E,B]=w.useState(1),[O,U]=w.useState({x:0,y:0}),[R,V]=w.useState(!1),[G,z]=w.useState({x:0,y:0}),[K,Y]=w.useState(null),[ae,$]=w.useState(null),W=w.useRef(null),ee=w.useRef(null),J=w.useRef(null),ye=w.useRef(null),me=w.useRef(null),{data:te}=Je({queryKey:["printer",s],queryFn:()=>ne.getPrinter(s),enabled:s>0}),{data:je}=Je({queryKey:["printerStatus",s],queryFn:()=>ne.getPrinterStatus(s),refetchInterval:3e4,enabled:s>0}),ue=ot({mutationFn:Se=>ne.setChamberLight(s,Se),onMutate:async Se=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Me=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],xe=>({...xe,chamber_light:Se})),{previousStatus:Me}},onSuccess:(Se,Me)=>{n(`Chamber light ${Me?"on":"off"}`)},onError:(Se,Me,xe)=>{xe?.previousStatus&&e.setQueryData(["printerStatus",s],xe.previousStatus),n(Se.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(je?.state==="RUNNING"||je?.state==="PAUSE")&&(je?.printable_objects_count??0)>=2;w.useEffect(()=>(te&&(document.title=`${te.name} - Camera`),()=>{document.title="Bambuddy"}),[te]);const _e=w.useRef(!1);w.useEffect(()=>{const Se=`/api/v1/printers/${s}/camera/stop`;_e.current=!1;const Me=()=>{if(s>0&&!_e.current){_e.current=!0;const He={},Pe=nd();Pe&&(He.Authorization=`Bearer ${Pe}`),fetch(Se,{method:"POST",keepalive:!0,headers:He}).catch(()=>{})}},xe=()=>{Me()};window.addEventListener("beforeunload",xe);const ve=W.current;return()=>{window.removeEventListener("beforeunload",xe),ve&&(ve.src=""),Me()}},[s]),w.useEffect(()=>{if(f&&!g){const Me=setTimeout(()=>{p(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Me)}},[o,f,x,g]),w.useEffect(()=>{const Se=()=>{const Me=!!document.fullscreenElement;N(Me),B(1),U({x:0,y:0}),o==="stream"&&!g&&(W.current&&(W.current.src=""),setTimeout(()=>{p(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",Se),()=>document.removeEventListener("fullscreenchange",Se)},[o,g]),w.useEffect(()=>{let Se;const Me=()=>{clearTimeout(Se),Se=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Me),()=>{clearTimeout(Se),window.removeEventListener("resize",Me)}},[]),w.useEffect(()=>()=>{J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),me.current&&clearInterval(me.current)},[]);const se=w.useCallback(()=>{if(k>=Pj){C(!1),h(!0);return}const Se=Math.min(sJe*Math.pow(2,k),oJe);C(!0),P(Math.ceil(Se/1e3)),ye.current=setInterval(()=>{P(Me=>Me<=1?(ye.current&&clearInterval(ye.current),0):Me-1)},1e3),J.current=setTimeout(()=>{A(Me=>Me+1),C(!1),p(!0),h(!1),W.current&&(W.current.src=""),v(Date.now())},Se)},[k]);w.useEffect(()=>{if(o!=="stream"||f||M||g){me.current&&(clearInterval(me.current),me.current=null);return}return me.current=setInterval(async()=>{try{const Se=await ne.getCameraStatus(s);(Se.stalled||!Se.active&&!d)&&(console.log(`Stream issue detected: stalled=${Se.stalled}, active=${Se.active}, reconnecting...`),me.current&&(clearInterval(me.current),me.current=null),p(!1),se())}catch{}},lJe),()=>{me.current&&(clearInterval(me.current),me.current=null)}},[o,f,d,M,g,s,se]);const Oe=()=>{p(!1),o==="stream"&&k{if(p(!1),h(!1),A(0),C(!1),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&!localStorage.getItem("cameraWindowState")){const Se=W.current,Me=Se.naturalWidth,xe=Se.naturalHeight;if(Me>0&&xe>0){const Pe=window.outerWidth-window.innerWidth,nt=window.outerHeight-window.innerHeight,Te=Me+16+Pe,Ge=xe+45+16+nt;try{window.resizeTo(Te,Ge)}catch{}}}},X=()=>{if(s>0){const Se={},Me=nd();Me&&(Se.Authorization=`Bearer ${Me}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:Se}).catch(()=>{})}},de=Se=>{o===Se||g||(y(!0),p(!0),h(!1),A(0),C(!1),B(1),U({x:0,y:0}),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&(W.current.src=""),o==="stream"&&X(),setTimeout(()=>{l(Se),v(Date.now()),y(!1)},100))},Z=()=>{g||(y(!0),p(!0),h(!1),A(0),C(!1),J.current&&clearTimeout(J.current),ye.current&&clearInterval(ye.current),W.current&&(W.current.src=""),o==="stream"&&X(),setTimeout(()=>{v(Date.now()),y(!1)},100))},ie=()=>{ee.current&&(document.fullscreenElement?document.exitFullscreen():ee.current.requestFullscreen())},le=()=>{B(Se=>Math.min(Se+.5,4))},Fe=()=>{B(Se=>{const Me=Math.max(Se-.5,1);return Me===1&&U({x:0,y:0}),Me})},pe=Se=>{Se.preventDefault(),Se.deltaY<0?le():Fe()},Q=Se=>{E>1&&(Se.preventDefault(),V(!0),z({x:Se.clientX-O.x,y:Se.clientY-O.y}))},L=w.useCallback(()=>{if(!ee.current)return{x:300,y:200};const Se=ee.current.getBoundingClientRect(),Me=Se.width*(E-1)/2,xe=Se.height*(E-1)/2;return{x:Math.max(50,Me),y:Math.max(50,xe)}},[E]),D=Se=>{if(R&&E>1){const Me=Se.clientX-G.x,xe=Se.clientY-G.y,ve=L();U({x:Math.max(-ve.x,Math.min(ve.x,Me)),y:Math.max(-ve.y,Math.min(ve.y,xe))})}},H=()=>{V(!1)},he=Se=>{if(Se.length<2)return 0;const Me=Se[0].clientX-Se[1].clientX,xe=Se[0].clientY-Se[1].clientY;return Math.sqrt(Me*Me+xe*xe)},be=Se=>Se.length<2?{x:Se[0].clientX,y:Se[0].clientY}:{x:(Se[0].clientX+Se[1].clientX)/2,y:(Se[0].clientY+Se[1].clientY)/2},fe=Se=>{Se.touches.length===2?(Se.preventDefault(),Y(he(Se.touches)),$(be(Se.touches))):Se.touches.length===1&&E>1&&(Se.preventDefault(),V(!0),z({x:Se.touches[0].clientX-O.x,y:Se.touches[0].clientY-O.y}))},ze=Se=>{if(Se.touches.length===2&&K!==null){Se.preventDefault();const Me=he(Se.touches),xe=Me/K;B(He=>{const Pe=Math.max(1,Math.min(4,He*xe));return Pe===1&&U({x:0,y:0}),Pe}),Y(Me);const ve=be(Se.touches);if(ae){const He=L();U(Pe=>({x:Math.max(-He.x,Math.min(He.x,Pe.x+(ve.x-ae.x))),y:Math.max(-He.y,Math.min(He.y,Pe.y+(ve.y-ae.y)))}))}$(ve)}else if(Se.touches.length===1&&R&&E>1){Se.preventDefault();const Me=Se.touches[0].clientX-G.x,xe=Se.touches[0].clientY-G.y,ve=L();U({x:Math.max(-ve.x,Math.min(ve.x,Me)),y:Math.max(-ve.y,Math.min(ve.y,xe))})}},Ie=Se=>{Se.touches.length<2&&(Y(null),$(null)),Se.touches.length===0&&V(!1)},qe=()=>{B(1),U({x:0,y:0})},tt=g?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`,Ee=f||g||M;return s?i.jsxs("div",{ref:ee,className:"min-h-screen bg-black flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary",children:[i.jsxs("h1",{className:"text-sm font-medium text-white flex items-center gap-2",children:[i.jsx(sb,{className:"w-4 h-4"}),te?.name||`Printer ${s}`]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex bg-bambu-dark rounded p-0.5",children:[i.jsx("button",{onClick:()=>de("stream"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="stream"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.live")}),i.jsx("button",{onClick:()=>de("snapshot"),disabled:Ee,className:`px-3 py-1 text-xs rounded transition-colors ${o==="snapshot"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white disabled:opacity-50"}`,children:t("camera.snapshot")})]}),i.jsx("button",{onClick:()=>ue.mutate(!je?.chamber_light),disabled:!je?.connected||ue.isPending||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${je?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30":"hover:bg-bambu-dark-tertiary"}`,title:r("printers:control")?t("camera.chamberLight"):t("printers.permission.noControl"),children:i.jsx(aL,{on:je?.chamber_light??!1,className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>u(!0),disabled:!oe||!r("printers:control"),className:`p-1.5 rounded disabled:opacity-50 ${oe&&r("printers:control")?"hover:bg-bambu-dark-tertiary":""}`,title:r("printers:control")?t(oe?"printers.skipObjects.tooltip":"printers.skipObjects.onlyWhilePrinting"):t("printers.permission.noControl"),children:i.jsx(lk,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:Z,disabled:Ee,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded disabled:opacity-50",title:t(o==="stream"?"camera.restartStream":"camera.refreshSnapshot"),children:i.jsx(Cr,{className:`w-4 h-4 text-bambu-gray ${Ee?"animate-spin":""}`})}),i.jsx("button",{onClick:ie,className:"p-1.5 hover:bg-bambu-dark-tertiary rounded",title:t(_?"camera.exitFullscreen":"camera.fullscreen"),children:_?i.jsx(oX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(ife,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:pe,onMouseMove:D,onMouseUp:H,onMouseLeave:H,onTouchStart:fe,onTouchMove:ze,onTouchEnd:Ie,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(f||g)&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/50 z-10",children:i.jsxs("div",{className:"text-center",children:[i.jsx(Cr,{className:"w-8 h-8 text-bambu-gray animate-spin mx-auto mb-2"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t(o==="stream"?"camera.connectingToCamera":"camera.capturingSnapshot")})]})}),M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/80 z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Pf,{className:"w-10 h-10 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.connectionLost")}),i.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:t("camera.reconnecting",{countdown:j,attempt:k+1,max:Pj})}),i.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white text-sm rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.reconnectNow")})]})}),d&&!M&&i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black z-10",children:i.jsxs("div",{className:"text-center p-4",children:[i.jsx(Tn,{className:"w-12 h-12 text-orange-400 mx-auto mb-3"}),i.jsx("p",{className:"text-white mb-2",children:t("camera.cameraUnavailable")}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 max-w-md",children:t("camera.cameraUnavailableDesc")}),i.jsx("button",{onClick:Z,className:"px-4 py-2 bg-bambu-green text-white rounded hover:bg-bambu-green/80 transition-colors",children:t("camera.retry")})]})}),i.jsx("img",{ref:W,src:tt,alt:t("camera.cameraStream"),className:"max-w-full max-h-full object-contain select-none",style:{transform:`scale(${E}) translate(${O.x/E}px, ${O.y/E}px)`,cursor:E>1?R?"grabbing":"grab":"default"},onError:tt?Oe:void 0,onLoad:tt?q:void 0,onMouseDown:Q,draggable:!1},x),i.jsxs("div",{className:"absolute bottom-4 left-4 flex items-center gap-1.5 bg-black/60 rounded-lg px-2 py-1.5",children:[i.jsx("button",{onClick:Fe,disabled:E<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(TF,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:qe,className:"px-2 py-1 text-sm text-white hover:bg-white/10 rounded min-w-[48px]",title:t("camera.resetZoom"),children:[Math.round(E*100),"%"]}),i.jsx("button",{onClick:le,disabled:E>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(AF,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(iL,{printerId:s,isOpen:c,onClose:()=>u(!1)})]}):i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:t("camera.invalidPrinterId")})})}function uJe(t){const e=t.get("show")?.split(",")||["progress","layers","eta","filename","status"],n=parseInt(t.get("fps")||"15",10),r=Math.min(Math.max(isNaN(n)?15:n,1),30),a=t.get("camera"),s=a!=="false"&&a!=="0";return{size:t.get("size")||"medium",fps:r,showCamera:s,showProgress:e.includes("progress"),showLayers:e.includes("layers"),showEta:e.includes("eta"),showFilename:e.includes("filename"),showStatus:e.includes("status"),showPrinter:e.includes("printer")}}function dJe(t,e){if(t.stg_cur_name)return t.stg_cur_name;switch(t.state){case"RUNNING":return e("streamOverlay.status.printing");case"PAUSE":return e("streamOverlay.status.paused");case"FINISH":return e("streamOverlay.status.finished");case"FAILED":return e("streamOverlay.status.failed");case"IDLE":return e("streamOverlay.status.idle");default:return t.state||e("streamOverlay.status.unknown")}}function hJe(t){switch(t){case"small":return{container:"p-3",text:"text-sm",textLarge:"text-lg",progressHeight:"h-2",icon:"w-3 h-3",gap:"gap-2",logoHeight:"h-12"};case"large":return{container:"p-6",text:"text-xl",textLarge:"text-3xl",progressHeight:"h-4",icon:"w-6 h-6",gap:"gap-4",logoHeight:"h-24"};default:return{container:"p-4",text:"text-base",textLarge:"text-xl",progressHeight:"h-3",icon:"w-4 h-4",gap:"gap-3",logoHeight:"h-16"}}}function mJe(){const{printerId:t}=i0(),[e]=dF(),{t:n}=Ut(),r=tn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>uJe(e),[e]),c=hJe(l.size),{data:u}=Je({queryKey:["printer",a],queryFn:()=>ne.getPrinter(a),enabled:a>0}),{data:d}=Je({queryKey:["printerStatus",a],queryFn:()=>ne.getPrinterStatus(a),enabled:a>0,refetchInterval:2e3}),{data:h}=Je({queryKey:["settings"],queryFn:ne.getSettings}),f=h?.time_format||"system";w.useEffect(()=>{if(!a)return;const _=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,N=new WebSocket(_);return N.onmessage=k=>{try{const A=JSON.parse(k.data);A.type==="printer_status"&&A.printer_id===a&&r.setQueryData(["printerStatus",a],A.status)}catch{}},N.onerror=()=>{},()=>{N.close()}},[a,r]),w.useEffect(()=>(document.title=u?`${u.name} - ${n("streamOverlay.title")}`:n("streamOverlay.title"),()=>{document.title="Bambuddy"}),[u,n]);const p=()=>{setTimeout(()=>{o(Date.now())},3e3)};if(!a)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-white",children:n("streamOverlay.invalidPrinterId")})});if(!d)return i.jsx("div",{className:"min-h-screen bg-black flex items-center justify-center",children:i.jsx("p",{className:"text-gray-400",children:n("common.loading")})});const x=d.state==="RUNNING"||d.state==="PAUSE",v=d.progress||0,g=`/api/v1/printers/${a}/camera/stream?fps=${l.fps}&t=${s}`;return i.jsxs("div",{className:"min-h-screen bg-black relative overflow-hidden",children:[l.showCamera&&i.jsx("img",{src:g,alt:n("streamOverlay.cameraStream"),className:"absolute inset-0 w-full h-full object-contain",onError:p},s),i.jsx("a",{href:"https://github.com/maziggy/bambuddy",target:"_blank",rel:"noopener noreferrer",className:"absolute top-4 right-4 z-10",children:i.jsx("img",{src:"/img/bambuddy_logo_dark_transparent.png",alt:"Bambuddy",className:`${c.logoHeight} object-contain drop-shadow-lg hover:scale-105 transition-transform`})}),i.jsx("div",{className:"absolute bottom-0 left-0 right-0 z-10 bg-gradient-to-t from-black/80 via-black/60 to-transparent",children:i.jsxs("div",{className:`${c.container}`,children:[l.showPrinter&&u&&i.jsxs("div",{className:`flex items-center ${c.gap} mb-2`,children:[i.jsx(xr,{className:`${c.icon} text-white/70`}),i.jsx("span",{className:`${c.text} text-white font-medium`,children:u.name})]}),l.showFilename&&d.current_print&&i.jsx("div",{className:`${c.textLarge} text-white font-semibold mb-2 truncate drop-shadow-md`,children:d.current_print.replace(/\.gcode\.3mf$|\.3mf$|\.gcode$/i,"")}),l.showStatus&&i.jsx("div",{className:`${c.text} text-white/70 mb-2`,children:dJe(d,n)}),l.showProgress&&x&&i.jsxs("div",{className:"mb-3",children:[i.jsxs("div",{className:`flex items-center justify-between mb-1 ${c.text}`,children:[i.jsx("span",{className:"text-white/70",children:n("streamOverlay.progress")}),i.jsxs("span",{className:"text-white font-bold",children:[Math.round(v),"%"]})]}),i.jsx("div",{className:`w-full bg-white/20 rounded-full ${c.progressHeight}`,children:i.jsx("div",{className:`bg-bambu-green ${c.progressHeight} rounded-full transition-all duration-500`,style:{width:`${v}%`}})})]}),x&&(l.showLayers||l.showEta)&&i.jsxs("div",{className:`flex items-center ${c.gap} flex-wrap`,children:[l.showLayers&&d.layer_num!=null&&d.total_layers!=null&&d.total_layers>0&&i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(mi,{className:c.icon}),i.jsxs("span",{className:c.text,children:[i.jsx("span",{className:"text-white",children:d.layer_num}),i.jsx("span",{className:"mx-1",children:"/"}),i.jsx("span",{children:d.total_layers})]})]}),l.showEta&&d.remaining_time!=null&&d.remaining_time>0&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Lu,{className:c.icon}),i.jsx("span",{className:`${c.text} text-white`,children:Qs(d.remaining_time*60)})]}),i.jsxs("div",{className:`flex items-center ${c.gap} text-white/70`,children:[i.jsx(Gn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",MF(d.remaining_time,f,n)]})]})]})]}),!x&&i.jsx("div",{className:`${c.text} text-white/70 py-2`,children:d.connected?n("streamOverlay.printerIdle"):n("streamOverlay.printerOffline")})]})})]})}function fJe(){const{t}=Ut(),{id:e}=i0(),{mode:n}=Jf(),{data:r,isLoading:a,error:s}=Je({queryKey:["external-link",e],queryFn:()=>ne.getExternalLink(Number(e)),enabled:!!e});return a?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s||!r?i.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 text-bambu-gray",children:[i.jsx(Tn,{className:"w-12 h-12"}),i.jsx("p",{children:t("common.linkNotFound")})]}):i.jsx("iframe",{src:r.url,className:"h-full w-full border-0",style:{colorScheme:n},title:r.name,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"})}function tK(){const{id:t}=i0(),e=rc(),n=tn(),{t:r}=Ut(),{showToast:a}=cn(),s=!!t,[o,l]=w.useState(""),[c,u]=w.useState(""),[d,h]=w.useState([]),[f,p]=w.useState(""),[x,v]=w.useState(!1),{data:g,isLoading:y}=Je({queryKey:["group",t],queryFn:()=>ne.getGroup(Number(t)),enabled:s}),{data:_,isLoading:N}=Je({queryKey:["permissions"],queryFn:()=>ne.getPermissions()});s&&g&&!x&&(l(g.name),u(g.description||""),h(g.permissions),v(!0));const k=ot({mutationFn:z=>ne.createGroup(z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.created")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),A=ot({mutationFn:z=>ne.updateGroup(Number(t),z),onSuccess:()=>{n.invalidateQueries({queryKey:["groups"]}),a(r("groups.toast.updated")),e("/settings?tab=users")},onError:z=>{a(z.message,"error")}}),M=k.isPending||A.isPending,C=()=>{if(!o.trim()){a(r("groups.toast.enterGroupName"),"error");return}s?A.mutate({name:o!==g?.name?o:void 0,description:c,permissions:d}):k.mutate({name:o,description:c||void 0,permissions:d})},j=z=>{h(K=>K.includes(z)?K.filter(Y=>Y!==z):[...K,z])},P=(z,K)=>{const Y=z.permissions.map(ae=>ae.value);h(ae=>{const $=ae.filter(W=>!Y.includes(W));return K?[...$,...Y]:$})},E=z=>z.permissions.every(K=>d.includes(K.value)),B=z=>{const K=z.permissions.filter(Y=>d.includes(Y.value)).length;return K>0&&K{_&&h(_.all_permissions)},U=()=>{h([])},R=f.toLowerCase(),V=w.useMemo(()=>_?R?_.categories.map(z=>({...z,permissions:z.permissions.filter(K=>K.label.toLowerCase().includes(R))})).filter(z=>z.permissions.length>0):_.categories:[],[_,R]),G=_?.all_permissions.length??0;return y||N?i.jsx("div",{className:"flex items-center justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):i.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("button",{onClick:()=>e("/settings?tab=users"),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",children:i.jsx(ZK,{className:"w-5 h-5"})}),i.jsx("h1",{className:"text-xl font-bold text-white",children:r(s?"groups.editor.title":"groups.editor.createTitle")})]}),s&&g?.is_system&&i.jsxs("div",{className:"flex items-center gap-3 px-4 py-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20 text-yellow-400 text-sm",children:[i.jsx(Tn,{className:"w-4 h-4 shrink-0"}),r("groups.form.systemGroupWarning")]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.groupName")}),i.jsx("input",{type:"text",value:o,onChange:z=>l(z.target.value),disabled:s&&g?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:r("groups.form.groupNamePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:r("groups.form.description")}),i.jsx("input",{type:"text",value:c,onChange:z=>u(z.target.value),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:r("groups.form.descriptionPlaceholder")})]})]}),i.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("span",{className:"text-sm text-bambu-gray",children:[r("groups.editor.permissionsSelected",{count:d.length})," / ",G]}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:O,children:r("groups.editor.selectAll")}),i.jsx(Ce,{size:"sm",variant:"ghost",onClick:U,children:r("groups.editor.clearAll")})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray"}),i.jsx("input",{type:"text",value:f,onChange:z=>p(z.target.value),placeholder:r("groups.editor.search"),className:"pl-9 pr-4 py-2 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors w-64"})]})]}),V.length===0?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:r("groups.editor.noResults")}):i.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:V.map(z=>{const K=_.categories.find(ee=>ee.name===z.name),Y=K.permissions.filter(ee=>d.includes(ee.value)).length,ae=K.permissions.length,$=E(K),W=B(K);return i.jsxs(vt,{children:[i.jsxs("div",{className:"sticky top-0 z-10 flex items-center justify-between px-4 py-3 bg-bambu-dark-secondary border-b border-bambu-dark-tertiary rounded-t-xl",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("button",{type:"button",onClick:()=>P(K,!$),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${$?"bg-bambu-green border-bambu-green":W?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[$&&i.jsx(ra,{className:"w-3 h-3 text-white"}),W&&!$&&i.jsx(x1,{className:"w-3 h-3 text-white"})]}),i.jsx(i3,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-white font-medium text-sm",children:z.name})]}),i.jsxs("span",{className:"text-xs text-bambu-gray tabular-nums",children:[Y,"/",ae]})]}),i.jsx("div",{className:"p-3 space-y-1",children:z.permissions.map(ee=>i.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:d.includes(ee.value),onChange:()=>j(ee.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),i.jsx("span",{className:"text-sm text-bambu-gray",children:ee.label})]},ee.value))})]},z.name)})}),i.jsx("div",{className:"h-16"}),i.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 px-6 py-3 bg-bambu-dark-secondary border-t border-bambu-dark-tertiary flex items-center justify-center gap-3",children:[i.jsx(Ce,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(Ce,{onClick:C,disabled:M||!o.trim(),children:M?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),r("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),r("common.save")]})})]})]})}const nK={material:"",subtype:"",brand:"",color_name:"",rgba:"808080FF",label_weight:1e3,core_weight:250,core_weight_catalog_id:null,weight_used:0,slicer_filament:"",note:"",cost_per_kg:null};function pJe(t){const e={};return t.slicer_filament||(e.slicer_filament="Slicer preset is required"),t.material||(e.material="Material is required"),t.brand||(e.brand="Brand is required"),t.subtype||(e.subtype="Subtype is required"),{isValid:Object.keys(e).length===0,errors:e}}const gJe=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],bJe=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],lv=["Basic","Matte","Silk","Tough","HF","High Flow","Engineering","Galaxy","Glow","Marble","Metal","Rainbow","Sparkle","Wood","Translucent","Transparent","Clear","Lite","Pro","Plus","Max","Super","Ultra","Flex","Soft","Hard","Strong","Impact","Heat Resistant","UV Resistant","ESD","Conductive","Magnetic","Gradient","Dual Color","Tri Color","Multicolor"],Hie=[{name:"Black",hex:"000000"},{name:"White",hex:"FFFFFF"},{name:"Gray",hex:"808080"},{name:"Red",hex:"FF0000"},{name:"Orange",hex:"FFA500"},{name:"Yellow",hex:"FFFF00"},{name:"Green",hex:"00AE42"},{name:"Blue",hex:"0066FF"},{name:"Purple",hex:"8B00FF"},{name:"Pink",hex:"FF69B4"},{name:"Brown",hex:"8B4513"},{name:"Silver",hex:"C0C0C0"}],xJe=[{name:"Dark Red",hex:"8B0000"},{name:"Crimson",hex:"DC143C"},{name:"Coral",hex:"FF7F50"},{name:"Salmon",hex:"FA8072"},{name:"Dark Orange",hex:"FF8C00"},{name:"Peach",hex:"FFDAB9"},{name:"Gold",hex:"FFD700"},{name:"Khaki",hex:"F0E68C"},{name:"Lemon",hex:"FFF44F"},{name:"Lime",hex:"32CD32"},{name:"Forest Green",hex:"228B22"},{name:"Olive",hex:"808000"},{name:"Mint",hex:"98FF98"},{name:"Teal",hex:"008080"},{name:"Navy",hex:"000080"},{name:"Sky Blue",hex:"87CEEB"},{name:"Royal Blue",hex:"4169E1"},{name:"Cyan",hex:"00FFFF"},{name:"Turquoise",hex:"40E0D0"},{name:"Violet",hex:"EE82EE"},{name:"Magenta",hex:"FF00FF"},{name:"Indigo",hex:"4B0082"},{name:"Lavender",hex:"E6E6FA"},{name:"Plum",hex:"DDA0DD"},{name:"Hot Pink",hex:"FF69B4"},{name:"Rose",hex:"FF007F"},{name:"Blush",hex:"FFB6C1"},{name:"Chocolate",hex:"D2691E"},{name:"Tan",hex:"D2B48C"},{name:"Beige",hex:"F5F5DC"},{name:"Maroon",hex:"800000"},{name:"Dark Gray",hex:"404040"},{name:"Light Gray",hex:"D3D3D3"},{name:"Charcoal",hex:"36454F"},{name:"Ivory",hex:"FFFFF0"},{name:"Bambu Green",hex:"00AE42"},{name:"Jade White",hex:"E8E8E8"},{name:"Titan Gray",hex:"5A5A5A"}],rK=[...Hie,...xJe],$ie="bambuddy-recent-colors",yJe=8,vJe=[{code:"GFL00",name:"Bambu PLA Basic",displayName:"Bambu PLA Basic",isCustom:!1,allCodes:["GFL00"]},{code:"GFL01",name:"Bambu PLA Matte",displayName:"Bambu PLA Matte",isCustom:!1,allCodes:["GFL01"]},{code:"GFL05",name:"Generic PLA",displayName:"Generic PLA",isCustom:!1,allCodes:["GFL05"]},{code:"GFG00",name:"Bambu PETG Basic",displayName:"Bambu PETG Basic",isCustom:!1,allCodes:["GFG00"]},{code:"GFG05",name:"Generic PETG",displayName:"Generic PETG",isCustom:!1,allCodes:["GFG05"]},{code:"GFB00",name:"Bambu ABS Basic",displayName:"Bambu ABS Basic",isCustom:!1,allCodes:["GFB00"]},{code:"GFB05",name:"Generic ABS",displayName:"Generic ABS",isCustom:!1,allCodes:["GFB05"]},{code:"GFA00",name:"Bambu ASA Basic",displayName:"Bambu ASA Basic",isCustom:!1,allCodes:["GFA00"]},{code:"GFU00",name:"Bambu TPU 95A",displayName:"Bambu TPU 95A",isCustom:!1,allCodes:["GFU00"]},{code:"GFU05",name:"Generic TPU",displayName:"Generic TPU",isCustom:!1,allCodes:["GFU05"]},{code:"GFC00",name:"Bambu PC Basic",displayName:"Bambu PC Basic",isCustom:!1,allCodes:["GFC00"]},{code:"GFN00",name:"Bambu PA Basic",displayName:"Bambu PA Basic",isCustom:!1,allCodes:["GFN00"]},{code:"GFN05",name:"Generic PA",displayName:"Generic PA",isCustom:!1,allCodes:["GFN05"]},{code:"GFS00",name:"Bambu PLA-CF",displayName:"Bambu PLA-CF",isCustom:!1,allCodes:["GFS00"]},{code:"GFT00",name:"Bambu PETG-CF",displayName:"Bambu PETG-CF",isCustom:!1,allCodes:["GFT00"]},{code:"GFNC0",name:"Bambu PA-CF",displayName:"Bambu PA-CF",isCustom:!1,allCodes:["GFNC0"]},{code:"GFV00",name:"Bambu PVA",displayName:"Bambu PVA",isCustom:!1,allCodes:["GFV00"]}];function Rb(t){let e=t.replace(/@.*$/,"").trim();e=e.replace(/\(Custom\)/i,"").trim(),e=e.replace(/^[#*]+\s*/,"").trim();const n=["PLA-CF","PETG-CF","ABS-GF","ASA-CF","PA-CF","PAHT-CF","PA6-CF","PA6-GF","PPA-CF","PPA-GF","PET-CF","PPS-CF","PC-CF","PC-ABS","ABS-GF","PCTG","PETG","PLA","ABS","ASA","PC","PA","TPU","PVA","HIPS","BVOH","PPS","PEEK","PEI"];let r="",a=-1;for(const c of n){const u=e.toUpperCase().indexOf(c.toUpperCase());if(u!==-1){r=c,a=u;break}}let s="";a>0&&(s=e.substring(0,a).trim(),s=s.replace(/[-_\s]+$/,""));let o="";a!==-1&&r&&(o=e.substring(a+r.length).trim(),o=o.replace(/^[-_\s]+/,""));let l="";for(const c of lv)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of lv){const u=new RegExp(`\\s+${c}$`,"i");if(u.test(s)){l=c,s=s.replace(u,"").trim();break}}return{brand:s,material:r,variant:l}}function wJe(t,e){const n=new Set(bJe);for(const r of t){const{brand:a}=Rb(r.name);a&&a.length>1&&n.add(a)}if(e)for(const r of e)if(r.filament_vendor&&r.filament_vendor.length>1)n.add(r.filament_vendor);else{const{brand:a}=Rb(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function SJe(t){const e=t.filter(r=>r.preset_type==="filament");if(e.length===0)return[];const n=new Map;for(const r of e){const a=r.name.replace(/@.*$/,"").trim(),s=n.get(a);if(s)s.allCodes.push(String(r.id));else{const o=r.filament_type||String(r.id);n.set(a,{code:o,name:a,displayName:a,isCustom:!1,allCodes:[o]})}}return Array.from(n.values()).sort((r,a)=>r.displayName.localeCompare(a.displayName))}function _Je(t,e,n){if(t.length>0){const r=[],a=new Map;for(const s of t)if(s.is_custom){const o=s.name.toUpperCase();(e.size===0||Array.from(e).some(c=>o.includes(c))||!o.includes("@"))&&r.push({code:s.setting_id,name:s.name,displayName:`${s.name} (Custom)`,isCustom:!0,allCodes:[s.setting_id]})}else{const o=s.name.replace(/@.*$/,"").trim(),l=a.get(o);l?l.allCodes.push(s.setting_id):a.set(o,{code:s.setting_id,name:o,displayName:o,isCustom:!1,allCodes:[s.setting_id]})}return[...r,...Array.from(a.values())].sort((s,o)=>s.displayName.localeCompare(o.displayName))}if(n&&n.length>0){const r=SJe(n);if(r.length>0)return r}return vJe}function NJe(t,e){if(!t)return;let n=e.find(r=>r.code===t);if(n||(n=e.find(r=>r.allCodes.includes(t))),!n){const r=t.toLowerCase();n=e.find(a=>a.code.toLowerCase()===r||a.allCodes.some(s=>s.toLowerCase()===r))}return n}function CJe(){try{const t=localStorage.getItem($ie);if(t)return JSON.parse(t)}catch{}return[]}function kJe(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,yJe);try{localStorage.setItem($ie,JSON.stringify(r))}catch{}return r}function Ej(t,e){if(!e.material)return!1;const r=(t.name||"").replace(/^High Flow[_\s]+/i,"").replace(/^Standard[_\s]+/i,"").replace(/^HF[_\s]+/i,"").replace(/^S[_\s]+/i,"").trim(),a=Rb(r);return!(!(a.material.toUpperCase()===e.material.toUpperCase())||e.brand&&!(a.brand.toLowerCase().includes(e.brand.toLowerCase())||e.brand.toLowerCase().includes(a.brand.toLowerCase()))||e.subtype&&!(a.variant.toLowerCase().includes(e.subtype.toLowerCase())||e.subtype.toLowerCase().includes(a.variant.toLowerCase())||r.toLowerCase().includes(e.subtype.toLowerCase())))}function AJe({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u}){const{t:d}=Ut(),[h,f]=w.useState(!1),[p,x]=w.useState(!1),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(""),[A,M]=w.useState(""),[C,j]=w.useState(""),[P,E]=w.useState(String(t.label_weight)),[B,O]=w.useState(!1),U=w.useRef(null),R=w.useRef(null),V=w.useRef(null),G=w.useRef(null);w.useEffect(()=>{const W=ee=>{U.current&&!U.current.contains(ee.target)&&f(!1),G.current&&!G.current.contains(ee.target)&&_(!1),R.current&&!R.current.contains(ee.target)&&x(!1),V.current&&!V.current.contains(ee.target)&&g(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[]);const z=w.useMemo(()=>{if(!a)return l;const W=a.toLowerCase();return l.filter(ee=>ee.displayName.toLowerCase().includes(W)||ee.code.toLowerCase().includes(W))},[l,a]),K=w.useMemo(()=>{if(!N)return c;const W=N.toLowerCase();return c.filter(J=>J.toLowerCase().includes(W)).sort((J,ye)=>{const me=J.toLowerCase()===W,te=ye.toLowerCase()===W;return me&&!te?-1:!me&&te?1:J.localeCompare(ye)})},[c,N]),Y=w.useMemo(()=>{if(!A)return lv;const W=A.toLowerCase();return lv.filter(ee=>ee.toLowerCase().includes(W))},[A]),ae=w.useMemo(()=>{if(!C)return u;const W=C.toLowerCase();return u.filter(J=>J.toLowerCase().includes(W)).sort((J,ye)=>{const me=J.toLowerCase()===W,te=ye.toLowerCase()===W;return me&&!te?-1:!me&&te?1:J.localeCompare(ye)})},[C,u]);w.useEffect(()=>{B||E(String(t.label_weight))},[t.label_weight,B]);const $=W=>{e("slicer_filament",W.code),s(W.displayName),f(!1);const ee=Rb(W.name);ee.material&&e("material",ee.material),ee.brand&&e("brand",ee.brand),ee.variant&&e("subtype",ee.variant)};return i.jsxs("div",{className:"space-y-4",children:[i.jsx("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:r?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-3 h-3 animate-spin"})," ",d("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(zb,{className:"w-3 h-3 text-bambu-green"})," ",d("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(yhe,{className:"w-3 h-3"})," ",d("inventory.cloudNotConnected")]})}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:U,children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:d("inventory.searchPresets"),value:a,onChange:W=>{s(W.target.value),f(!0)},onFocus:()=>{f(!0),s("")}}),h&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:z.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noPresetsFound")}):z.map(W=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${o?.code===W.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>$(W),children:[i.jsx("span",{className:"truncate",children:W.displayName}),i.jsx("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:W.code})]},W.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[d("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:G,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:d("inventory.selectMaterial"),value:y?C:t.material,onChange:W=>{j(W.target.value),_(!0)},onFocus:()=>{_(!0),j("")}}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),y&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[ae.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):ae.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",W),_(!1),j("")},children:W},W)),C&&!ae.includes(C)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("material",C),_(!1),j("")},children:d("inventory.useCustomMaterial",{material:C})})]})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.brand")," *"]}),i.jsxs("div",{className:"relative",ref:R,children:[i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:d("inventory.searchBrand"),value:p?N:t.brand,onChange:W=>{k(W.target.value),x(!0)},onFocus:()=>{x(!0),k("")}}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),p&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[K.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):K.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",W),x(!1),k("")},children:W},W)),N&&!K.includes(N)&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("brand",N),x(!1),k("")},children:d("inventory.useCustomBrand",{brand:N})})]})]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[d("inventory.subtype")," *"]}),i.jsxs("div",{className:"relative",ref:V,children:[i.jsx("input",{type:"text",value:v?A:t.subtype,onChange:W=>{M(W.target.value),g(!0)},onFocus:()=>{g(!0),M("")},placeholder:"Basic, Matte, Silk...",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),i.jsx(Un,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),v&&i.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[Y.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:d("inventory.noResults")}):Y.map(W=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===W?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",W),g(!1),M("")},children:W},W)),A&&!lv.some(W=>W.toLowerCase()===A.toLowerCase().trim())&&i.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary text-bambu-green border-t border-bambu-dark-tertiary",onClick:()=>{e("subtype",A),g(!1),M("")},children:d("inventory.useCustomBrand",{brand:A})})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:d("inventory.labelWeight")}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"number",className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:P,min:0,onFocus:()=>O(!0),onChange:W=>E(W.target.value),onBlur:()=>{O(!1);const W=P.trim(),ee=Number(W);if(!W||!Number.isFinite(ee)||ee<0){E(String(t.label_weight));return}const J=Math.round(ee);e("label_weight",J),E(String(J))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]})]})}function TJe({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=t.rgba.replace("#","").substring(0,6),h=y=>d.toUpperCase()===y.toUpperCase(),f=(y,_)=>{e("rgba",y.toUpperCase()+"FF"),e("color_name",_),r({name:_,hex:y})},p=w.useMemo(()=>{if(a.length===0)return[];const y=t.brand?.trim(),_=t.material?.toLowerCase().trim(),N=t.subtype?.toLowerCase().trim();if(!y&&!_)return[];const k=y?y.toLowerCase().split(/[\s\-_]+/).filter(C=>C.length>=2):[],A=C=>{if(k.length===0)return!0;const j=C.toLowerCase();return k.some(P=>j.includes(P))};if(y&&!_){const C=a.filter(j=>A(j.manufacturer));if(C.length>0)return C.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6),manufacturer:j.manufacturer,material:typeof j.material=="string"?j.material:void 0}))}const M=_&&N?`${_} ${N}`:"";if(M){const C=a.filter(P=>A(P.manufacturer)&&P.material?.toLowerCase()===M);if(C.length>0)return C.map(P=>({name:P.color_name,hex:P.hex_color.replace("#","").substring(0,6),manufacturer:P.manufacturer,material:typeof P.material=="string"?P.material:void 0}));const j=M.replace(/\+$/,"");if(j!==M){const P=a.filter(E=>A(E.manufacturer)&&E.material?.toLowerCase()===j);if(P.length>0)return P.map(E=>({name:E.color_name,hex:E.hex_color.replace("#","").substring(0,6),manufacturer:E.manufacturer,material:typeof E.material=="string"?E.material:void 0}))}}if(_){const C=a.filter(j=>A(j.manufacturer)&&(!j.material||j.material.toLowerCase().startsWith(_)));if(C.length>0)return C.map(j=>({name:j.color_name,hex:j.hex_color.replace("#","").substring(0,6),manufacturer:j.manufacturer,material:typeof j.material=="string"?j.material:void 0}))}return[]},[a,t.brand,t.material,t.subtype]),x=w.useMemo(()=>{if(!c)return p;if(p.length===0)return[];const y=c.toLowerCase();return p.filter(N=>N.name.toLowerCase().includes(y)||(N.manufacturer?.toLowerCase().includes(y)??!1)||(N.material?.toLowerCase().includes(y)??!1))},[c,p]),v=p.length>0,g=w.useMemo(()=>c?rK.filter(y=>y.name.toLowerCase().includes(c.toLowerCase())):o?rK:Hie,[c,o]);return i.jsxs("div",{className:"space-y-3",children:[i.jsx("div",{className:"h-10 rounded-lg border border-bambu-dark-tertiary",style:{backgroundColor:`#${d}`}}),n.length>0&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-bambu-gray shrink-0",children:[i.jsx(Gn,{className:"w-3 h-3"}),i.jsx("span",{children:s("inventory.recentColors")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name},y.hex))})]}),i.jsxs("div",{className:"relative",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),i.jsx("input",{type:"text",className:"w-full pl-9 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchColors"),value:c,onChange:y=>u(y.target.value)})]}),v?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-xs text-bambu-gray",children:c?s("inventory.searchResults"):`${t.brand}${t.material?` ${t.material}`:""}`}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[x.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:y.manufacturer&&y.material?`${y.name} (${y.manufacturer} — ${y.material})`:y.manufacturer?`${y.name} (${y.manufacturer})`:y.name})},`${y.hex}-${y.name}-${y.manufacturer??""}`)),x.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}):i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray",children:[i.jsx("span",{children:s(c?"inventory.searchResults":o?"inventory.allColors":"inventory.commonColors")}),!c&&i.jsx("button",{type:"button",onClick:()=>l(!o),className:"flex items-center gap-1 hover:text-white transition-colors",children:o?i.jsxs(i.Fragment,{children:[s("inventory.showLess")," ",i.jsx(yl,{className:"w-3 h-3"})]}):i.jsxs(i.Fragment,{children:[s("inventory.showAll")," ",i.jsx(Un,{className:"w-3 h-3"})]})})]}),i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[g.map(y=>i.jsx("button",{type:"button",onClick:()=>f(y.hex,y.name),className:`w-6 h-6 rounded border-2 transition-all hover:scale-110 hover:z-20 relative group ${h(y.hex)?"border-bambu-green ring-1 ring-bambu-green/30 scale-110":"border-bambu-dark-tertiary"}`,style:{backgroundColor:`#${y.hex}`},title:y.name,children:i.jsx("span",{className:"absolute -bottom-7 left-1/2 -translate-x-1/2 px-2 py-0.5 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-xs whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-20 shadow-lg text-white",children:y.name})},y.hex)),g.length===0&&i.jsx("p",{className:"text-sm text-bambu-gray py-1",children:s("inventory.noColorsFound")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.colorName")}),i.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.colorNamePlaceholder"),value:t.color_name,onChange:y=>e("color_name",y.target.value)})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:s("inventory.hexColor")}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray",children:"#"}),i.jsx("input",{type:"text",className:"w-full pl-7 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono uppercase focus:outline-none focus:border-bambu-green",placeholder:"RRGGBB",value:d.toUpperCase(),onChange:y=>{const _=y.target.value.replace("#","").replace(/[^0-9A-Fa-f]/g,"");_.length<=8&&e("rgba",_.toUpperCase()+(_.length<=6?"FF":""))}})]}),i.jsx("input",{type:"color",className:"w-11 h-[38px] rounded-lg cursor-pointer border border-bambu-dark-tertiary shrink-0 bg-transparent",value:`#${d}`,onChange:y=>{const _=y.target.value.replace("#","").toUpperCase();e("rgba",_+"FF")},title:s("inventory.pickColor")})]})]})]})]})}function MJe({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Ut(),[o,l]=w.useState(!1),[c,u]=w.useState(""),d=w.useRef(null),h=w.useRef(null);w.useEffect(()=>{const v=g=>{d.current&&!d.current.contains(g.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[]),w.useEffect(()=>{if(t.length===0)return;const v=t.filter(g=>g.weight===e);if(r){const g=t.find(y=>y.id===r);if(g&&g.weight===e)return}v.length===1?a(v[0].id):v.length===0&&r!==null&&a(null)},[e,t,r,a]);const f=w.useMemo(()=>{if(!c)return t;const v=c.toLowerCase();return t.filter(g=>g.name.toLowerCase().includes(v)||g.weight.toString().includes(v))},[t,c]),p=w.useMemo(()=>t.filter(v=>v.weight===e),[t,e]),x=w.useMemo(()=>{if(o)return c;if(r){const v=t.find(g=>g.id===r);if(v)return v.name}return p.length>0?p[0].name:""},[o,c,r,t,p]);return i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx(Bfe,{className:"w-3.5 h-3.5 text-bambu-gray"}),s("inventory.coreWeight")]})}),i.jsxs("div",{className:"flex gap-2 items-center",children:[i.jsxs("div",{className:"flex-1 min-w-0 relative",ref:d,children:[i.jsx("input",{ref:h,type:"text",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green",placeholder:s("inventory.searchSpoolWeight"),value:x,onFocus:()=>{l(!0),u("")},onChange:v=>{u(v.target.value),l(!0)}}),o&&i.jsx("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-64 overflow-y-auto",children:f.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:s("inventory.noResults")}):f.map(v=>i.jsxs("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary flex justify-between items-center ${(r?v.id===r:v.weight===e)?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{a(v.id),n(v.weight),l(!1),u("")},children:[i.jsx("span",{className:"truncate",children:v.name}),i.jsxs("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:[v.weight,"g"]})]},v.id))})]}),i.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[i.jsx("input",{type:"number",className:"w-16 px-2 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm text-center font-mono focus:outline-none focus:border-bambu-green",value:e,min:0,max:2e3,onChange:v=>{const g=parseInt(v.target.value);!isNaN(g)&&g>=0&&n(g)}}),i.jsx("span",{className:"text-bambu-gray text-sm",children:"g"})]})]})]})}function PJe({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Ut(),{showToast:s}=cn(),[o,l]=w.useState(""),[c,u]=w.useState(!1),[d,h]=w.useState(""),[f,p]=w.useState(!1),x=Math.max(0,t.label_weight-t.weight_used),v=t.core_weight+x;return w.useEffect(()=>{c||l(String(v))},[c,v]),w.useEffect(()=>{f||h(String(x))},[f,x]),i.jsxs("div",{className:"space-y-4",children:[i.jsx(MJe,{catalog:n,value:t.core_weight,onChange:g=>e("core_weight",g),catalogId:t.core_weight_catalog_id,onCatalogIdChange:g=>e("core_weight_catalog_id",g)}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.currentWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:d,min:0,max:t.label_weight,onFocus:()=>p(!0),onChange:g=>{h(g.target.value)},onBlur:()=>{p(!1);const g=d.trim(),y=Number(g);if(!g||!Number.isFinite(y)||y<0||y>t.label_weight){h(String(x));return}const _=Math.round(y);e("weight_used",Math.max(0,t.label_weight-_)),h(String(_))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.measuredWeight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx("input",{type:"number",value:o,min:0,onFocus:()=>u(!0),onChange:g=>{l(g.target.value)},onBlur:()=>{u(!1);const g=o.trim(),y=Number(g),_=t.core_weight,N=t.core_weight+t.label_weight;if(!g||!Number.isFinite(y)||y<_||y>N){s(a("inventory.measuredWeightError",{min:_,max:N}),"error"),l(String(v));return}const k=Math.round(y),A=Math.max(0,Math.min(t.label_weight,k-t.core_weight));e("weight_used",Math.max(0,t.label_weight-A)),l(String(k))},className:"w-full px-3 py-2 pr-7 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]}),i.jsxs("span",{className:"text-xs text-bambu-gray shrink-0",children:["/ ",t.core_weight+t.label_weight,"g"]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.costPerKg","Cost per kg")}),i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("div",{className:"relative flex-1",children:[i.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:r}),i.jsx("input",{type:"number",value:t.cost_per_kg??"",min:0,step:.01,placeholder:"0.00",onChange:g=>{const y=g.target.value===""?null:parseFloat(g.target.value);e("cost_per_kg",y)},style:{paddingLeft:`${Math.max(2,r.length*.6+1)}rem`},className:"w-full py-2 pr-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green"})]})})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("inventory.note")}),i.jsx("textarea",{className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green resize-none min-h-[80px]",placeholder:a("inventory.notePlaceholder"),value:t.note,onChange:g=>e("note",g.target.value)})]})]})}function EJe({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Ut(),l=f=>{s(p=>{const x=new Set(p);return x.has(f)?x.delete(f):x.add(f),x})},c=(f,p,x)=>{const v=`${f}:${p}:${x??"null"}`,g=`${f}:${x??"null"}`;r(y=>{const _=new Set(y);if(_.has(v))_.delete(v);else{for(const N of Array.from(_)){const k=N.split(":");`${k[0]}:${k[2]}`===g&&_.delete(N)}_.add(v)}return _})},u=()=>{const f=new Set;for(const{printer:p,calibrations:x}of e){if(!p.connected)continue;const v=x.filter(y=>Ej(y,t)),g=new Map;for(const y of v){const _=`${y.extruder_id??"null"}`;g.has(_)||g.set(_,[]),g.get(_).push(y)}for(const[y,_]of g)if(_.length>0){const k=[..._].sort((A,M)=>M.k_value-A.k_value)[0];f.add(`${p.id}:${k.cali_idx}:${y}`)}}r(f)};if(!t.material)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.selectMaterialFirst")})});if(e.length===0)return i.jsx("div",{className:"p-6 bg-bambu-dark rounded-lg text-center",children:i.jsx("p",{className:"text-bambu-gray",children:o("inventory.noPrintersConfigured")})});const d=e.reduce((f,{printer:p,calibrations:x})=>p.connected?f+x.filter(v=>Ej(v,t)).length:f,0),h=(f,p)=>{const x=`${f.id}:${p.cali_idx}:${p.extruder_id??"null"}`,v=n.has(x);return i.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all border ${v?"bg-bambu-green/10 border-bambu-green/30":"bg-bambu-dark border-transparent hover:bg-bambu-dark/80"}`,children:[i.jsx("input",{type:"checkbox",checked:v,onChange:()=>c(String(f.id),p.cali_idx,p.extruder_id),className:"w-4 h-4 rounded border-bambu-dark-tertiary text-bambu-green focus:ring-bambu-green"}),i.jsx("div",{className:"flex-1 min-w-0",children:i.jsx("span",{className:`text-sm font-medium ${v?"text-bambu-green":"text-white"}`,children:p.name||p.filament_id})}),i.jsx("div",{className:"flex items-center gap-2 shrink-0",children:i.jsxs("span",{className:"text-xs font-mono px-2 py-0.5 rounded bg-bambu-dark text-bambu-gray",children:["K=",p.k_value.toFixed(3)]})})]},`${p.cali_idx}-${p.extruder_id}`)};return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("p",{className:"text-xs text-bambu-gray",children:[o("inventory.matchingFilter"),": ",t.brand||o("inventory.anyBrand")," / ",t.material," / ",t.subtype||o("inventory.anyVariant")]}),d>0&&i.jsxs("button",{type:"button",onClick:u,className:"flex items-center gap-1.5 px-2 py-1 text-xs bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(lb,{className:"w-3.5 h-3.5"}),o("inventory.autoSelect")," (",d,")"]})]}),i.jsx("div",{className:"space-y-3",children:e.map(({printer:f,calibrations:p})=>{const x=a.has(String(f.id)),v=p.filter(k=>Ej(k,t)),g=v.length,y=v.some(k=>k.extruder_id!==void 0&&k.extruder_id!==null&&k.extruder_id>0),_=v.filter(k=>k.extruder_id===1),N=v.filter(k=>k.extruder_id===0||k.extruder_id===void 0||k.extruder_id===null);return i.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{type:"button",onClick:()=>l(String(f.id)),className:"w-full px-4 py-3 flex items-center justify-between bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[x?i.jsx(Un,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(pi,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"font-medium text-white",children:f.name}),g>0?i.jsxs("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:[g," ",o(g!==1?"inventory.matches":"inventory.match")]}):i.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-bambu-dark-tertiary text-bambu-gray",children:o("inventory.noMatches")})]}),i.jsx("span",{className:`text-xs px-2 py-1 rounded-full ${f.connected?"bg-green-500/20 text-green-500":"bg-bambu-gray/20 text-bambu-gray"}`,children:f.connected?o("inventory.connected"):o("inventory.offline")})]}),x&&i.jsx("div",{className:"px-4 py-3 space-y-3 bg-bambu-dark border-t border-bambu-dark-tertiary",children:f.connected?g===0?i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.noKProfilesMatch")}):y?i.jsxs(i.Fragment,{children:[_.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.leftNozzle")}),i.jsx("div",{className:"space-y-2",children:_.map(k=>h(f,k))})]}),N.length>0&&i.jsxs("div",{className:"space-y-2",children:[i.jsx("p",{className:"text-xs font-medium text-bambu-gray uppercase tracking-wide",children:o("inventory.rightNozzle")}),i.jsx("div",{className:"space-y-2",children:N.map(k=>h(f,k))})]})]}):i.jsx("div",{className:"space-y-2",children:v.map(k=>h(f,k))}):i.jsx("p",{className:"text-sm text-bambu-gray italic py-2",children:o("inventory.printerOffline")})})]},f.id)})}),n.size>0&&i.jsx("div",{className:"p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"font-semibold",children:n.size})," ",o("inventory.profilesSelected")]})})]})}function jJe(t){const e=new Date(t);return e.toLocaleDateString("en-GB",{day:"2-digit",month:"2-digit",year:"2-digit"})+" "+e.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"})}const DJe={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function RJe({spoolId:t}){const{t:e}=Ut(),n=tn(),{showToast:r}=cn(),{data:a,isLoading:s}=Je({queryKey:["spool-usage",t],queryFn:()=>ne.getSpoolUsageHistory(t)}),o=ot({mutationFn:()=>ne.clearSpoolUsageHistory(t),onSuccess:()=>{n.invalidateQueries({queryKey:["spool-usage",t]}),r(e("inventory.historyCleared"),"success")}});return s?i.jsx("div",{className:"flex justify-center py-4",children:i.jsx(it,{className:"w-5 h-5 animate-spin text-bambu-green"})}):!a||a.length===0?i.jsxs("div",{className:"text-center py-4 text-bambu-gray text-sm",children:[i.jsx(Gn,{className:"w-5 h-5 mx-auto mb-2 opacity-50"}),e("inventory.noUsageHistory")]}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("h4",{className:"text-sm font-medium text-white",children:e("inventory.usageHistory")}),i.jsxs(Ce,{variant:"ghost",size:"sm",onClick:()=>o.mutate(),disabled:o.isPending,className:"text-xs text-bambu-gray hover:text-red-400",children:[i.jsx(Jt,{className:"w-3 h-3 mr-1"}),e("inventory.clearHistory")]})]}),i.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:a.map(l=>i.jsxs("div",{className:"flex items-center justify-between p-2 rounded bg-bambu-dark/50 text-xs",children:[i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("span",{className:"text-bambu-gray",children:jJe(l.created_at)}),l.print_name&&i.jsx("span",{className:"text-white ml-2 truncate",title:l.print_name,children:l.print_name})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0 ml-2",children:[i.jsxs("span",{className:"text-white font-medium",children:[l.weight_used.toFixed(1),"g"]}),i.jsxs("span",{className:"text-bambu-gray",children:["(",l.percent_used,"%)"]}),i.jsx("span",{className:DJe[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function FJe({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Ut(),o=tn(),{showToast:l}=cn(),c=!!n,[u,d]=w.useState(nK),[h,f]=w.useState({}),[p,x]=w.useState("filament"),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),[A,M]=w.useState([]),[C,j]=w.useState(""),[P,E]=w.useState([]),[B,O]=w.useState([]),[U,R]=w.useState([]),[V,G]=w.useState([]),[z,K]=w.useState([]),[Y,ae]=w.useState(new Set),[$,W]=w.useState(new Set),ee=r.length>0?r:z,J=w.useMemo(()=>Y.size,[Y]);w.useEffect(()=>{G(CJe())},[]),w.useEffect(()=>{t&&((async()=>{k(!0);try{const Q=await ne.getCloudStatus();if(_(Q.is_authenticated),Q.is_authenticated){const L=await ne.getFilamentPresets();M(L)}}catch(Q){console.error("Failed to fetch cloud presets:",Q),_(!1)}finally{k(!1)}})(),ne.getSpoolCatalog().then(E).catch(console.error),ne.getColorCatalog().then(R).catch(console.error),ne.getLocalPresets().then(Q=>O(Q.filament)).catch(console.error),r.length===0&&(async()=>{try{const Q=await ne.getPrinters(),L=await Promise.all(Q.map(H=>ne.getPrinterStatus(H.id).catch(()=>null))),D=[];for(let H=0;H({cali_idx:qe.slot_id,filament_id:qe.filament_id,setting_id:qe.setting_id||"",name:qe.name,k_value:parseFloat(qe.k_value)||0,n_coef:parseFloat(qe.n_coef)||0,extruder_id:qe.extruder_id,nozzle_diameter:qe.nozzle_diameter}))}catch{}D.push({printer:{...he,connected:fe},calibrations:ze})}K(D)}catch(Q){console.error("Failed to fetch printer calibrations:",Q)}})())},[t,r.length]);const ye=w.useMemo(()=>_Je(A,new Set,B),[A,B]),me=w.useMemo(()=>{const pe=wJe(A,B),Q=U.map(D=>D.manufacturer?.trim()).filter(D=>!!D),L=new Set([...pe,...Q]);return Array.from(L).sort((D,H)=>D.localeCompare(H))},[A,B,U]),te=w.useMemo(()=>{const pe=U.map(L=>L.material?.trim()).filter(L=>!!L),Q=new Set([...gJe,...pe]);return Array.from(Q).sort((L,D)=>L.localeCompare(D))},[U]),je=w.useMemo(()=>{const pe=[];for(const Q of U){const L=Q.manufacturer?.trim(),D=Q.material?.trim();L&&D&&pe.push({brand:L,material:D})}for(const Q of A){const L=Rb(Q.name);L.brand&&L.material&&pe.push({brand:L.brand,material:L.material})}for(const Q of B){const L=Rb(Q.name),D=Q.filament_vendor?.trim()||L.brand,H=L.material;D&&H&&pe.push({brand:D,material:H})}return pe},[A,U,B]),ue=w.useMemo(()=>{const pe=new Map;for(const Q of je){const L=Q.brand.toLowerCase(),D=Q.material.toLowerCase();pe.has(L)||pe.set(L,new Set),pe.get(L).add(D)}return pe},[je]),oe=w.useMemo(()=>{const pe=new Map;for(const Q of je){const L=Q.brand.toLowerCase(),D=Q.material.toLowerCase();pe.has(D)||pe.set(D,new Set),pe.get(D).add(L)}return pe},[je]),_e=w.useMemo(()=>{if(!u.material)return me;const pe=u.material.toLowerCase(),Q=oe.get(pe);return!Q||Q.size===0?me:me.filter(L=>Q.has(L.toLowerCase()))},[me,u.material,oe]),se=w.useMemo(()=>{if(!u.brand)return te;const pe=u.brand.toLowerCase(),Q=ue.get(pe);return!Q||Q.size===0?te:te.filter(L=>Q.has(L.toLowerCase()))},[te,u.brand,ue]),Oe=w.useMemo(()=>NJe(u.slicer_filament,ye),[u.slicer_filament,ye]);w.useEffect(()=>{if(t){if(n)if(d({material:n.material||"",subtype:n.subtype||"",brand:n.brand||"",color_name:n.color_name||"",rgba:n.rgba||"808080FF",label_weight:n.label_weight||1e3,core_weight:n.core_weight||250,core_weight_catalog_id:n.core_weight_catalog_id??null,weight_used:n.weight_used||0,slicer_filament:n.slicer_filament||"",note:n.note||"",cost_per_kg:n.cost_per_kg??null}),j(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const pe=new Set;for(const Q of n.k_profiles)Q.cali_idx!==null&&Q.cali_idx!==void 0&&pe.add(`${Q.printer_id}:${Q.cali_idx}:${Q.extruder??"null"}`);ae(pe)}else ae(new Set);else d(nK),j(""),ae(new Set);f({}),x("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&ee.length>0&&W(new Set(ee.map(pe=>String(pe.printer.id))))},[t,ee]);const q=(pe,Q)=>{d(L=>({...L,[pe]:Q})),pe==="weight_used"&&g(!0),h[pe]&&f(L=>({...L,[pe]:void 0}))},X=pe=>{G(Q=>kJe(pe,Q))},de=ot({mutationFn:pe=>ne.createSpool(pe),onSuccess:async pe=>{Y.size>0&&pe?.id&&await ie(pe.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:pe=>{l(pe.message,"error")}}),Z=ot({mutationFn:pe=>ne.updateSpool(n.id,pe),onSuccess:async()=>{n?.id&&await ie(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:pe=>{l(pe.message,"error")}}),ie=async pe=>{if(Y.size===0){try{await ne.saveSpoolKProfiles(pe,[])}catch{}return}const Q=[];for(const L of Y){const[D,H,he]=L.split(":"),be=parseInt(D),fe=parseInt(H),ze=he==="null"?0:parseInt(he),Ie=ee.find(qe=>qe.printer.id===be);if(Ie){const qe=Ie.calibrations.find(tt=>tt.cali_idx===fe);qe&&Q.push({printer_id:be,extruder:ze,nozzle_diameter:qe.nozzle_diameter||"0.4",k_value:qe.k_value,name:qe.name||null,cali_idx:qe.cali_idx,setting_id:qe.setting_id||null})}}if(Q.length>0)try{await ne.saveSpoolKProfiles(pe,Q)}catch(L){console.error("Failed to save K-profiles:",L)}};if(w.useEffect(()=>{if(!t)return;const pe=Q=>{Q.key==="Escape"&&e()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[t,e]),!t)return null;const le=()=>{const pe=pJe(u);if(!pe.isValid){f(pe.errors),(pe.errors.slicer_filament||pe.errors.material||pe.errors.brand||pe.errors.subtype)&&x("filament");return}const Q=Oe?.displayName||C||null,L={material:u.material,subtype:u.subtype||null,brand:u.brand||null,color_name:u.color_name||null,rgba:u.rgba||null,label_weight:u.label_weight,core_weight:u.core_weight,core_weight_catalog_id:u.core_weight_catalog_id,slicer_filament:u.slicer_filament||null,slicer_filament_name:Q,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(L.weight_used=u.weight_used),c?Z.mutate(L):de.mutate(L)},Fe=de.isPending||Z.isPending;return i.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),i.jsxs("div",{className:"relative w-full max-w-lg mx-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-h-[90vh] flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:s(c?"inventory.editSpool":"inventory.addSpool")}),i.jsx("button",{onClick:e,className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(Ft,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("button",{onClick:()=>x("filament"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="filament"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(VC,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),i.jsxs("button",{onClick:()=>x("pa-profile"),className:`flex-1 px-4 py-2.5 text-sm font-medium flex items-center justify-center gap-2 transition-colors ${p==="pa-profile"?"text-bambu-green border-b-2 border-bambu-green":"text-bambu-gray hover:text-white"}`,children:[i.jsx(Ede,{className:"w-4 h-4"}),s("inventory.paProfileTab"),J>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:J})]})]}),i.jsx("div",{className:"p-4 overflow-y-auto flex-1",style:{scrollbarGutter:"stable"},children:p==="filament"?i.jsxs("div",{className:"space-y-6",children:[i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.filamentInfo")}),i.jsx(AJe,{formData:u,updateField:q,cloudAuthenticated:y,loadingCloudPresets:N,presetInputValue:C,setPresetInputValue:j,selectedPresetOption:Oe,filamentOptions:ye,availableBrands:_e,availableMaterials:se}),h.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.slicer_filament}),h.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.material}),h.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.brand}),h.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:h.subtype})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.color")}),i.jsx(TJe,{formData:u,updateField:q,recentColors:V,onColorUsed:X,catalogColors:U})]}),i.jsxs("div",{children:[i.jsx("h3",{className:"text-sm font-semibold text-bambu-gray uppercase tracking-wide mb-3",children:s("inventory.additional")}),i.jsx(PJe,{formData:u,updateField:q,spoolCatalog:P,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(RJe,{spoolId:n.id})})]}):i.jsx(EJe,{formData:u,updateField:q,printersWithCalibrations:ee,selectedProfiles:Y,setSelectedProfiles:ae,expandedPrinters:$,setExpandedPrinters:W})}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx(Ce,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Ce,{onClick:le,disabled:Fe,children:Fe?i.jsxs(i.Fragment,{children:[i.jsx(it,{className:"w-4 h-4 animate-spin"}),s("common.saving")]}):i.jsxs(i.Fragment,{children:[i.jsx(ps,{className:"w-4 h-4"}),s(c?"common.save":"inventory.addSpool")]})})]})]})]})}function LJe({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Ut(),[o,l]=w.useState(n),[c,u]=w.useState(null),d=w.useRef(null);if(w.useEffect(()=>{t&&l(n.map(k=>({...k})))},[t,n]),w.useEffect(()=>{if(!t)return;const k=A=>{A.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,e]),!t)return null;const h=k=>{l(A=>A.map((M,C)=>C===k?{...M,visible:!M.visible}:M))},f=(k,A)=>{A<0||A>=o.length||l(M=>{const C=[...M],[j]=C.splice(k,1);return C.splice(A,0,j),C})},p=(k,A)=>{d.current=A,u(A),k.dataTransfer.effectAllowed="move"},x=(k,A)=>{k.preventDefault(),k.dataTransfer.dropEffect="move";const M=d.current;M!==null&&M!==A&&(f(M,A),d.current=A,u(A))},v=k=>{k.preventDefault()},g=()=>{d.current=null,u(null)},y=()=>{l(r.map(k=>({...k})))},_=()=>{a(o),e()},N=o.filter(k=>k.visible).length;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsx(vt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",onClick:k=>k.stopPropagation(),children:i.jsxs(_t,{className:"p-6 flex flex-col min-h-0",children:[i.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:s("inventory.configureColumns")}),i.jsxs("p",{className:"text-sm text-bambu-gray mb-4",children:[s("inventory.configureColumnsDesc"),i.jsxs("span",{className:"ml-2 text-bambu-gray/60",children:["(",N," ",s("inventory.of")," ",o.length," ",s("inventory.visible"),")"]})]}),i.jsx("div",{className:"space-y-1 overflow-y-auto flex-1 min-h-0 pr-1",children:o.map((k,A)=>i.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg border transition-colors ${c===A?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-tertiary/50"} ${k.visible?"":"opacity-50"}`,draggable:!0,onDragStart:M=>p(M,A),onDragOver:M=>x(M,A),onDrop:v,onDragEnd:g,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Ph,{className:"w-4 h-4"})}),i.jsx("span",{className:"flex-1 font-medium text-sm text-white",children:k.label}),i.jsxs("div",{className:"flex items-center gap-0.5",children:[i.jsx("button",{onClick:()=>f(A,A-1),disabled:A===0,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveUp"),children:i.jsx(yl,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>f(A,A+1),disabled:A===o.length-1,className:"p-1 rounded text-bambu-gray hover:bg-bambu-dark-secondary disabled:opacity-30 disabled:cursor-not-allowed",title:s("inventory.moveDown"),children:i.jsx(Un,{className:"w-4 h-4"})})]}),i.jsx("button",{onClick:()=>h(A),className:`p-1.5 rounded transition-colors ${k.visible?"text-bambu-green hover:bg-bambu-green/10":"text-bambu-gray/50 hover:bg-bambu-dark-secondary"}`,title:k.visible?s("inventory.hideColumn"):s("inventory.showColumn"),children:k.visible?i.jsx(Ql,{className:"w-4 h-4"}):i.jsx(o0,{className:"w-4 h-4"})})]},k.id))}),i.jsxs("div",{className:"flex items-center gap-3 mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs(Ce,{variant:"secondary",onClick:y,className:"mr-auto",children:[i.jsx(Fo,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(Ce,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(Ce,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}const Vie="bambuddy-inventory-columns",c1=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"cost_per_kg",label:"Cost/kg",visible:!1}];function OJe(){try{const t=localStorage.getItem(Vie);if(t){const e=JSON.parse(t),n=new Set(c1.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=c1.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return c1.map(t=>({...t}))}function IJe(t){try{localStorage.setItem(Vie,JSON.stringify(t))}catch{}}function Ru(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const zJe={PLA:"bg-green-500/20 text-green-400",ABS:"bg-red-500/20 text-red-400",PETG:"bg-blue-500/20 text-blue-400",TPU:"bg-purple-500/20 text-purple-400",ASA:"bg-orange-500/20 text-orange-400",PA:"bg-yellow-500/20 text-yellow-400",PC:"bg-cyan-500/20 text-cyan-400",PET:"bg-sky-500/20 text-sky-400"};function jj(t,e="system"){if(!t)return"-";const n=di(t);return n?o3(n,e):"-"}const UJe={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",remaining:t=>t("inventory.remaining"),cost_per_kg:t=>t("inventory.costPerKg")},BJe={id:({spool:t})=>i.jsx("span",{className:"text-sm font-medium text-white",children:t.id}),added_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:jj(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:jj(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?jj(t.last_used,e):"Never"}),rgba:({spool:t})=>i.jsx("div",{className:"flex items-center justify-center",children:i.jsx("span",{className:"w-5 h-5 rounded-full border border-white/20 flex-shrink-0",style:{backgroundColor:t.rgba?`#${t.rgba.substring(0,6)}`:"#808080"},title:t.rgba?`#${t.rgba.substring(0,6)}`:void 0})}),material:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:t.material}),subtype:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.subtype||"-"}),color_name:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:one(t.color_name,t.rgba)||"-"}),brand:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.brand||"-"}),slicer_filament:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",title:t.slicer_filament||void 0,children:t.slicer_filament_name||t.slicer_filament||"-"}),location:({spool:t,assignmentMap:e})=>{const n=e[t.id];if(!n)return i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"});const r=n.printer_name||`Printer ${n.printer_id}`,a=n.ams_id===254||n.ams_id===255,s=!a&&n.ams_id>=128,o=cI(n.ams_id,n.tray_id,s,a);return i.jsxs("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-purple-500/20 text-purple-400",children:[r," ",o]})},label_weight:({spool:t})=>i.jsx("span",{className:"text-sm text-white",children:Ru(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:Ru(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:Ru(e+t.core_weight)}),added_full:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.added_full==null?"-":t.added_full?"Yes":"No"}),used:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.weight_used>0?Ru(t.weight_used):"-"}),printed_total:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),printed_since_weight:()=>i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"}),note:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray max-w-[150px] truncate block",title:t.note||void 0,children:t.note||"-"}),pa_k:({spool:t})=>(t.k_profiles?.length??0)===0?i.jsx("span",{className:"text-sm text-bambu-gray",children:"-"}):i.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-xs font-medium bg-bambu-green/20 text-bambu-green",children:"K"}),tag_id:({spool:t})=>{const e=t.tag_uid||t.tray_uuid;return e?i.jsx("span",{className:"text-sm text-bambu-gray font-mono",title:e,children:e.length>12?`${e.slice(0,6)}...${e.slice(-4)}`:e}):i.jsx("span",{className:"text-sm text-bambu-gray/50",children:"-"})},data_origin:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.data_origin||"-"}),tag_type:({spool:t})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.tag_type||"-"}),remaining:({remaining:t,pct:e})=>i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${e>50?"bg-bambu-green":e>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(e,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(t),"g"]})]}),cost_per_kg:({spool:t,currencySymbol:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.cost_per_kg!=null?`${e}${t.cost_per_kg.toFixed(2)}`:"-"})},Dj={id:t=>t.id,added_time:t=>t.created_at||"",encode_time:t=>t.encode_time||"",last_used_time:t=>t.last_used||"",material:t=>(t.material||"").toLowerCase(),subtype:t=>(t.subtype||"").toLowerCase(),color_name:t=>(t.color_name||"").toLowerCase(),brand:t=>(t.brand||"").toLowerCase(),slicer_filament:t=>(t.slicer_filament_name||t.slicer_filament||"").toLowerCase(),location:(t,e)=>{const n=e[t.id];if(!n)return"";const r=n.ams_id===254||n.ams_id===255,a=!r&&n.ams_id>=128;return`${n.printer_name||""} ${cI(n.ams_id,n.tray_id,a,r)}`},label_weight:t=>t.label_weight,net:t=>Math.max(0,t.label_weight-t.weight_used),gross:t=>Math.max(0,t.label_weight-t.weight_used)+t.core_weight,used:t=>t.weight_used,remaining:t=>t.label_weight>0?Math.max(0,t.label_weight-t.weight_used)/t.label_weight:0,note:t=>(t.note||"").toLowerCase(),data_origin:t=>(t.data_origin||"").toLowerCase(),tag_type:t=>(t.tag_type||"").toLowerCase(),cost_per_kg:t=>t.cost_per_kg??0},nF="bambuddy-inventory-sort";function HJe(){try{const t=localStorage.getItem(nF);if(t)return JSON.parse(t)}catch{}return null}function $Je(t){try{t?localStorage.setItem(nF,JSON.stringify(t)):localStorage.removeItem(nF)}catch{}}function VJe(){const{t}=Ut(),e=tn(),{showToast:n}=cn(),[r,a]=w.useState(null),[s,o]=w.useState(null),[l,c]=w.useState("active"),[u,d]=w.useState("all"),[h,f]=w.useState(""),[p,x]=w.useState(""),[v,g]=w.useState(""),[y,_]=w.useState("table"),[N,k]=w.useState(HJe),[A,M]=w.useState(OJe),[C,j]=w.useState(!1),[P,E]=w.useState(0),[B,O]=w.useState(()=>{try{const Q=localStorage.getItem("bambuddy-inventory-pageSize");if(Q){const L=Number(Q);if([15,30,50,100,-1].includes(L))return L}}catch{}return 15}),{data:U}=Je({queryKey:["settings"],queryFn:ne.getSettings}),R=U?.date_format||"system",{data:V,isLoading:G}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!0),refetchInterval:3e4}),{data:z}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),refetchInterval:3e4}),K=ot({mutationFn:Q=>ne.deleteSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),Y=ot({mutationFn:Q=>ne.archiveSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),ae=ot({mutationFn:Q=>ne.restoreSpool(Q),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),$=w.useMemo(()=>{if(!V)return null;let Q=0,L=0,D=0,H=0;const he={};for(const be of V){if(be.archived_at)continue;H++;const fe=Math.max(0,be.label_weight-be.weight_used);Q+=fe,L+=be.weight_used,(be.label_weight>0?fe/be.label_weight*100:0)<20&&D++;const Ie=be.material||"Unknown";he[Ie]||(he[Ie]={count:0,weight:0}),he[Ie].count++,he[Ie].weight+=fe}return{totalWeight:Q,totalConsumed:L,lowStock:D,byMaterial:he,totalSpools:H}},[V]),W=z?.length??0,ee=rl(U?.currency||"USD"),J=w.useMemo(()=>{const Q={};for(const L of z||[])Q[L.spool_id]=L;return Q},[z]),ye=w.useMemo(()=>$?Object.entries($.byMaterial).sort((Q,L)=>L[1].weight-Q[1].weight).slice(0,4):[],[$]),me=w.useMemo(()=>{let Q=V||[];if(l==="active"?Q=Q.filter(L=>!L.archived_at):Q=Q.filter(L=>!!L.archived_at),u==="used"?Q=Q.filter(L=>L.weight_used>0):u==="new"&&(Q=Q.filter(L=>L.weight_used===0)),h&&(Q=Q.filter(L=>L.material===h)),p&&(Q=Q.filter(L=>L.brand===p)),v){const L=v.toLowerCase();Q=Q.filter(D=>D.brand?.toLowerCase().includes(L)||D.material.toLowerCase().includes(L)||D.color_name?.toLowerCase().includes(L)||D.subtype?.toLowerCase().includes(L)||D.note?.toLowerCase().includes(L)||D.slicer_filament_name?.toLowerCase().includes(L))}return Q},[V,l,u,h,p,v]),te=()=>E(0),je=[...new Set(V?.map(Q=>Q.material)||[])].sort(),ue=[...new Set(V?.map(Q=>Q.brand).filter(Boolean)||[])].sort(),oe=l!=="active"||u!=="all"||!!h||!!p||!!v,_e=Q=>{M(Q),IJe(Q)},se=w.useMemo(()=>A.filter(Q=>Q.visible).map(Q=>Q.id),[A]),Oe=Q=>{Dj[Q]&&(k(L=>{let D;return L?.column===Q?D=L.direction==="asc"?{column:Q,direction:"desc"}:null:D={column:Q,direction:"asc"},$Je(D),D}),te())},q=w.useMemo(()=>{if(!N)return me;const Q=Dj[N.column];return Q?[...me].sort((D,H)=>{const he=Q(D,J),be=Q(H,J);return hebe?N.direction==="asc"?1:-1:0}):me},[me,N,J]),X=B===-1,de=X?q.length||1:B,Z=Math.max(1,Math.ceil(q.length/de)),ie=X?0:Math.min(P,Z-1),le=X?q:q.slice(ie*de,(ie+1)*de),Fe=Q=>{O(Q),E(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Q))}catch{}},pe=()=>{c("active"),d("all"),f(""),x(""),g(""),te()};return i.jsxs("div",{className:"p-4 md:p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(fi,{className:"w-6 h-6 text-bambu-green"}),i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("inventory.title")})]}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-9",children:(t("inventory.noSpools").split(".")[0],"")})]}),i.jsxs(Ce,{onClick:()=>a({spool:null}),children:[i.jsx(Xn,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),$&&!G&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(fi,{className:"w-4 h-4 text-bambu-green"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalInventory")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Ru($.totalWeight,!0)}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[$.totalSpools," ",$.totalSpools!==1?t("inventory.spools"):t("inventory.spool")]})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(CF,{className:"w-4 h-4 text-blue-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.totalConsumed")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:Ru($.totalConsumed,!0)}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.sinceTracking")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(mi,{className:"w-4 h-4 text-green-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.byMaterial")})]}),i.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:ye.map(([Q,L])=>i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${zJe[Q]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Q," ",i.jsx("span",{className:"opacity-70",children:Ru(L.weight,!0)})]},Q))})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(xr,{className:"w-4 h-4 text-purple-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.inPrinter")})]}),i.jsx("div",{className:"text-xl font-bold text-white",children:W}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.loadedInAms")})]}),i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-4",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.jsx(Tn,{className:"w-4 h-4 text-yellow-400"}),i.jsx("span",{className:"text-xs text-bambu-gray font-medium uppercase tracking-wide",children:t("inventory.lowStock")})]}),i.jsx("div",{className:`text-xl font-bold ${$.lowStock>0?"text-yellow-400":"text-white"}`,children:$.lowStock}),i.jsx("div",{className:"text-xs text-bambu-gray mt-1",children:t("inventory.lowStockThreshold")})]})]}),i.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-start sm:items-center justify-between",children:[i.jsxs("div",{className:"relative flex-1 max-w-md",children:[i.jsx(kr,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50"}),i.jsx("input",{type:"text",value:v,onChange:Q=>{g(Q.target.value),te()},placeholder:t("inventory.search"),className:"w-full pl-10 pr-8 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm placeholder:text-bambu-gray/50 focus:outline-none focus:border-bambu-green"}),v&&i.jsx("button",{onClick:()=>{g(""),te()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[y==="table"&&i.jsxs("button",{onClick:()=>j(!0),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-bambu-gray border border-bambu-dark-tertiary rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t("inventory.configureColumns"),children:[i.jsx(Ehe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),i.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>_("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(mpe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),i.jsxs("button",{onClick:()=>_("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${y==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(c0,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.cards")})]})]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsxs("button",{onClick:()=>{c("active"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="active"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(fi,{className:"w-3.5 h-3.5"}),t("inventory.active")]}),i.jsxs("button",{onClick:()=>{c("archived"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${l==="archived"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(js,{className:"w-3.5 h-3.5"}),t("inventory.archived")]})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{d("all"),te()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsxs("button",{onClick:()=>{d("used"),te()},className:`flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium transition-colors ${u==="used"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(Gn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),i.jsx("button",{onClick:()=>{d("new"),te()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${u==="new"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.new")})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("select",{value:h,onChange:Q=>{f(Q.target.value),te()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${h?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.material")}),je.map(Q=>i.jsx("option",{value:Q,children:Q},Q))]}),i.jsxs("select",{value:p,onChange:Q=>{x(Q.target.value),te()},className:`px-3 py-1.5 rounded-lg border text-xs font-medium transition-colors cursor-pointer focus:outline-none ${p?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"bg-transparent text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,children:[i.jsx("option",{value:"",children:t("inventory.brand")}),ue.map(Q=>i.jsx("option",{value:Q,children:Q},Q))]}),oe&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("button",{onClick:pe,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[i.jsx(Ft,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),i.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[q.length," ",q.length!==1?t("inventory.spools"):t("inventory.spool")]})]}),G?i.jsx("div",{className:"flex justify-center py-16",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):y==="cards"?le.length>0?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:le.map(Q=>{const L=Math.max(0,Q.label_weight-Q.weight_used),D=Q.label_weight>0?L/Q.label_weight*100:0,H=Q.rgba?`#${Q.rgba.substring(0,6)}`:"#808080";return i.jsxs("div",{className:`bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary hover:border-bambu-green transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>a({spool:Q}),children:[i.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:H},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:one(Q.color_name,Q.rgba)||"-"})}),i.jsxs("div",{className:"p-4 space-y-3",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[Q.material,Q.subtype?` ${Q.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:Q.brand||"-"})]}),i.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",Q.id]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[i.jsx("span",{children:t("inventory.remaining")}),i.jsxs("span",{children:[Math.round(D),"%"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:"flex-1 h-2 bg-bambu-dark-tertiary rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full rounded-full ${D>50?"bg-bambu-green":D>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(D,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(L),"g"]})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.labelWeight"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Ru(Q.label_weight)})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[t("inventory.weightUsed"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Q.weight_used>0?Ru(Q.weight_used):"-"})]})]}),Q.note&&i.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:Q.note,children:Q.note})]})]},Q.id)})}),i.jsx(qJe,{pageIndex:ie,pageSize:B,totalRows:q.length,totalPages:Z,onPageChange:E,onPageSizeChange:Fe,t})]}):i.jsx(aK,{hasFilters:oe,onAddSpool:()=>a({spool:null}),t}):le.length>0?i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-dark-tertiary",children:[i.jsx("div",{className:"overflow-x-auto",children:i.jsxs("table",{className:"w-full",children:[i.jsx("thead",{children:i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary bg-bambu-dark-tertiary/30",children:[se.map(Q=>{const L=!!Dj[Q],D=N?.column===Q;return i.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Q==="remaining"?"min-w-[150px]":""} ${L?"cursor-pointer hover:text-bambu-green transition-colors":""} ${D?"text-bambu-green":"text-bambu-gray"}`,onClick:L?()=>Oe(Q):void 0,children:i.jsxs("span",{className:"inline-flex items-center gap-1",children:[UJe[Q]?.(t)??Q,L&&(D?N.direction==="asc"?i.jsx(Af,{className:"w-3 h-3"}):i.jsx(ib,{className:"w-3 h-3"}):i.jsx(vF,{className:"w-3 h-3 opacity-30"}))]})},Q)}),i.jsx("th",{className:"text-right py-3 px-4 text-xs font-medium text-bambu-gray uppercase tracking-wide",children:t("common.actions")})]})}),i.jsx("tbody",{children:le.map(Q=>{const L=Math.max(0,Q.label_weight-Q.weight_used),D=Q.label_weight>0?L/Q.label_weight*100:0;return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${Q.archived_at?"opacity-50":""}`,onClick:()=>a({spool:Q}),children:[se.map(H=>i.jsx("td",{className:"py-3 px-4",children:BJe[H]?.({spool:Q,remaining:L,pct:D,assignmentMap:J,currencySymbol:ee,dateFormat:R})},H)),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:H=>H.stopPropagation(),children:[i.jsx("button",{onClick:()=>a({spool:Q}),className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:t("inventory.editSpool"),children:i.jsx(Jm,{className:"w-4 h-4"})}),Q.archived_at?i.jsx("button",{onClick:()=>ae.mutate(Q.id),className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:t("inventory.restore"),children:i.jsx(Fo,{className:"w-4 h-4"})}):i.jsx("button",{onClick:()=>o({type:"archive",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:t("inventory.archive"),children:i.jsx(js,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>o({type:"delete",spoolId:Q.id}),className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:t("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]},Q.id)})})]})}),i.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-bambu-dark-tertiary/50 border-t border-bambu-dark-tertiary text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:X?`${q.length} ${q.length!==1?t("inventory.spools"):t("inventory.spool")}`:i.jsxs(i.Fragment,{children:[t("inventory.showing")," ",ie*de+1," ",t("inventory.to")," ",Math.min((ie+1)*de,q.length)," ",t("inventory.of")," ",q.length," ",t("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:t("inventory.show")}),i.jsxs("select",{value:B,onChange:Q=>Fe(Number(Q.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(Q=>i.jsx("option",{value:Q,children:Q},Q)),i.jsx("option",{value:-1,children:t("inventory.all")})]}),!X&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>E(0),disabled:ie===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"First page",children:i.jsx(eX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>E(Q=>Math.max(0,Q-1)),disabled:ie===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",ie+1," ",t("inventory.of")," ",Z]}),i.jsx("button",{onClick:()=>E(Q=>Math.min(Z-1,Q+1)),disabled:ie>=Z-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>E(Z-1),disabled:ie>=Z-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",title:"Last page",children:i.jsx(tX,{className:"w-4 h-4"})})]})]})]})]}):i.jsx(aK,{hasFilters:oe,onAddSpool:()=>a({spool:null}),t}),r!==null&&i.jsx(FJe,{isOpen:!0,onClose:()=>a(null),spool:r.spool,currencySymbol:ee}),s&&i.jsx(gn,{title:s.type==="delete"?t("common.delete"):t("inventory.archive"),message:s.type==="delete"?t("inventory.deleteConfirm"):t("inventory.archiveConfirm"),confirmText:s.type==="delete"?t("common.delete"):t("inventory.archive"),variant:s.type==="delete"?"danger":"warning",onConfirm:()=>{s.type==="delete"?K.mutate(s.spoolId):Y.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),i.jsx(LJe,{isOpen:C,onClose:()=>j(!1),columns:A,defaultColumns:c1,onSave:_e})]})}function qJe({pageIndex:t,pageSize:e,totalRows:n,totalPages:r,onPageChange:a,onPageSizeChange:s,t:o}){const l=e===-1;if(r<=1&&!l)return null;const c=l?n||1:e;return i.jsxs("div",{className:"flex items-center justify-between pt-2 text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:l?`${n} ${o(n!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[o("inventory.showing")," ",t*c+1," ",o("inventory.to")," ",Math.min((t+1)*c,n)," ",o("inventory.of")," ",n," ",o("inventory.spools")]})}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-bambu-gray",children:o("inventory.show")}),i.jsxs("select",{value:e,onChange:u=>s(Number(u.target.value)),className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:border-bambu-green",children:[[15,30,50,100].map(u=>i.jsx("option",{value:u,children:u},u)),i.jsx("option",{value:-1,children:o("inventory.all")})]}),!l&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>a(0),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(eX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(Math.max(0,t-1)),disabled:t===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Xl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[o("inventory.page")," ",t+1," ",o("inventory.of")," ",r]}),i.jsx("button",{onClick:()=>a(Math.min(r-1,t+1)),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(pi,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>a(r-1),disabled:t>=r-1,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(tX,{className:"w-4 h-4"})})]})]})]})}function aK({hasFilters:t,onAddSpool:e,t:n}){return i.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-4",children:[i.jsxs("div",{className:"relative mb-6",children:[i.jsx("div",{className:"absolute inset-0 -m-4 bg-bambu-green/5 rounded-full blur-2xl"}),i.jsxs("div",{className:"relative flex items-center justify-center w-24 h-24 rounded-2xl bg-gradient-to-br from-bambu-dark-secondary to-bambu-dark-tertiary border border-bambu-dark-tertiary shadow-lg",children:[i.jsx("div",{className:"absolute -top-1 -right-1 w-3 h-3 rounded-full bg-bambu-green/30"}),i.jsx("div",{className:"absolute -bottom-2 -left-2 w-2 h-2 rounded-full bg-bambu-green/20"}),t?i.jsx(kr,{className:"w-10 h-10 text-bambu-gray/40",strokeWidth:1.5}):i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"w-14 h-14 rounded-full border-4 border-bambu-gray/20 flex items-center justify-center",children:i.jsx("div",{className:"w-6 h-6 rounded-full bg-bambu-gray/10 border-2 border-bambu-gray/20"})}),i.jsx("div",{className:"absolute -bottom-1 -right-1 w-6 h-6 rounded-full bg-bambu-green flex items-center justify-center shadow-md",children:i.jsx("span",{className:"text-white text-lg font-bold leading-none",children:"+"})})]})]})]}),i.jsx("h3",{className:"text-lg font-semibold text-white mb-2 text-center",children:t?n("inventory.noSpoolsMatch"):n("inventory.noSpools").split(".")[0]}),i.jsx("p",{className:"text-sm text-bambu-gray text-center max-w-sm mb-6",children:n(t?"inventory.noSpoolsMatchDesc":"inventory.noSpools")}),!t&&i.jsxs(Ce,{onClick:e,children:[i.jsx(fi,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const iK=["DEBUG","INFO","WARNING","ERROR"],Rj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},GJe={DEBUG:OC,INFO:Zs,WARNING:Tn,ERROR:Ba};function WJe(){const t=tn(),[e,n]=w.useState(!0),[r,a]=w.useState(new Set),[s,o]=w.useState(""),[l,c]=w.useState("ALL"),[u,d]=w.useState(!1),[h,f]=w.useState(!1),p=w.useRef(null),{data:x,isLoading:v,refetch:g}=Je({queryKey:["application-logs",l,s],queryFn:()=>qg.getLogs({limit:200,level:l==="ALL"?void 0:l,search:s||void 0}),refetchInterval:h?2e3:!1,enabled:u});w.useEffect(()=>{u||f(!1)},[u]);const y=ot({mutationFn:()=>qg.clearLogs(),onSuccess:()=>{t.invalidateQueries({queryKey:["application-logs"]})}});w.useEffect(()=>{e&&p.current&&x?.entries&&(p.current.scrollTop=p.current.scrollHeight)},[x?.entries,e]);const _=C=>{a(j=>{const P=new Set(j);return P.has(C)?P.delete(C):P.add(C),P})},N=C=>{const j=C.split(" ");return j.length>=2?j[1]:C},k=w.useMemo(()=>x?.entries??[],[x?.entries]),A=w.useMemo(()=>[...k].reverse(),[k]),M=({level:C})=>{const j=GJe[C]||Zs;return i.jsx(j,{className:`w-3.5 h-3.5 ${Rj[C]||"text-gray-400"}`})};return i.jsxs("div",{className:"bg-bambu-dark rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>d(!u),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/50 transition-colors",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${h?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(OC,{className:"w-5 h-5"})}),i.jsxs("div",{className:"text-left",children:[i.jsx("p",{className:"font-medium text-white",children:"Application Logs"}),i.jsx("p",{className:"text-sm text-bambu-gray",children:h?`Live streaming - ${x?.filtered_count??0} entries`:"View and filter application logs"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[h&&i.jsxs("span",{className:"flex items-center gap-1.5 px-2 py-1 bg-bambu-green/20 rounded text-bambu-green text-xs",children:[i.jsx("span",{className:"w-1.5 h-1.5 bg-bambu-green rounded-full animate-pulse"}),"Live"]}),u?i.jsx(yl,{className:"w-5 h-5 text-bambu-gray"}):i.jsx(Un,{className:"w-5 h-5 text-bambu-gray"})]})]}),u&&i.jsxs("div",{className:"border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex flex-col gap-2 p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[h?i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!1)},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded transition-colors",children:[i.jsx(vl,{className:"w-4 h-4"}),"Stop"]}):i.jsxs("button",{onClick:C=>{C.stopPropagation(),f(!0),g()},className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 rounded transition-colors",children:[i.jsx(io,{className:"w-4 h-4"}),"Start"]}),i.jsxs("button",{onClick:()=>y.mutate(),disabled:y.isPending||k.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:[i.jsx(Jt,{className:"w-4 h-4"}),"Clear"]}),i.jsx("button",{onClick:()=>g(),disabled:v,className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-bambu-dark-tertiary text-bambu-gray hover:text-white hover:bg-bambu-dark-secondary rounded transition-colors disabled:opacity-50",children:i.jsx(Cr,{className:`w-4 h-4 ${v?"animate-spin":""}`})}),i.jsx("div",{className:"flex-1"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:e,onChange:C=>n(C.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark-tertiary"}),"Auto-scroll"]}),i.jsxs("span",{className:"text-sm text-bambu-gray",children:[x?.filtered_count??0,"/",x?.total_in_file??0]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("div",{className:"relative flex-1",children:[i.jsx(kr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),i.jsx("input",{type:"text",placeholder:"Search message or logger name...",value:s,onChange:C=>o(C.target.value),className:"w-full pl-8 pr-8 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),s&&i.jsx("button",{onClick:()=>o(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ft,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-1 bg-bambu-dark-secondary rounded border border-bambu-dark-tertiary",children:[i.jsx("button",{onClick:()=>c("ALL"),className:`px-2 py-1.5 text-xs rounded-l transition-colors ${l==="ALL"?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:"All"}),iK.map((C,j)=>i.jsx("button",{onClick:()=>c(C),className:`px-2 py-1.5 text-xs transition-colors flex items-center gap-1 ${j===iK.length-1?"rounded-r":""} ${l===C?`${Rj[C]} bg-bambu-dark-tertiary`:"text-bambu-gray hover:text-white"}`,children:C},C))]})]})]}),i.jsx("div",{ref:p,className:"overflow-auto font-mono text-xs bg-black min-h-[300px] max-h-[500px]",children:k.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-[300px] text-bambu-gray",children:[i.jsx("p",{className:"mb-2",children:"No log entries found"}),i.jsx("p",{className:"text-sm",children:"Log file may be empty or cleared"})]}):i.jsx("div",{className:"divide-y divide-bambu-dark-tertiary/30",children:A.map((C,j)=>{const P=r.has(j),E=C.message.includes(` `);return i.jsx("div",{className:`p-2 cursor-pointer hover:bg-bambu-dark-secondary/50 transition-colors ${P?"bg-bambu-dark-secondary/30":""}`,onClick:()=>E&&_(j),children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("span",{className:"text-bambu-gray/70 shrink-0 w-20",children:N(C.timestamp)}),i.jsx("span",{className:"shrink-0",children:i.jsx(M,{level:C.level})}),i.jsxs("span",{className:"text-purple-400/80 shrink-0 max-w-[200px] truncate",title:C.logger_name,children:["[",C.logger_name,"]"]}),i.jsx("span",{className:`flex-1 ${Rj[C.level]||"text-white/80"} ${!P&&E?"truncate":""}`,children:P?i.jsx("pre",{className:"whitespace-pre-wrap break-all",children:C.message}):C.message.split(` `)[0]}),E&&i.jsx("span",{className:"text-bambu-gray/50 shrink-0",children:P?i.jsx(yl,{className:"w-3.5 h-3.5"}):i.jsx(Un,{className:"w-3.5 h-3.5"})})]})},j)})})}),i.jsx("div",{className:"flex items-center justify-between p-3 border-t border-bambu-dark-tertiary text-sm text-bambu-gray",children:h?i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full animate-pulse"}),"Auto-refreshing every 2 seconds"]}):i.jsx("span",{children:"Click Start to enable live log streaming"})})]})]})}function KJe(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:`${(t/(1024*1024*1024)).toFixed(2)} GB`}function ka({icon:t,label:e,value:n,subValue:r,color:a="text-bambu-green"}){return i.jsxs("div",{className:"flex items-start gap-3 p-4 bg-bambu-dark rounded-lg",children:[i.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark-tertiary ${a}`,children:i.jsx(t,{className:"w-5 h-5"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:e}),i.jsx("p",{className:"text-lg font-semibold text-white truncate",children:n}),r&&i.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:r})]})]})}function sK({percent:t,color:e="bg-bambu-green"}){return i.jsx("div",{className:"w-full h-2 bg-bambu-dark rounded-full overflow-hidden",children:i.jsx("div",{className:`h-full ${e} transition-all duration-300`,style:{width:`${Math.min(100,t)}%`}})})}function nh({title:t,icon:e,children:n}){return i.jsxs(vt,{className:"p-6",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[i.jsx(e,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:t})]}),n]})}function XJe(){const{t}=Ut(),e=tn(),[n,r]=w.useState(null),[a,s]=w.useState(!1),[o,l]=w.useState(!1),{data:c,isLoading:u,refetch:d,isFetching:h}=Je({queryKey:["systemInfo"],queryFn:ne.getSystemInfo,refetchInterval:3e4}),{data:f}=Je({queryKey:["debugLogging"],queryFn:qg.getDebugLoggingState,staleTime:10*1e3,refetchInterval:10*1e3}),{data:p}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:x}=Je({queryKey:["library-stats"],queryFn:ne.getLibraryStats}),v=p?.time_format||"system",g=async()=>{l(!0);try{const k=await qg.setDebugLogging(!f?.enabled);e.setQueryData(["debugLogging"],k)}catch(k){console.error("Failed to toggle debug logging:",k)}finally{l(!1)}},y=async()=>{r(null),s(!0);try{await qg.downloadSupportBundle()}catch(k){r(k instanceof Error?k.message:"Failed to download support bundle")}finally{s(!1)}};if(u)return i.jsx("div",{className:"flex items-center justify-center h-64",children:i.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(!c)return i.jsx("div",{className:"p-6 text-center text-bambu-gray",children:t("system.failedToLoad","Failed to load system information")});const _=c.storage.disk_percent_used>90?"bg-red-500":c.storage.disk_percent_used>75?"bg-yellow-500":"bg-bambu-green",N=c.memory.percent_used>90?"bg-red-500":c.memory.percent_used>75?"bg-yellow-500":"bg-bambu-green";return i.jsxs("div",{className:"p-6 space-y-6",children:[i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("system.title","System Information")}),i.jsx("p",{className:"text-bambu-gray mt-1",children:t("system.subtitle","Monitor system resources and database statistics")})]}),i.jsxs("button",{onClick:()=>d(),disabled:h,className:"flex items-center gap-2 px-4 py-2 bg-bambu-dark-secondary hover:bg-bambu-dark-tertiary rounded-lg transition-colors disabled:opacity-50",children:[i.jsx(Cr,{className:`w-4 h-4 ${h?"animate-spin":""}`}),t("common.refresh","Refresh")]})]}),i.jsx(nh,{title:t("system.application","Application"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.version","Version"),value:`v${c.app.version}`}),i.jsx(ka,{icon:Gn,label:t("system.uptime","System Uptime"),value:c.system.uptime_formatted}),i.jsx(ka,{icon:Um,label:t("system.hostname","Hostname"),value:c.system.hostname})]})}),i.jsx(nh,{title:t("support.title","Support & Troubleshooting"),icon:Mme,children:i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.description","Enable debug logging to capture detailed information, then download a support bundle to share when reporting issues.")}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:`p-2 rounded-lg ${f?.enabled?"bg-amber-500/20 text-amber-500":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:i.jsx(OC,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.debugLogging","Debug Logging")}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:[f?.enabled?t("support.debugLoggingEnabled","Capturing detailed logs"):t("support.debugLoggingDisabled","Normal logging level"),f?.enabled&&f.duration_seconds!==null&&i.jsxs("span",{className:"text-amber-400 ml-2",children:["(",Math.floor(f.duration_seconds/60),"m ",f.duration_seconds%60,"s)"]})]})]})]}),i.jsxs("button",{onClick:g,disabled:o,className:`px-4 py-2 rounded-lg font-medium transition-colors flex items-center gap-2 ${f?.enabled?"bg-amber-500/20 text-amber-400 hover:bg-amber-500/30":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30"} disabled:opacity-50`,children:[o&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),f?.enabled?t("support.disableDebug","Disable"):t("support.enableDebug","Enable")]})]}),i.jsxs("div",{className:"flex items-center justify-between p-4 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-green",children:i.jsx(ua,{className:"w-5 h-5"})}),i.jsxs("div",{children:[i.jsx("p",{className:"font-medium text-white",children:t("support.supportBundle","Support Bundle")}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t("support.supportBundleDescription","Download system info and logs as a ZIP file")})]})]}),i.jsxs("button",{onClick:y,disabled:a||!f?.enabled,className:"px-4 py-2 rounded-lg font-medium bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30 transition-colors flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",title:f?.enabled?void 0:t("support.enableDebugFirst","Enable debug logging first"),children:[a&&i.jsx(it,{className:"w-4 h-4 animate-spin"}),t("common.download","Download")]})]}),n&&i.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/30 rounded-lg text-red-400 text-sm",children:n}),!f?.enabled&&i.jsx("div",{className:"p-4 bg-bambu-dark-tertiary/50 rounded-lg",children:i.jsxs("p",{className:"text-sm text-bambu-gray",children:[i.jsx("span",{className:"text-amber-400 font-medium",children:t("support.instructions","To report an issue:")}),i.jsx("br",{}),"1. ",t("support.step1","Enable debug logging"),i.jsx("br",{}),"2. ",t("support.step2","Reproduce the issue"),i.jsx("br",{}),"3. ",t("support.step3","Download the support bundle"),i.jsx("br",{}),"4. ",t("support.step4","Attach the ZIP file to your issue report")]})}),i.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg space-y-3",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:t("support.privacyTitle","What's in the support bundle?")}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-sm",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-bambu-green font-medium mb-1",children:t("support.collected","Collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.collectItem1","App version and debug mode")]}),i.jsxs("li",{children:["• ",t("support.collectItem2","OS, architecture, Python version")]}),i.jsxs("li",{children:["• ",t("support.collectItem3","Database statistics (counts only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem4","Printer models and nozzle counts")]}),i.jsxs("li",{children:["• ",t("support.collectItem5","Non-sensitive settings (themes, formats)")]}),i.jsxs("li",{children:["• ",t("support.collectItem6","Debug logs (sanitized)")]}),i.jsxs("li",{children:["• ",t("support.collectItem7","Printer connectivity and firmware versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem8","Integration status (Spoolman, MQTT, HA)")]}),i.jsxs("li",{children:["• ",t("support.collectItem9","Network interfaces (subnets only)")]}),i.jsxs("li",{children:["• ",t("support.collectItem10","Python package versions")]}),i.jsxs("li",{children:["• ",t("support.collectItem11","Database health checks")]}),i.jsxs("li",{children:["• ",t("support.collectItem12","Docker environment details")]})]})]}),i.jsxs("div",{children:[i.jsx("p",{className:"text-red-400 font-medium mb-1",children:t("support.notCollected","NOT collected:")}),i.jsxs("ul",{className:"text-bambu-gray space-y-0.5",children:[i.jsxs("li",{children:["• ",t("support.notItem1","Printer names and serial numbers")]}),i.jsxs("li",{children:["• ",t("support.notItem2","Access codes and passwords")]}),i.jsxs("li",{children:["• ",t("support.notItem3","Email addresses")]}),i.jsxs("li",{children:["• ",t("support.notItem4","API keys and tokens")]}),i.jsxs("li",{children:["• ",t("support.notItem5","Webhook URLs")]}),i.jsxs("li",{children:["• ",t("support.notItem6","Your hostname or username")]})]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:t("support.privacyNote","Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], and serial numbers with [SERIAL].")})]}),i.jsx(WJe,{})]})}),i.jsxs(nh,{title:t("system.database","Database"),icon:Pc,children:[i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-4",children:[i.jsx(ka,{icon:js,label:t("system.totalArchives","Total Archives"),value:c.database.archives}),i.jsx(ka,{icon:ob,label:t("system.completed","Completed"),value:c.database.archives_completed,color:"text-green-500"}),i.jsx(ka,{icon:hi,label:t("system.failed","Failed"),value:c.database.archives_failed,color:"text-red-500"}),i.jsx(ka,{icon:it,label:t("system.printing","Printing"),value:c.database.archives_printing,color:"text-yellow-500"})]}),i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:xr,label:t("system.printers","Printers"),value:c.database.printers}),i.jsx(ka,{icon:VC,label:t("system.filaments","Filaments"),value:c.database.filaments}),i.jsx(ka,{icon:gs,label:t("system.projects","Projects"),value:c.database.projects}),i.jsx(ka,{icon:fl,label:t("system.smartPlugs","Smart Plugs"),value:c.database.smart_plugs})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[i.jsx(ka,{icon:Gn,label:t("system.totalPrintTime","Total Print Time"),value:c.database.total_print_time_formatted}),i.jsx(ka,{icon:js,label:t("system.totalFilament","Total Filament Used"),value:`${c.database.total_filament_kg} kg`,subValue:`${c.database.total_filament_grams.toLocaleString()} g`})]})]}),i.jsxs(nh,{title:t("system.connectedPrinters","Connected Printers"),icon:xr,children:[i.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[i.jsx("div",{className:"text-3xl font-bold text-bambu-green",children:c.printers.connected}),i.jsx("div",{className:"text-bambu-gray",children:t("system.ofTotal","of {{total}} printers connected",{total:c.printers.total})})]}),c.printers.connected_list.length>0?i.jsx("div",{className:"space-y-2",children:c.printers.connected_list.map(k=>i.jsxs("div",{className:"flex items-center justify-between p-3 bg-bambu-dark rounded-lg",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-2 h-2 rounded-full bg-bambu-green"}),i.jsx("span",{className:"font-medium text-white",children:k.name})]}),i.jsxs("div",{className:"flex items-center gap-4 text-sm text-bambu-gray",children:[i.jsx("span",{children:k.model}),i.jsx("span",{className:`px-2 py-0.5 rounded ${k.state==="RUNNING"?"bg-bambu-green/20 text-bambu-green":k.state==="IDLE"?"bg-blue-500/20 text-blue-400":"bg-bambu-dark-tertiary"}`,children:k.state})]})]},k.id))}):i.jsx("p",{className:"text-bambu-gray",children:t("system.noPrintersConnected","No printers connected")})]}),i.jsx(nh,{title:t("system.storage","Storage"),icon:Ub,children:i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.diskUsage","Disk Usage")}),i.jsxs("span",{className:"text-white",children:[c.storage.disk_used_formatted," / ",c.storage.disk_total_formatted]})]}),i.jsx(sK,{percent:c.storage.disk_percent_used,color:_}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.storage.disk_free_formatted," ",t("system.free","free")," (",(100-c.storage.disk_percent_used).toFixed(1),"%)"]})]}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[i.jsx(ka,{icon:js,label:t("system.archiveStorage","Archive Storage"),value:c.storage.archive_size_formatted}),i.jsx(ka,{icon:Pc,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&i.jsx(ka,{icon:Zl,label:t("system.fileManagerStorage","File Manager"),value:KJe(x.total_size_bytes),subValue:`${x.total_files} files, ${x.total_folders} folders`})]})]})}),i.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[i.jsx(nh,{title:t("system.memory","Memory"),icon:ofe,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray",children:t("system.memoryUsage","Memory Usage")}),i.jsxs("span",{className:"text-white",children:[c.memory.used_formatted," / ",c.memory.total_formatted]})]}),i.jsx(sK,{percent:c.memory.percent_used,color:N}),i.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:[c.memory.available_formatted," ",t("system.available","available")]})]})})}),i.jsx(nh,{title:t("system.cpu","CPU"),icon:Jw,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(ka,{icon:Jw,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),i.jsx(ka,{icon:Jw,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),i.jsx(nh,{title:t("system.systemDetails","System Details"),icon:Um,children:i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(ka,{icon:Um,label:t("system.os","Operating System"),value:c.system.platform,subValue:c.system.platform_release}),i.jsx(ka,{icon:Jw,label:t("system.architecture","Architecture"),value:c.system.architecture}),i.jsx(ka,{icon:Um,label:t("system.python","Python"),value:c.system.python_version}),i.jsx(ka,{icon:Gn,label:t("system.bootTime","Boot Time"),value:jf(c.system.boot_time,v)})]})})]})}function YJe(){const t=rc(),{t:e}=Ut(),{login:n}=Or(),{showToast:r}=cn(),{mode:a}=Jf(),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(!1),[h,f]=w.useState(""),{data:p}=Je({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()}),x=ot({mutationFn:()=>n(s,l),onSuccess:()=>{r(e("login.loginSuccess")),t("/")},onError:_=>{r(_.message||e("login.loginFailed"),"error")}}),v=ot({mutationFn:_=>ne.forgotPassword({email:_}),onSuccess:_=>{r(_.message,"success"),d(!1),f("")},onError:_=>{r(_.message,"error")}}),g=_=>{if(_.preventDefault(),!s||!l){r(e("login.enterCredentials"),"error");return}x.mutate()},y=_=>{if(_.preventDefault(),!h){r("Please enter your email address","error");return}v.mutate(h)};return i.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:[i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:a==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("login.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("login.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:g,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{htmlFor:"username",className:"block text-sm font-medium text-white mb-2",children:p?.advanced_auth_enabled?e("login.usernameOrEmail")||"Username or Email":e("login.username")}),i.jsx("input",{id:"username",type:"text",required:!0,value:s,onChange:_=>o(_.target.value),className:"block 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:p?.advanced_auth_enabled?e("login.usernameOrEmailPlaceholder")||"Enter your username or email":e("login.usernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"password",className:"block text-sm font-medium text-white mb-2",children:e("login.password")}),i.jsx("input",{id:"password",type:"password",required:!0,value:l,onChange:_=>c(_.target.value),className:"block 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:e("login.passwordPlaceholder"),autoComplete:"current-password"})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:x.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:x.isPending?e("login.signingIn"):e("login.signIn")})}),p?.advanced_auth_enabled&&i.jsx("div",{className:"text-center",children:i.jsx("button",{type:"button",onClick:()=>d(!0),className:"text-sm text-bambu-gray hover:text-bambu-green transition-colors",children:e("login.forgotPassword")})})]})]}),u&&i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>d(!1),children:i.jsxs(vt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[i.jsx(In,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(fv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),i.jsx(Ce,{variant:"ghost",size:"sm",onClick:()=>{d(!1),f("")},children:i.jsx(Ft,{className:"w-5 h-5"})})]})}),i.jsx(_t,{children:p?.advanced_auth_enabled?i.jsxs("form",{onSubmit:y,className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray text-sm",children:e("login.forgotPasswordEmailMessage")||"Enter your email address and we'll send you a new password."}),i.jsxs("div",{children:[i.jsx("label",{htmlFor:"forgot-email",className:"block text-sm font-medium text-white mb-2",children:e("login.emailAddress")||"Email Address"}),i.jsx("input",{id:"forgot-email",type:"email",required:!0,value:h,onChange:_=>f(_.target.value),className:"block 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:e("login.emailPlaceholder")||"your.email@example.com"})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Ce,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),f("")},children:e("login.cancel")||"Cancel"}),i.jsx(Ce,{type:"submit",className:"flex-1",disabled:v.isPending,children:v.isPending?e("login.sending")||"Sending...":e("login.sendResetEmail")||"Send Reset Email"})]})]}):i.jsxs("div",{className:"space-y-4",children:[i.jsx("p",{className:"text-bambu-gray",children:e("login.forgotPasswordMessage")}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4 space-y-2",children:[i.jsx("p",{className:"text-sm text-white font-medium",children:e("login.howToReset")}),i.jsxs("ol",{className:"text-sm text-bambu-gray space-y-1 list-decimal list-inside",children:[i.jsx("li",{children:e("login.resetStep1")}),i.jsx("li",{children:e("login.resetStep2")}),i.jsx("li",{children:e("login.resetStep3")}),i.jsx("li",{children:e("login.resetStep4")})]})]}),i.jsx(Ce,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function QJe(){const t=rc(),{t:e}=Ut(),{showToast:n}=cn(),{mode:r}=Jf(),{refreshAuth:a}=Or(),[s,o]=w.useState(!1),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),p=ot({mutationFn:()=>ne.setupAuth({auth_enabled:s,admin_username:s?l:void 0,admin_password:s?u:void 0}),onSuccess:async v=>{await a(),v.auth_enabled?v.admin_created?(n(e("setup.toast.authEnabledAdminCreated")),t("/login")):(n(e("setup.toast.authEnabledExistingAdmins")),t("/login")):(n(e("setup.toast.setupCompleted")),t("/"))},onError:v=>{n(v.message,"error")}}),x=v=>{if(v.preventDefault(),s&&(l||u)){if(!l||!u){n(e("setup.toast.enterBothCredentials"),"error");return}if(u!==h){n(e("setup.toast.passwordsDoNotMatch"),"error");return}if(u.length<6){n(e("setup.toast.passwordTooShort"),"error");return}}p.mutate()};return i.jsx("div",{className:"min-h-screen flex items-center justify-center bg-bambu-dark p-4",children:i.jsxs("div",{className:"max-w-md w-full space-y-8 p-8 bg-gradient-to-br from-bambu-card to-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary shadow-lg",children:[i.jsxs("div",{className:"text-center",children:[i.jsx("div",{className:"flex items-center justify-center mb-6",children:i.jsx("img",{src:r==="dark"?"/img/bambuddy_logo_dark_transparent.png":"/img/bambuddy_logo_light.png",alt:"Bambuddy",className:"h-16"})}),i.jsx("h2",{className:"text-3xl font-bold text-white",children:e("setup.title")}),i.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:e("setup.subtitle")})]}),i.jsxs("form",{className:"mt-8 space-y-6",onSubmit:x,children:[i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"flex items-center p-4 bg-bambu-dark-secondary/50 rounded-lg border border-bambu-dark-tertiary",children:[i.jsx("input",{id:"auth-enabled",type:"checkbox",checked:s,onChange:v=>o(v.target.checked),className:"h-4 w-4 text-bambu-green focus:ring-bambu-green border-bambu-dark-tertiary rounded bg-bambu-dark-secondary"}),i.jsx("label",{htmlFor:"auth-enabled",className:"ml-3 block text-sm font-medium text-white",children:e("setup.enableAuth")})]}),s&&i.jsxs("div",{className:"space-y-4 mt-4",children:[i.jsx("div",{className:"p-3 bg-bambu-dark-secondary/50 border border-bambu-dark-tertiary rounded-lg",children:i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(Zs,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),i.jsxs("div",{className:"text-sm text-bambu-gray",children:[i.jsx("p",{className:"text-white font-medium mb-1",children:e("setup.adminAccount")}),i.jsx("p",{children:e("setup.adminAccountDesc")})]})]})}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-username",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminUsername")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-username",type:"text",value:l,onChange:v=>c(v.target.value),className:"block 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:e("setup.adminUsernamePlaceholder"),autoComplete:"username"})]}),i.jsxs("div",{children:[i.jsxs("label",{htmlFor:"admin-password",className:"block text-sm font-medium text-white mb-2",children:[e("setup.adminPassword")," ",i.jsx("span",{className:"text-bambu-gray text-xs",children:e("setup.optionalIfAdminExists")})]}),i.jsx("input",{id:"admin-password",type:"password",value:u,onChange:v=>d(v.target.value),className:"block 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:e("setup.adminPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]}),u&&i.jsxs("div",{children:[i.jsx("label",{htmlFor:"confirm-password",className:"block text-sm font-medium text-white mb-2",children:e("setup.confirmPassword")}),i.jsx("input",{id:"confirm-password",type:"password",value:h,onChange:v=>f(v.target.value),className:"block 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:e("setup.confirmPasswordPlaceholder"),minLength:6,autoComplete:"new-password"})]})]})]}),i.jsx("div",{children:i.jsx("button",{type:"submit",disabled:p.isPending,className:"w-full flex justify-center py-3 px-4 bg-bambu-green hover:bg-bambu-green-light text-white font-medium rounded-lg shadow-lg shadow-bambu-green/20 hover:shadow-bambu-green/30 focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:ring-offset-2 focus:ring-offset-bambu-dark-secondary transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-bambu-green",children:p.isPending?e("setup.settingUp"):e("setup.completeSetup")})})]})]})})}function ZJe(){const t=w.useRef(null),e=w.useRef(null),n=tn(),[r,a]=w.useState(!1),s=w.useRef(new Set),o=w.useRef(null),l=w.useRef(new Map),c=w.useRef(null),u=w.useRef([]),d=w.useRef(!1),h=w.useRef(()=>{}),f=w.useCallback(()=>{if(d.current||u.current.length===0)return;d.current=!0;const _=()=>{const N=u.current.shift();N?requestAnimationFrame(()=>{h.current(N),u.current.length>0?setTimeout(_,16):d.current=!1}):d.current=!1};_()},[]),p=w.useCallback(()=>{if(t.current?.readyState===WebSocket.OPEN)return;const N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/v1/ws`,k=new WebSocket(N);let A=null;k.onopen=()=>{console.log("[WebSocket] Connected"),a(!0),A=window.setInterval(()=>{k.readyState===WebSocket.OPEN&&k.send(JSON.stringify({type:"ping"}))},3e4)},k.onmessage=M=>{try{const C=JSON.parse(M.data);C.type==="printer_status"&&C.printer_id!==void 0&&C.data?h.current(C):(u.current.push(C),f())}catch{}},k.onclose=M=>{console.log("[WebSocket] Closed",M.code,M.reason),A&&(clearInterval(A),A=null),a(!1),t.current=null,e.current=window.setTimeout(()=>{p()},3e3)},k.onerror=M=>{console.error("[WebSocket] Error",M),k.close()},t.current=k},[f]),x=w.useCallback((_,N)=>{const k=l.current.get(_)||{};l.current.set(_,{...k,...N}),c.current||(c.current=window.setTimeout(()=>{const A=new Map(l.current);l.current.clear(),c.current=null,requestAnimationFrame(()=>{A.forEach((M,C)=>{n.setQueryData(["printerStatus",C],j=>{const P={...j,...M};return P.wifi_signal==null&&j?.wifi_signal!=null&&(P.wifi_signal=j.wifi_signal),P})})})},100))},[n]),v=w.useCallback(_=>{s.current.add(_),o.current&&clearTimeout(o.current),o.current=window.setTimeout(()=>{const N=Array.from(s.current);s.current.clear(),o.current=null;let k=0;N.forEach(A=>{setTimeout(()=>{requestAnimationFrame(()=>{n.invalidateQueries({queryKey:[A]})})},k),k+=500})},3e3)},[n]),g=w.useCallback(_=>{switch(_.type){case"printer_status":_.printer_id!==void 0&&_.data&&x(_.printer_id,_.data);break;case"print_start":_.printer_id!==void 0&&n.invalidateQueries({queryKey:["printerStatus",_.printer_id]});break;case"print_complete":v("archives"),v("archiveStats");break;case"archive_created":v("archives"),v("archiveStats");break;case"archive_updated":v("archives");break;case"pong":break;case"plate_not_empty":window.dispatchEvent(new CustomEvent("plate-not-empty",{detail:{printer_id:_.printer_id,printer_name:_.printer_name,message:_.message}}));break;case"spool_auto_assigned":v("inventory-spools"),v("spool-assignments");break;case"spool_usage_logged":v("inventory-spools");break;case"unknown_tag":window.dispatchEvent(new CustomEvent("unknown-tag",{detail:{printer_id:_.printer_id,ams_id:_.ams_id,tray_id:_.tray_id,tag_uid:_.tag_uid,tray_uuid:_.tray_uuid}}));break;case"background_dispatch":window.dispatchEvent(new CustomEvent("background-dispatch",{detail:_.data||{}}));break}},[n,v,x]);w.useEffect(()=>{h.current=g},[g]),w.useEffect(()=>(p(),()=>{e.current&&clearTimeout(e.current),o.current&&clearTimeout(o.current),c.current&&clearTimeout(c.current),t.current&&t.current.close()}),[p]);const y=w.useCallback(_=>{t.current?.readyState===WebSocket.OPEN&&t.current.send(JSON.stringify(_))},[]);return{isConnected:r,sendMessage:y}}const JJe=new ode({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function eet({children:t}){return ZJe(),i.jsx(i.Fragment,{children:t})}function tet({children:t}){const{authEnabled:e,loading:n,user:r}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Fj({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?r?a?i.jsx(i.Fragment,{children:t}):i.jsx(ab,{to:"/",replace:!0}):i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function net({children:t}){const{authEnabled:e,loading:n}=Or();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(ab,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function ret(){return i.jsx(Zpe,{children:i.jsx(sge,{children:i.jsx(lde,{client:JJe,children:i.jsx(age,{children:i.jsx(Aue,{children:i.jsxs(nue,{children:[i.jsx(fa,{path:"/setup",element:i.jsx(net,{children:i.jsx(QJe,{})})}),i.jsx(fa,{path:"/login",element:i.jsx(YJe,{})}),i.jsx(fa,{path:"/camera/:printerId",element:i.jsx(cJe,{})}),i.jsx(fa,{path:"/overlay/:printerId",element:i.jsx(mJe,{})}),i.jsxs(fa,{element:i.jsx(tet,{children:i.jsx(eet,{children:i.jsx(uge,{})})}),children:[i.jsx(fa,{index:!0,element:i.jsx(c$e,{})}),i.jsx(fa,{path:"archives",element:i.jsx(XXe,{})}),i.jsx(fa,{path:"queue",element:i.jsx(DQe,{})}),i.jsx(fa,{path:"stats",element:i.jsx(WQe,{})}),i.jsx(fa,{path:"profiles",element:i.jsx(IZe,{})}),i.jsx(fa,{path:"maintenance",element:i.jsx($Ze,{})}),i.jsx(fa,{path:"projects",element:i.jsx(qZe,{})}),i.jsx(fa,{path:"projects/:id",element:i.jsx(ZZe,{})}),i.jsx(fa,{path:"inventory",element:i.jsx(VJe,{})}),i.jsx(fa,{path:"files",element:i.jsx(iJe,{})}),i.jsx(fa,{path:"settings",element:i.jsx(Fj,{children:i.jsx(NZe,{})})}),i.jsx(fa,{path:"groups/new",element:i.jsx(Fj,{children:i.jsx(tK,{})})}),i.jsx(fa,{path:"groups/:id/edit",element:i.jsx(Fj,{children:i.jsx(tK,{})})}),i.jsx(fa,{path:"users",element:i.jsx(ab,{to:"/settings?tab=users",replace:!0})}),i.jsx(fa,{path:"groups",element:i.jsx(ab,{to:"/settings?tab=users",replace:!0})}),i.jsx(fa,{path:"system",element:i.jsx(XJe,{})}),i.jsx(fa,{path:"external/:id",element:i.jsx(fJe,{})})]})]})})})})})})}Yoe.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx(ret,{})})); diff --git a/static/index.html b/static/index.html index e48b825f1..a8dd67159 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +