diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e1533564..c42f34624 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.1b3] - Unreleased ### Fixed +- **IP Addresses Not Redacted From Support Bundle Logs** — The `_sanitize_log_content()` function redacted emails, serials, and credentials but left raw IPv4 addresses in log output. Now adds known printer IPs to the sensitive string list for exact matching, and applies an IPv4 regex that replaces addresses with `[IP]` while preserving firmware version strings (which use leading-zero octets like `01.09.01.00`). Updated the system info page privacy disclaimer to list IP addresses as redacted. - **"Unknown stage (74)" on H2D During Print Preparation** — The H2D firmware reports `stg_cur=74` during print preparation, but this stage was not in the stage name lookup table (which went up to 66, sourced from BambuStudio). Now maps stage 74 to "Preparing". Also added stage 77 ("Preparing AMS") which was present in BambuStudio but missing from the lookup. - **Wrong Documentation Link for "Lubricate Carbon Rods" on P2S** ([#490](https://github.com/maziggy/bambuddy/issues/490)) — The "Lubricate Carbon Rods" maintenance task linked to the belt tension wiki page instead of the XYZ axis lubrication page for P2S printers. - **External Spool Mapping Inverted on H2C** ([#492](https://github.com/maziggy/bambuddy/issues/492)) — On H2C dual-nozzle printers, printing from the right nozzle's external spool (Ext-R) incorrectly highlighted the left external spool (Ext-L) as active. The H2C firmware reports `tray_now=254` generically for both external spools, so the frontend's direct ID comparison (`effectiveTrayNow === extTrayId`) always matched Ext-L (id=254). Now uses `active_extruder` on dual-nozzle printers to determine which external spool is active: extruder 1 (left) → Ext-L, extruder 0 (right) → Ext-R. diff --git a/backend/app/api/routes/support.py b/backend/app/api/routes/support.py index 3fc810221..07a323879 100644 --- a/backend/app/api/routes/support.py +++ b/backend/app/api/routes/support.py @@ -684,6 +684,13 @@ def _sanitize_log_content(content: str, sensitive_strings: dict[str, str] | None # Replace Bambu Lab printer serial numbers (format: 00M/01D/01S/01P/03W + alphanumeric, 12-16 chars total) content = re.sub(r"\b0[0-3][A-Z0-9][A-Z0-9]{9,13}\b", "[SERIAL]", content, flags=re.IGNORECASE) + # Replace IPv4 addresses (skip firmware versions like 01.09.01.00 which have leading zeros) + content = re.sub( + r"\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\b", + "[IP]", + content, + ) + # Replace paths with usernames content = re.sub(r"/home/[^/\s]+/", "/home/[user]/", content) content = re.sub(r"/Users/[^/\s]+/", "/Users/[user]/", content) @@ -733,13 +740,15 @@ async def generate_support_bundle( # Collect known sensitive values for log redaction sensitive_strings: dict[str, str] = {} - # Printer names and serial numbers - result = await db.execute(select(Printer.name, Printer.serial_number)) - for name, serial in result.all(): + # Printer names, serial numbers, and IP addresses + result = await db.execute(select(Printer.name, Printer.serial_number, Printer.ip_address)) + for name, serial, ip_address in result.all(): if name: sensitive_strings[name] = "[PRINTER]" if serial: sensitive_strings[serial] = "[SERIAL]" + if ip_address: + sensitive_strings[ip_address] = "[IP]" # Auth usernames result = await db.execute(select(User.username)) diff --git a/backend/tests/unit/test_support_helpers.py b/backend/tests/unit/test_support_helpers.py index bb509fd30..aa9019fb7 100644 --- a/backend/tests/unit/test_support_helpers.py +++ b/backend/tests/unit/test_support_helpers.py @@ -228,6 +228,107 @@ class TestFormatBytes: assert _format_bytes(0) == "0 B" +class TestSanitizeLogContent: + """Tests for _sanitize_log_content() redaction.""" + + def test_ipv4_addresses_redacted(self): + """IPv4 addresses in log lines are replaced with [IP].""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "2024-01-15 Connected to printer at 192.168.1.100 on port 8883" + result = _sanitize_log_content(content) + assert "192.168.1.100" not in result + assert "[IP]" in result + assert "on port 8883" in result + + def test_multiple_ipv4_addresses_redacted(self): + """Multiple different IPs in the same line are all redacted.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Proxy 10.0.0.1 -> 192.168.1.50" + result = _sanitize_log_content(content) + assert result == "Proxy [IP] -> [IP]" + + def test_firmware_versions_with_leading_zeros_preserved(self): + """Firmware versions like 01.09.01.00 have leading zeros and should NOT be redacted.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Firmware version: 01.09.01.00" + result = _sanitize_log_content(content) + assert "01.09.01.00" in result + + def test_firmware_version_mixed_with_ip(self): + """Firmware versions preserved while real IPs are redacted in the same line.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Printer at 192.168.1.5 running firmware 01.07.02.00" + result = _sanitize_log_content(content) + assert "192.168.1.5" not in result + assert "01.07.02.00" in result + assert "[IP] running firmware 01.07.02.00" in result + + def test_printer_ip_from_sensitive_strings(self): + """Printer IPs in sensitive_strings are replaced before regex pass.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Connecting to 192.168.1.100" + result = _sanitize_log_content(content, sensitive_strings={"192.168.1.100": "[IP]"}) + assert result == "Connecting to [IP]" + + def test_edge_case_zero_ip(self): + """0.0.0.0 is a valid IP and should be redacted.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Binding to 0.0.0.0" + result = _sanitize_log_content(content) + assert result == "Binding to [IP]" + + def test_edge_case_broadcast_ip(self): + """255.255.255.255 is a valid IP and should be redacted.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Broadcast to 255.255.255.255" + result = _sanitize_log_content(content) + assert result == "Broadcast to [IP]" + + def test_invalid_octet_not_redacted(self): + """Octets >255 are not valid IPs and should not be redacted.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Value 999.999.999.999" + result = _sanitize_log_content(content) + assert "999.999.999.999" in result + + def test_existing_serial_redaction_still_works(self): + """Serial number redaction still functions alongside IP redaction.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Printer 01SABCDEF1234 at 10.0.0.5" + result = _sanitize_log_content(content) + assert "[SERIAL]" in result + assert "[IP]" in result + assert "01SABCDEF1234" not in result + assert "10.0.0.5" not in result + + def test_existing_email_redaction_still_works(self): + """Email redaction still functions alongside IP redaction.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "User user@example.com from 172.16.0.1" + result = _sanitize_log_content(content) + assert "[EMAIL]" in result + assert "[IP]" in result + + def test_existing_path_redaction_still_works(self): + """Path redaction still functions alongside IP redaction.""" + from backend.app.api.routes.support import _sanitize_log_content + + content = "Config at /home/john/config.yaml from 192.168.0.1" + result = _sanitize_log_content(content) + assert "/home/[user]/" in result + assert "[IP]" in result + + class TestCollectSupportInfo: """Tests for _collect_support_info() new diagnostic sections.""" diff --git a/frontend/src/pages/SystemInfoPage.tsx b/frontend/src/pages/SystemInfoPage.tsx index 40c98beea..18c0970a5 100644 --- a/frontend/src/pages/SystemInfoPage.tsx +++ b/frontend/src/pages/SystemInfoPage.tsx @@ -341,11 +341,12 @@ export function SystemInfoPage() {
  • • {t('support.notItem4', 'API keys and tokens')}
  • • {t('support.notItem5', 'Webhook URLs')}
  • • {t('support.notItem6', 'Your hostname or username')}
  • +
  • • {t('support.notItem7', 'IP addresses')}
  • - {t('support.privacyNote', 'Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], and serial numbers with [SERIAL].')} + {t('support.privacyNote', 'Email addresses in logs are replaced with [EMAIL], printer names with [PRINTER], serial numbers with [SERIAL], and IP addresses with [IP].')}

    diff --git a/static/assets/index-t1Z8cVOI.js b/static/assets/index-DLCtwgng.js similarity index 98% rename from static/assets/index-t1Z8cVOI.js rename to static/assets/index-DLCtwgng.js index da3b11b1d..2b10f76aa 100644 --- a/static/assets/index-t1Z8cVOI.js +++ b/static/assets/index-DLCtwgng.js @@ -8683,4 +8683,4 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${Qs(t. `)+` `+n+"}"}return String(t)}function KZe({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=i0(t.setting_id),v=uI(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(wt,{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(Ot,{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:nF(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(Mn,{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(Pe,{variant:"secondary",onClick:()=>d(!1),disabled:p.isPending,className:"flex-1",children:o("common.cancel")}),i.jsxs(Pe,{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(Pe,{variant:"secondary",onClick:e,className:"flex-1",children:o("common.close")}),i.jsxs(Pe,{variant:"secondary",onClick:r,disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.presets.noDuplicatePermission"),children:[i.jsx(Ql,{className:"w-4 h-4"}),o("profiles.presets.duplicate")]}),x&&i.jsxs(i.Fragment,{children:[i.jsxs(Pe,{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(Pe,{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 Wie(){try{const t=localStorage.getItem("bambusy_preset_templates");return t?JSON.parse(t):[]}catch{return[]}}function Kie(t){localStorage.setItem("bambusy_preset_templates",JSON.stringify(t))}function XZe({onClose:t,onApply:e,t:n}){const{showToast:r}=cn(),[a,s]=w.useState(Wie),[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(B=>B.type===o),A=B=>{s(B),Kie(B)},T=B=>{const D=a.filter($=>$.id!==B);A(D),N(null),r(n("profiles.templates.toast.deleted"))},C=B=>{u(B.id),h(B.name),p(B.description),v(JSON.stringify(B.settings,null,2)),y(null)},j=()=>{if(!(!c||!d.trim()))try{const B=JSON.parse(x),D=a.map($=>$.id===c?{...$,name:d.trim(),description:f.trim(),settings:B}:$);A(D),u(null),r(n("profiles.templates.toast.updated"))}catch(B){y(B.message)}},P=()=>{u(null),h(""),p(""),v("{}"),y(null)},E=B=>{const D=a.map($=>$.id===B?{...$,showInModal:!$.showInModal}:$);A(D)},U={filament:{label:n("profiles.presets.types.filament"),icon:BC,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(B=>B.id===_):null;return w.useEffect(()=>{const B=D=>{D.key==="Escape"&&(_?N(null):c?P():t())};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[_,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(wt,{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(Mn,{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(Pe,{variant:"secondary",onClick:()=>N(null),className:"flex-1",children:n("common.cancel")}),i.jsxs(Pe,{onClick:()=>T(_),className:"flex-1 bg-red-500 hover:bg-red-600",children:[i.jsx(Jt,{className:"w-4 h-4"}),n("common.delete")]})]})]})})}),i.jsx(wt,{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(db,{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(Ot,{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(B=>i.jsx("button",{onClick:()=>l(B),className:`px-3 py-1 text-sm rounded-lg transition-colors ${o===B?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:B==="all"?n("common.all"):U[B].label},B))]}),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(db,{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(B=>{const D=U[B.type],$=D.icon;return c===B.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(Pe,{size:"sm",onClick:j,disabled:!d.trim(),children:[i.jsx(ps,{className:"w-4 h-4"}),"Save"]}),i.jsx(Pe,{size:"sm",variant:"secondary",onClick:P,children:"Cancel"})]})]},B.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($,{className:`w-5 h-5 ${D.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:B.name}),i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:B.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(B.settings).length})}),i.jsx("button",{onClick:()=>E(B.id),className:`p-1 transition-colors ${B.showInModal?"text-bambu-green hover:text-bambu-green/70":"text-bambu-gray hover:text-white"}`,title:B.showInModal?n("profiles.templates.shownInModals"):n("profiles.templates.hiddenInModals"),children:B.showInModal?i.jsx(Zl,{className:"w-4 h-4"}):i.jsx(c0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>e(B),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(B),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(B.id),className:"p-1 text-bambu-gray hover:text-red-400",title:n("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]},B.id)})})})]})})]})}function Xie({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(wt,{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(qg,{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(Ot,{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(Yn,{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(w1,{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(e3,{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(zT,{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(zT,{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(Yn,{className:"w-3.5 h-3.5 text-green-400"}),removed:i.jsx(w1,{className:"w-3.5 h-3.5 text-red-400"}),changed:i.jsx(e3,{className:"w-3.5 h-3.5 text-amber-400"}),same:i.jsx(zT,{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 YZe({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,T]=w.useState(null),[C,j]=w.useState(""),[P,E]=w.useState(!1),[U,O]=w.useState(""),[B,D]=w.useState(!1),[$,G]=w.useState(Wie),[z,W]=w.useState(!1),[X,ae]=w.useState(""),[H,K]=w.useState(""),[ee,Z]=w.useState(!0),[ve,ce]=w.useState(null),[J,je]=w.useState(!1),he=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer})[u]||[],[n,u]),oe=w.useMemo(()=>he.filter(Ne=>i0(Ne.setting_id)),[he]),{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(Ne=>Ne.setting_id).join(",")],queryFn:async()=>{const Ne={};for(let we=0;we{try{const De=await ne.getCloudSettingDetail(tt.setting_id);return{id:tt.setting_id,detail:De}}catch{return null}}))).forEach(tt=>{tt&&(Ne[tt.id]=tt.detail)})}return Ne},enabled:oe.length>0,staleTime:1e3*60*10}),{data:ze,isLoading:V}=Je({queryKey:["cloudSettingDetail",p],queryFn:()=>ne.getCloudSettingDetail(p),enabled:!!p});w.useEffect(()=>{l!=="json"&&k(JSON.stringify(y,null,2))},[y,l]);const Y=w.useMemo(()=>({filament:n.filament,print:n.process,printer:n.printer}[u]||[]).filter(be=>!i0(be.setting_id)).sort((be,we)=>be.name.localeCompare(we.name)),[n,u]);w.useEffect(()=>{if(!p)return;const Ne=Y.find(be=>be.setting_id===p);Ne&&(g(Ne.name),o||(_({inherits:Ne.name}),k(JSON.stringify({inherits:Ne.name},null,2))))},[p,Y,o]);const me=w.useMemo(()=>{const Ne=_e?.fields||[],be=new Set(Ne.map(tt=>tt.key)),we=new Set,Ge=new Set(["inherits","updated_time","compatible_printers","compatible_prints"]);se&&Object.values(se).forEach(tt=>{tt?.setting&&Object.keys(tt.setting).forEach(De=>{!be.has(De)&&!Ge.has(De)&&we.add(De)})}),Object.keys(y).forEach(tt=>{!be.has(tt)&&!Ge.has(tt)&&we.add(tt)});const ke=Array.from(we).sort().map(tt=>({key:tt,label:tt.replace(/_/g," ").replace(/\b\w/g,De=>De.toUpperCase()),type:"text",category:"discovered",description:r("profiles.presets.discoveredFromPresets")}));return[...Ne,...ke]},[_e,se,y,r]),Q=me.filter(Ne=>Ne.label.toLowerCase().includes(C.toLowerCase())||Ne.key.toLowerCase().includes(C.toLowerCase())),ie=()=>{if(U.trim()){const Ne=U.trim().toLowerCase().replace(/\s+/g,"_");ue(Ne,""),O(""),D(!1),a(r("profiles.presets.toast.fieldAdded",{key:Ne}))}},ue=(Ne,be)=>{_(we=>{const Ge={...we};return be===""||be===void 0?delete Ge[Ne]:Ge[Ne]=be,Ge})},Oe=Ne=>{_(be=>({...be,...Ne.settings})),ce(Ne.name),a(r("profiles.templates.toast.applied"))},Ce=()=>{if(!X.trim())return;const Ne={...y};if(delete Ne.inherits,Object.keys(Ne).length===0){a(r("profiles.presets.noOverridesToSave"),"error");return}const be={id:Date.now().toString(),name:X.trim(),description:H.trim()||r("profiles.presets.customTemplate"),type:u,settings:Ne,showInModal:ee},we=[...$,be];G(we),Kie(we),W(!1),ae(""),K(""),Z(!0),a(r("profiles.templates.toast.created"))},ge=w.useMemo(()=>$.filter(Ne=>Ne.type===u&&Ne.showInModal),[u,$]),L=Ne=>{k(Ne);try{const be=JSON.parse(Ne);_(be),T(null)}catch(be){T(be.message)}},R=Ne=>{Ne.preventDefault(),E(!1);const be=Ne.dataTransfer.files[0];if(be&&be.name.endsWith(".json")){const we=new FileReader;we.onload=Ge=>{try{const ke=Ge.target?.result,tt=JSON.parse(ke),De=tt.setting||tt;_(Ke=>({...Ke,...De})),k(JSON.stringify({...y,...De},null,2)),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJsonFile"),"error")}},we.readAsText(be)}},q=ot({mutationFn:()=>{const Ne={...y},be=u==="filament"?"filament_settings_id":u==="print"?"print_settings_id":"printer_settings_id";Ne[be]=`"${h}"`;const we={type:u,name:h,base_id:p,setting:Ne};return ne.createCloudSetting(we)},onSuccess:async()=>{a(r("profiles.presets.toast.created")),await s.refetchQueries({queryKey:["cloudSettings"]}),t()},onError:Ne=>a(Ne.message,"error")}),le=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:Ne=>a(Ne.message,"error")}),pe=o?le:q,te=ze?.setting?.inherits,Ue=te?Y.find(Ne=>Ne.name===te):void 0,{data:Ie}=Je({queryKey:["cloudSettingDetail",Ue?.setting_id],queryFn:()=>ne.getCloudSettingDetail(Ue.setting_id),enabled:!!Ue?.setting_id}),$e=w.useMemo(()=>{const Ne=Ie?.setting||{},be=ze?.setting||{},we=p&&se?.[p]?.setting?se[p].setting:{};return{...Ne,...be,...we}},[p,ze,Ie,se]),Fe=Ne=>{if(Ne==null)return"";if(Array.isArray(Ne)){const be=[...new Set(Ne.map(we=>String(we)))];return be.length===1?be[0]:Ne.join(", ")}return String(Ne)},fe=Ne=>{const be=y[Ne.key],we=$e[Ne.key],Ge=Fe(we),ke=V?r("common.loading"):Ge||"",tt="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(Ne.type==="boolean"){const De=be==="1"||be===void 0&&we==="1";return i.jsx("button",{type:"button",onClick:()=>ue(Ne.key,be==="1"?"0":"1"),className:`w-8 h-5 rounded-full transition-colors ${De?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:`w-4 h-4 rounded-full bg-white shadow transition-transform ${De?"translate-x-3.5":"translate-x-0.5"}`})})}return Ne.type==="select"?i.jsxs("select",{value:be||"",onChange:De=>ue(Ne.key,De.target.value),className:tt,children:[i.jsx("option",{value:"",children:ke}),Ne.options?.map(De=>i.jsx("option",{value:De.value,children:De.label},De.value))]}):i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:Ne.type==="number"?"number":"text",value:be!==void 0?String(be):"",onChange:De=>ue(Ne.key,De.target.value),step:Ne.step,min:Ne.min,max:Ne.max,placeholder:ke,className:tt}),Ne.unit&&i.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:Ne.unit})]})},xe=w.useMemo(()=>ze?.setting?ze.setting:{},[ze]);return i.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onDragOver:Ne=>{Ne.preventDefault(),E(!0)},onDragLeave:()=>E(!1),onDrop:R,children:[J&&p&&i.jsx(Xie,{onClose:()=>je(!1),leftPreset:xe,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(wt,{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(qg,{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(Ot,{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:Ne=>{d(Ne.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:Ne=>x(Ne.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")}),Y.map(Ne=>i.jsx("option",{value:Ne.setting_id,children:Ne.name},Ne.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:Ne=>f(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",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(aa,{className:"w-3 h-3 text-bambu-green"}),r("profiles.presets.inheritsFrom")," ",i.jsx("span",{className:"text-white",children:v}),V&&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(LB,{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(qC,{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(mX,{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 Ne={name:h,type:u,base_id:p,setting:y},be=new Blob([JSON.stringify(Ne,null,2)],{type:"application/json"}),we=URL.createObjectURL(be),Ge=document.createElement("a");Ge.href=we,Ge.download=`${h||"preset"}.json`,document.body.appendChild(Ge),Ge.click(),document.body.removeChild(Ge),URL.revokeObjectURL(we),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(da,{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:Ne=>{const be=Ne.target.files?.[0];if(be){const we=new FileReader;we.onload=Ge=>{try{const ke=JSON.parse(Ge.target?.result),tt=ke.setting||ke;_(De=>({...De,...tt})),a(r("profiles.presets.fileImported"))}catch{a(r("profiles.presets.invalidJson"),"error")}},we.readAsText(be)}}})]}),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(db,{className:"w-4 h-4 text-amber-400"}),r("profiles.templates.title")]}),Object.keys(y).filter(Ne=>Ne!=="inherits").length>0&&i.jsxs("button",{onClick:()=>W(!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:X,onChange:Ne=>ae(Ne.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:H,onChange:Ne=>K(Ne.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(Pe,{size:"sm",onClick:Ce,disabled:!X.trim(),children:[i.jsx(ps,{className:"w-3 h-3"}),r("common.save")]}),i.jsx(Pe,{size:"sm",variant:"secondary",onClick:()=>W(!1),children:r("common.cancel")})]}),i.jsxs("button",{onClick:()=>Z(!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(Zl,{className:"w-3.5 h-3.5"}):i.jsx(c0,{className:"w-3.5 h-3.5"}),r(ee?"profiles.templates.shownInModals":"profiles.templates.hiddenInModals")]})]})]}),ve&&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(aa,{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:ve})]}),i.jsx("button",{onClick:()=>ce(null),className:"ml-auto text-bambu-green/70 hover:text-bambu-green",children:i.jsx(Ot,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[ge.map(Ne=>i.jsxs("button",{onClick:()=>Oe(Ne),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:Ne.name}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Ne.description})]},Ne.id)),ge.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:me.slice(0,10).map(Ne=>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:Ne.label}),i.jsx("div",{className:"w-48 max-[640px]:w-full",children:fe(Ne)})]},Ne.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(([Ne])=>Ne!=="inherits").map(([Ne,be])=>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:[Ne,": ",String(be).slice(0,20),i.jsx("button",{onClick:()=>ue(Ne,void 0),className:"hover:text-white",children:i.jsx(Ot,{className:"w-3 h-3"})})]},Ne))})]})]}),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:me.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:Ne=>j(Ne.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:[Q.filter(Ne=>!(Ne.key in y)).map(Ne=>{const be=$e[Ne.key],we=Fe(be);return i.jsxs("div",{onClick:()=>{_(Ge=>({...Ge,[Ne.key]:we||""}))},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:Ne.label}),i.jsx("p",{className:"text-xs text-bambu-gray-dark truncate",children:Ne.key})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[we&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark px-2 py-0.5 rounded max-w-32 truncate",title:we,children:[we.slice(0,20),we.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(Yn,{className:"w-4 h-4 text-bambu-gray group-hover:text-bambu-green transition-colors"})})]})]},Ne.key)}),Q.filter(Ne=>!(Ne.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:B?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",value:U,onChange:Ne=>O(Ne.target.value),onKeyDown:Ne=>Ne.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(Pe,{size:"sm",onClick:ie,disabled:!U.trim(),children:i.jsx(Yn,{className:"w-4 h-4"})}),i.jsx(Pe,{size:"sm",variant:"secondary",onClick:()=>{D(!1),O("")},children:i.jsx(Ot,{className:"w-4 h-4"})})]}):i.jsxs("button",{onClick:()=>D(!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(Yn,{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(Ne=>Ne!=="inherits").length})})]}),i.jsxs("div",{className:"flex-1 overflow-y-auto space-y-2 pr-2 min-h-0",children:[Object.entries(y).filter(([Ne])=>Ne!=="inherits").map(([Ne,be])=>{const we=me.find(Ge=>Ge.key===Ne);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:we?.label||Ne}),i.jsx("p",{className:"text-xs text-bambu-gray-dark",children:Ne})]}),i.jsx("button",{onClick:()=>ue(Ne,void 0),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",children:i.jsx(Ot,{className:"w-4 h-4"})})]}),we?fe(we):i.jsx("input",{type:"text",value:String(be),onChange:Ge=>ue(Ne,Ge.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"})]},Ne)}),Object.keys(y).filter(Ne=>Ne!=="inherits").length===0&&i.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[i.jsx(LB,{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(Ne=>Ne!=="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:()=>{W(!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:Ne=>L(Ne.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(Pe,{variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsxs(Pe,{onClick:()=>pe.mutate(),disabled:pe.isPending||!h.trim()||!o&&!p||!!A,className:"flex-1",children:[pe.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o?i.jsx(ps,{className:"w-4 h-4"}):i.jsx(Yn,{className:"w-4 h-4"}),r(o?"common.save":e?"common.duplicate":"common.create")]})]})]})})]})}function QZe({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,T]=w.useState(null),[C,j]=w.useState(!1),[P,E]=w.useState(!1),[U,O]=w.useState(null),[B,D]=w.useState(null),[$,G]=w.useState(null),[z,W]=w.useState(!1),[X,ae]=w.useState([null,null]),[H,K]=w.useState(!1),[ee,Z]=w.useState(null),ve=tn(),ce=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:uI(ie.name)})),[t]),J=w.useMemo(()=>{const Q=new Set,ie=new Set,ue=new Set;return ce.forEach(Oe=>{Oe.meta.nozzle&&Q.add(Oe.meta.nozzle),Oe.meta.filamentType&&ie.add(Oe.meta.filamentType),Oe.meta.layerHeight&&ue.add(Oe.meta.layerHeight)}),{printers:a.map(Oe=>({id:Oe.id.toString(),name:Oe.name})),nozzles:Array.from(Q).sort((Oe,Ce)=>parseFloat(Oe)-parseFloat(Ce)),filaments:Array.from(ie).sort(),layerHeights:Array.from(ue).sort((Oe,Ce)=>parseFloat(Oe)-parseFloat(Ce))}},[ce,a]),je=w.useMemo(()=>p==="all"?null:a.find(ie=>ie.id.toString()===p)?.model||null,[p,a]),he=w.useMemo(()=>ce.filter(Q=>u==="all"||Q.type===u).filter(Q=>{if(h==="all")return!0;const ie=i0(Q.setting_id);return h==="custom"?ie:!ie}).filter(Q=>{if(p==="all"||!je)return!0;const ie=Q.meta.printer?.toLowerCase()||"",ue=je.toLowerCase();return ie.includes(ue)||ue.includes(ie)}).filter(Q=>v==="all"||Q.meta.nozzle===v).filter(Q=>y==="all"||Q.meta.filamentType===y).filter(Q=>N==="all"||Q.meta.layerHeight===N).filter(Q=>l===""||Q.name.toLowerCase().includes(l.toLowerCase())).sort((Q,ie)=>Q.name.localeCompare(ie.name)),[ce,u,h,p,je,v,y,N,l]),oe=Q=>{if(z){const ie=X[0]?.setting_id===Q.setting_id,ue=X[1]?.setting_id===Q.setting_id;if(ie)ae([X[1],null]);else if(ue)ae([X[0],null]);else if(!X[0])ae([Q,null]);else if(X[1]){if(X[0].type!==Q.type)return;ae([X[0],Q])}else{if(X[0].type!==Q.type)return;ae([X[0],Q])}}else T(Q)},_e=Q=>{if(X[0]?.setting_id===Q.setting_id)return 0;if(X[1]?.setting_id===Q.setting_id)return 1},se=async Q=>{try{const ie=await ne.getCloudSettingDetail(Q.setting_id),ue=Q.type==="process"?"print":Q.type;O({type:ue,name:Q.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{}}),T(null)}catch(ie){console.error("Failed to fetch preset details for duplication:",ie)}},ze=async Q=>{try{ve.removeQueries({queryKey:["cloudSettingDetail",Q.setting_id]});const ie=await ne.getCloudSettingDetail(Q.setting_id),ue=Q.type==="process"?"print":Q.type;D({type:ue,name:Q.name,base_id:ie.base_id||"GFSA00",setting:ie.setting||{},setting_id:Q.setting_id}),T(null)}catch(ie){console.error("Failed to fetch preset details for editing:",ie)}},V=()=>{d("all"),f("all"),x("all"),g("all"),_("all"),k("all"),c("")},Y=u!=="all"||h!=="all"||p!=="all"||v!=="all"||y!=="all"||N!=="all"||l!=="",me=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:Q=>c(Q.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(Pe,{variant:z?"primary":"secondary",onClick:()=>{z?(W(!1),ae([null,null])):W(!0)},children:[i.jsx(qg,{className:"w-4 h-4"}),o(z?"common.cancel":"profiles.presets.compare")]}),i.jsxs(Pe,{variant:"secondary",onClick:()=>E(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noTemplatesPermission"),children:[i.jsx(db,{className:"w-4 h-4"}),o("profiles.cloudView.templates")]}),i.jsxs(Pe,{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(Pe,{onClick:()=>j(!0),disabled:!s("cloud:auth"),title:s("cloud:auth")?void 0:o("profiles.cloudView.noCreatePermission"),children:[i.jsx(Yn,{className:"w-4 h-4"}),o("profiles.cloudView.newPreset")]})]})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[i.jsx($C,{className:"w-4 h-4 text-bambu-gray"}),i.jsx(Mg,{label:o("profiles.cloudView.filters.type"),value:u,options:[{value:"all",label:o("profiles.cloudView.filters.all"),count:me},{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:Q=>d(Q)}),i.jsx(Mg,{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:Q=>f(Q)}),J.printers.length>0&&i.jsx(Mg,{label:o("profiles.cloudView.filters.printer"),value:p,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.printers.map(Q=>({value:Q.id,label:Q.name}))],onChange:x}),J.nozzles.length>0&&i.jsx(Mg,{label:o("profiles.cloudView.filters.nozzle"),value:v,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.nozzles.map(Q=>({value:Q,label:Q}))],onChange:g}),J.filaments.length>0&&(u==="all"||u==="filament")&&i.jsx(Mg,{label:o("profiles.cloudView.filters.filament"),value:y,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.filaments.map(Q=>({value:Q,label:Q}))],onChange:_}),J.layerHeights.length>0&&(u==="all"||u==="process")&&i.jsx(Mg,{label:o("profiles.cloudView.filters.layer"),value:N,options:[{value:"all",label:o("profiles.cloudView.filters.all")},...J.layerHeights.map(Q=>({value:Q,label:Q}))],onChange:k}),Y&&i.jsx("button",{onClick:V,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(qg,{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:X[0]?o("profiles.cloudView.selectAnotherPreset",{type:X[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] ${X[0]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:X[0]?X[0].name:o("profiles.cloudView.selectFirst")}),i.jsx(e3,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:`px-2 py-1 text-sm rounded truncate max-w-[200px] ${X[1]?"bg-blue-500/30 text-blue-700 dark:text-blue-300":"bg-bambu-dark text-bambu-gray"}`,children:X[1]?X[1].name:o("profiles.cloudView.selectSecond")})]}),X[0]&&X[1]&&i.jsxs(Pe,{size:"sm",onClick:async()=>{try{const[Q,ie]=await Promise.all([ne.getCloudSettingDetail(X[0].setting_id),ne.getCloudSettingDetail(X[1].setting_id)]);Z([Q.setting||{},ie.setting||{}]),K(!0)}catch{}},children:[i.jsx(qg,{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(Wn,{className:"w-3 h-3"}),o("profiles.cloudView.lastSynced")," ",xv(e.toISOString(),"system",o)]}),i.jsx("span",{children:o("profiles.cloudView.showingCount",{showing:he.length,total:me})}),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")]})]})]}),he.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")}),Y&&i.jsx("button",{onClick:V,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(BC,{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:["(",he.filter(Q=>Q.type==="filament").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[he.filter(Q=>Q.type==="filament").map(Q=>i.jsx(Pj,{setting:Q,onClick:()=>oe(Q),onDuplicate:()=>se(Q),compareMode:z,isCompareSelected:_e(Q)!==void 0,compareIndex:_e(Q),compareDisabled:z&&!!X[0]&&X[0].type!==Q.type,t:o},Q.setting_id)),he.filter(Q=>Q.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:["(",he.filter(Q=>Q.type==="process").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[he.filter(Q=>Q.type==="process").map(Q=>i.jsx(Pj,{setting:Q,onClick:()=>oe(Q),onDuplicate:()=>se(Q),compareMode:z,isCompareSelected:_e(Q)!==void 0,compareIndex:_e(Q),compareDisabled:z&&!!X[0]&&X[0].type!==Q.type,t:o},Q.setting_id)),he.filter(Q=>Q.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:["(",he.filter(Q=>Q.type==="printer").length,")"]})]}),i.jsxs("div",{className:"space-y-1 max-h-[calc(100vh-320px)] overflow-y-auto pr-1",children:[he.filter(Q=>Q.type==="printer").map(Q=>i.jsx(Pj,{setting:Q,onClick:()=>oe(Q),onDuplicate:()=>se(Q),compareMode:z,isCompareSelected:_e(Q)!==void 0,compareIndex:_e(Q),compareDisabled:z&&!!X[0]&&X[0].type!==Q.type,t:o},Q.setting_id)),he.filter(Q=>Q.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(KZe,{setting:A,onClose:()=>T(null),onDeleted:()=>T(null),onDuplicate:()=>se(A),onEdit:()=>ze(A),hasPermission:s,t:o}),(C||U||B||$)&&i.jsx(YZe,{onClose:()=>{j(!1),O(null),D(null),G(null)},initialData:B||U||($?{type:$.type,name:"",base_id:"",setting:$.setting}:void 0),allPresets:t,t:o}),P&&i.jsx(XZe,{onClose:()=>E(!1),onApply:Q=>{G({type:Q.type,setting:Q.settings}),E(!1)},t:o}),H&&ee&&X[0]&&X[1]&&i.jsx(Xie,{onClose:()=>{K(!1),Z(null)},leftPreset:ee[0],rightPreset:ee[1],leftLabel:X[0].name,rightLabel:X[1].name,t:o})]})}function ZZe(){const{t}=Rt(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Ir(),[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(Hb,{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($b,{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(VC,{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(Pe,{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(i3,{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(QZe,{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(Pe,{onClick:()=>p(),children:t("profiles.retry")})]}):i.jsx(GZe,{onSuccess:g,t})]}),a==="local"&&i.jsx(qZe,{}),a==="kprofiles"&&i.jsx(BZe,{}),i.jsx(WZe,{})]})}const zy={Droplet:BC,Flame:pme,Ruler:Xfe,Sparkles:db,Square:vl,Cable:Zde,Wrench:jf,Calendar:ra,Timer:Lu,Cog:Ihe,Fan:fX,Zap:nd,Wind:CX,Thermometer:ZC,Layers:mi,Box:Ja,Target:SX,RefreshCw:Cr,Settings:QC,Filter:$C,CircleDot:yhe};function cv(t){return t&&zy[t]||jf}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 Ej(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 JZe(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/lubricate-x-y-z-axis":null;case"Lubricate Linear Rails":return s?"https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis":o?"https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis":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 eJe({item:t,onPerform:e,onToggle:n,hasPermission:r,t:a}){const s=cv(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(ra,{className:"w-3.5 h-3.5 text-bambu-gray shrink-0"})}),(()=>{const p=t.maintenance_type_wiki_url||JZe(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(Xr,{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(Mn,{className:"w-3 h-3"}),t.is_warning&&!t.is_due&&i.jsx(Wn,{className:"w-3 h-3"}),!t.is_due&&!t.is_warning&&t.enabled&&i.jsx(aa,{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(In,{checked:t.enabled,onChange:p=>n(t.id,p),disabled:!r("maintenance:update")})}),i.jsxs(Pe,{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(so,{className:"w-3.5 h-3.5"}),a("common.reset")]})]})]})})}function tJe({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(wt,{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(Mn,{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(Wn,{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(aa,{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(Pn,{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(Pe,{size:"sm",onClick:x,children:s("common.save")}),i.jsx(Pe,{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=cv(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(eJe,{item:v,onPerform:e,onToggle:n,hasPermission:a,t:s},v.id))})})]})}function nJe({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(""),[T,C]=w.useState("100"),[j,P]=w.useState("hours"),[E,U]=w.useState("Wrench"),[O,B]=w.useState(""),[D,$]=w.useState(new Set),[G,z]=w.useState(null),[W,X]=w.useState(null),ae=w.useMemo(()=>t?t.map(L=>({id:L.printer_id,name:L.printer_name})):[],[t]),H=L=>t?t.filter(R=>R.maintenance_items.some(q=>q.maintenance_type_id===L)).map(R=>({printerId:R.printer_id,printerName:R.printer_name,itemId:R.maintenance_items.find(q=>q.maintenance_type_id===L)?.id})):[],K=L=>{if(!t)return[];const R=new Set(H(L).map(q=>q.printerId));return ae.filter(q=>!R.has(q.id))},[ee,Z]=w.useState(null),[ve,ce]=w.useState(""),[J,je]=w.useState(""),[he,oe]=w.useState("hours"),[_e,se]=w.useState("Wrench"),[ze,V]=w.useState(""),Y=L=>{Z(L),ce(L.name),je(L.default_interval_hours.toString()),oe(L.interval_type||"hours"),se(L.icon||"Wrench"),V(L.wiki_url||"")},me=()=>{ee&&ve.trim()&&parseFloat(J)>0&&(a(ee.id,{name:ve.trim(),default_interval_hours:parseFloat(J),interval_type:he,icon:_e,wiki_url:ze.trim()||null}),Z(null))},Q=(L,R,q)=>{const le=parseFloat(x);if(!isNaN(le)&&le>0){const pe=Math.abs(le-R)<.01?null:le;n(L,{custom_interval_hours:pe,custom_interval_type:g!==q?g:null})}p(null)},ie=L=>{L.preventDefault(),k.trim()&&parseFloat(T)>0&&D.size>0&&(r({name:k.trim(),default_interval_hours:parseFloat(T),interval_type:j,icon:E,wiki_url:O.trim()||null},Array.from(D)),A(""),C("100"),P("hours"),B(""),$(new Set),N(!1))},ue=L=>{$(R=>{const q=new Set(R);return q.has(L)?q.delete(L):q.add(L),q})},Oe=t?.map(L=>({printerId:L.printer_id,printerName:L.printer_name,items:L.maintenance_items.sort((R,q)=>R.maintenance_type_id-q.maintenance_type_id)})).sort((L,R)=>L.printerName.localeCompare(R.printerName))||[],Ce=e.filter(L=>L.is_system),ge=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(Pe,{variant:"secondary",onClick:o,disabled:!d("maintenance:delete")||l,title:d("maintenance:delete")?void 0:h("maintenance.noPermissionDeleteTypes"),children:h("maintenance.restoreDefaults")}),i.jsxs(Pe,{onClick:()=>N(!_),disabled:!d("maintenance:create"),title:d("maintenance:create")?void 0:h("maintenance.noPermissionEditTypes"),children:[i.jsx(Yn,{className:"w-4 h-4"}),h("maintenance.addCustomType")]})]})]}),_&&i.jsx(wt,{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:T,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(zy).map(L=>{const R=zy[L];return i.jsx("button",{type:"button",onClick:()=>U(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(R,{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=>B(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:()=>ue(L.id),className:`px-3 py-1.5 rounded-lg text-sm transition-colors ${D.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))}),D.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(Pe,{type:"button",variant:"secondary",onClick:()=>{N(!1),$(new Set)},children:h("common.cancel")}),i.jsx(Pe,{type:"submit",disabled:!k.trim()||D.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:[Ce.map(L=>{const R=cv(L.icon),q=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(R,{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:[q==="days"?i.jsx(ra,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Ej(L.default_interval_hours,q,h)]})]}),i.jsx("button",{onClick:()=>{d("maintenance:delete")&&X(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)}),ge.map(L=>{const R=cv(L.icon),q=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:ve,onChange:Ie=>ce(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:he,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:J,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(zy).map(Ie=>{const $e=zy[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($e,{className:"w-3.5 h-3.5"})},Ie)})}),i.jsx("input",{type:"url",value:ze,onChange:Ie=>V(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(Pe,{size:"sm",onClick:me,disabled:!ve.trim(),children:h("common.save")}),i.jsx(Pe,{size:"sm",variant:"secondary",onClick:()=>Z(null),children:h("common.cancel")})]})]})},L.id);const pe=H(L.id),te=K(L.id),Ue=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(R,{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:[q==="days"?i.jsx(ra,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Ej(L.default_interval_hours,q,h)]})]}),i.jsxs("button",{onClick:()=>z(Ue?null:L.id),className:`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${pe.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:pe.length}),children:[i.jsx(xr,{className:"w-3 h-3"}),i.jsx("span",{className:"text-xs font-medium",children:pe.length}),i.jsx(Pn,{className:`w-3 h-3 transition-transform ${Ue?"rotate-180":""}`})]}),i.jsx("button",{onClick:()=>Y(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"})})]}),Ue&&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")}),pe.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:pe.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))}),te.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")}),te.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)})]})]}),Oe.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:Oe.map(L=>i.jsx(wt,{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(R=>{const q=cv(R.maintenance_type_icon),le=e.find($e=>$e.id===R.maintenance_type_id),pe=le?.default_interval_hours||R.interval_hours,te=le?.interval_type||"hours",Ue=R.interval_type||"hours",Ie=f===R.id;return i.jsxs("div",{className:"flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg",children:[i.jsx(q,{className:"w-4 h-4 text-bambu-gray shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray flex-1 truncate",children:R.maintenance_type_name}),Ie?i.jsxs("div",{className:"flex items-center gap-1",children:[g==="days"?i.jsx(ra,{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:$e=>y($e.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:$e=>v($e.target.value),onKeyDown:$e=>{$e.key==="Enter"&&Q(R.id,pe,te),$e.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(Pe,{size:"sm",onClick:()=>Q(R.id,pe,te),children:"OK"})]}):i.jsxs("button",{onClick:()=>{d("maintenance:update")&&(p(R.id),v(R.interval_hours.toString()),y(Ue))},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:[Ue==="days"?i.jsx(ra,{className:"w-3 h-3"}):i.jsx(Lu,{className:"w-3 h-3"}),Ej(R.interval_hours,Ue,h),i.jsx(Tf,{className:"w-3 h-3 text-bambu-gray"})]})]},R.id)})})]})},L.printerId))})]}),Oe.length===0&&i.jsx(wt,{children:i.jsxs(_t,{className:"text-center py-12",children:[i.jsx(Wn,{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")})]})}),W&&i.jsx(bn,{title:h("maintenance.deleteSystemTypeTitle"),message:h("maintenance.deleteSystemTypeMessage",{name:W.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(W.id),X(null)},onCancel:()=>X(null)})]})}function rJe(){const{t}=Rt(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Ir(),[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:T,notes:C})=>ne.performMaintenance(T,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.maintenanceComplete"))},onError:T=>{n(T.message,"error")}}),d=ot({mutationFn:({id:T,data:C})=>ne.updateMaintenanceItem(T,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]})},onError:T=>{n(T.message,"error")}}),h=ot({mutationFn:({id:T,data:C})=>ne.updateMaintenanceType(T,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onError:T=>{n(T.message,"error")}}),f=ot({mutationFn:ne.deleteMaintenanceType,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeDeleted"))},onError:T=>{n(T.message,"error")}}),p=ot({mutationFn:ne.restoreDefaultMaintenanceTypes,onSuccess:T=>{e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.defaultsRestored",{count:T.restored}))},onError:T=>{n(T.message,"error")}}),x=ot({mutationFn:({printerId:T,hours:C})=>ne.setPrinterHours(T,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),e.invalidateQueries({queryKey:["maintenanceSummary"]}),n(t("maintenance.printHoursUpdated"))},onError:T=>{n(T.message,"error")}}),v=ot({mutationFn:({printerId:T,typeId:C})=>ne.assignMaintenanceType(T,C),onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerAssigned"))},onError:T=>{n(T.message,"error")}}),g=ot({mutationFn:ne.removeMaintenanceItem,onSuccess:()=>{e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.printerRemoved"))},onError:T=>{n(T.message,"error")}}),y=T=>{u.mutate({id:T})},_=(T,C)=>{d.mutate({id:T,data:{enabled:C}})},N=(T,C)=>{x.mutate({printerId:T,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((T,C)=>T+C.due_count,0)||0,A=o?.reduce((T,C)=>T+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((T,C)=>{const j=T.due_count*10+T.warning_count,P=C.due_count*10+C.warning_count;return j!==P?P-j:T.printer_name.localeCompare(C.printer_name)}).map(T=>i.jsx(tJe,{overview:T,onPerform:y,onToggle:_,onSetHours:N,hasPermission:r,t},T.printer_id)):i.jsx(wt,{children:i.jsxs(_t,{className:"text-center py-16",children:[i.jsx(jf,{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(nJe,{overview:o,types:c||[],onUpdateInterval:(T,C)=>d.mutate({id:T,data:C}),onAddType:async(T,C)=>{const j=await ne.createMaintenanceType(T);for(const P of C)await ne.assignMaintenanceType(P,j.id);e.invalidateQueries({queryKey:["maintenanceTypes"]}),e.invalidateQueries({queryKey:["maintenanceOverview"]}),n(t("maintenance.typeUpdated"))},onUpdateType:(T,C)=>h.mutate({id:T,data:C}),onDeleteType:T=>f.mutate(T),onRestoreDefaults:()=>p.mutate(),isRestoringDefaults:p.isPending,onAssignType:(T,C)=>v.mutate({printerId:T,typeId:C}),onRemoveItem:T=>g.mutate(T),hasPermission:r,t})]})}const rK=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#8b5cf6","#ec4899","#6b7280"];function Yie({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||rK[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,T]=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:rK.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=>T(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(Pe,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Pe,{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 aJe({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:ub,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:Wn,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(Mh,{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(Mn,{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(Wn,{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(Mn,{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(Mn,{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(a3,{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 iJe(){const{t}=Rt(),e=Al(),n=tn(),{showToast:r}=cn(),{hasPermission:a}=Ir(),[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:B=>ne.createProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),r(t("projects.toast.created"),"success")},onError:B=>{r(B.message,"error")}}),g=ot({mutationFn:({id:B,data:D})=>ne.updateProject(B,D),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),o(!1),c(void 0),r(t("projects.toast.updated"),"success")},onError:B=>{r(B.message,"error")}}),y=ot({mutationFn:B=>ne.deleteProject(B),onSuccess:()=>{f(null),r(t("projects.toast.deleted"),"success"),setTimeout(()=>window.location.reload(),100)},onError:B=>{f(null),r(B.message,"error")}}),_=ot({mutationFn:B=>ne.importProject(B),onSuccess:()=>{n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success")},onError:B=>{r(B.message,"error")}}),N=w.useRef(null),k=async()=>{try{const B=await ne.getProjects(),D=await Promise.all(B.map(async W=>await ne.exportProjectJson(W.id))),$=new Blob([JSON.stringify(D,null,2)],{type:"application/json"}),G=URL.createObjectURL($),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(B){r(B.message,"error")}},A=()=>{N.current?.click()},T=async B=>{const D=B.target.files?.[0];if(D){try{if(D.name.toLowerCase().endsWith(".zip"))await ne.importProjectFile(D),n.invalidateQueries({queryKey:["projects"]}),r(t("projects.toast.imported"),"success");else{const G=await D.text(),z=JSON.parse(G),W=Array.isArray(z)?z:[z];for(const X of W)await _.mutateAsync(X);W.length>1&&r(t("projects.toast.multipleImported",{count:W.length}),"success")}}catch($){r(`${t("projects.toast.importFailed")}: ${$.message}`,"error")}B.target.value=""}},C=B=>{l?g.mutate({id:l.id,data:B}):v.mutate(B)},j=B=>{c(B),o(!0)},P=B=>{e(`/projects/${B.id}`)},E=B=>{f(B)},U=()=>{h!==null&&y.mutate(h)},O=p?.reduce((B,D)=>(B[D.status]=(B[D.status]||0)+1,B.all=(B.all||0)+1,B),{})||{};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:T,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(Pe,{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(Pe,{variant:"secondary",onClick:k,disabled:!a("projects:read"),title:a("projects:read")?t("projects.exportAll"):t("projects.noExportPermission"),children:[i.jsx(da,{className:"w-4 h-4 mr-2"}),t("projects.export")]}),i.jsxs(Pe,{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(Yn,{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:Wn},{key:"completed",label:t("projects.statusCompleted"),icon:ub},{key:"archived",label:t("projects.statusArchived"),icon:js},{key:"all",label:t("common.all"),icon:gs}].map(({key:B,label:D,icon:$})=>i.jsxs("button",{onClick:()=>d(B),className:`flex items-center gap-2 px-4 py-2 text-sm rounded-lg transition-all ${u===B?"bg-bambu-card text-white shadow-sm":"text-bambu-gray hover:text-white"}`,children:[i.jsx($,{className:"w-4 h-4"}),i.jsx("span",{children:D}),O[B]>0&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded-full ${u===B?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark-tertiary"}`,children:O[B]})]},B))}),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(Pe,{onClick:()=>o(!0),disabled:!a("projects:create"),title:a("projects:create")?void 0:t("projects.noCreatePermission"),children:[i.jsx(Yn,{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(B=>i.jsx(aJe,{project:B,onClick:()=>P(B),onEdit:()=>j(B),onDelete:()=>E(B.id),hasPermission:a,t},B.id))}),h!==null&&i.jsx(bn,{title:t("projects.deleteProject"),message:t("projects.deleteConfirm"),confirmText:t("projects.deleteProject"),variant:"danger",onConfirm:U,onCancel:()=>f(null)}),s&&i.jsx(Yie,{project:l,onClose:()=>{o(!1),c(void 0)},onSave:C,isLoading:v.isPending||g.isPending,t})]})}function sJe(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 oJe(t){return t>=1e3?`${(t/1e3).toFixed(2)}kg`:`${Math.round(t)}g`}function lJe({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 aK({icon:t,label:e,value:n,subValue:r,hint:a,color:s="text-bambu-gray"}){return i.jsx(wt,{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 cJe({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 uJe({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(Mn,{className:"w-3 h-3"}),a]})}function dJe(t){return t?hb(t,{year:"numeric",month:"short",day:"numeric"}):""}function jj(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 hJe(){const{id:t}=o0(),e=Al(),{t:n}=Rt(),r=tn(),{showToast:a}=cn(),{hasPermission:s}=Ir(),[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:T}=Je({queryKey:["settings"],queryFn:ne.getSettings}),{data:C}=Je({queryKey:["project-folders",f],queryFn:()=>ne.getLibraryFoldersByProject(f),enabled:f>0}),j=rl(T?.currency||"USD"),P=T?.time_format||"system",E=ot({mutationFn:we=>ne.updateProject(f,we),onSuccess:()=>{r.invalidateQueries({queryKey:["project",f]}),r.invalidateQueries({queryKey:["projects"]}),l(!1),u(!1),a(n("projectDetail.toast.projectUpdated"),"success")},onError:we=>{a(we.message,"error")}}),U=()=>{h(p?.notes||""),u(!0)},O=()=>{E.mutate({notes:d})},B=()=>{u(!1),h("")},[D,$]=w.useState(""),[G,z]=w.useState(1),[W,X]=w.useState(""),[ae,H]=w.useState(""),[K,ee]=w.useState(""),[Z,ve]=w.useState(!1),[ce,J]=w.useState(!1),[je,he]=w.useState(null),[oe,_e]=w.useState(""),[se,ze]=w.useState(1),[V,Y]=w.useState(""),[me,Q]=w.useState(""),[ie,ue]=w.useState(""),[Oe,Ce]=w.useState({isOpen:!1,title:"",message:"",onConfirm:()=>{}}),ge=ot({mutationFn:we=>ne.createBOMItem(f,we),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),$(""),z(1),X(""),H(""),ee(""),ve(!1),a(n("projectDetail.toast.partAdded"),"success")},onError:we=>a(we.message,"error")}),L=ot({mutationFn:({itemId:we,data:Ge})=>ne.updateBOMItem(f,we,Ge),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),he(null)},onError:we=>a(we.message,"error")}),R=ot({mutationFn:we=>ne.deleteBOMItem(f,we),onSuccess:()=>{r.invalidateQueries({queryKey:["project-bom",f]}),r.invalidateQueries({queryKey:["project",f]}),a(n("projectDetail.toast.partRemoved"),"success")},onError:we=>a(we.message,"error")}),q=we=>{we.preventDefault(),D.trim()&&ge.mutate({name:D.trim(),quantity_needed:G,unit_price:W?parseFloat(W):void 0,sourcing_url:ae.trim()||void 0,remarks:K.trim()||void 0})},le=we=>{const Ge=we.is_complete?0:we.quantity_needed;L.mutate({itemId:we.id,data:{quantity_acquired:Ge}})},pe=(we,Ge)=>{Ce({isOpen:!0,title:n("projectDetail.bom.deletePart"),message:n("projectDetail.bom.deleteConfirm",{name:Ge}),onConfirm:()=>{Ce(ke=>({...ke,isOpen:!1})),R.mutate(we)}})},te=we=>{he(we),_e(we.name),ze(we.quantity_needed),Y(we.unit_price?.toString()||""),Q(we.sourcing_url||""),ue(we.remarks||"")},Ue=we=>{we.preventDefault(),!(!je||!oe.trim())&&L.mutate({itemId:je.id,data:{name:oe.trim(),quantity_needed:se,unit_price:V?parseFloat(V):void 0,sourcing_url:me.trim()||void 0,remarks:ie.trim()||void 0}})},Ie=()=>{he(null)},$e=async()=>{try{const{blob:we,filename:Ge}=await ne.exportProjectZip(Number(f)),ke=URL.createObjectURL(we),tt=document.createElement("a");tt.href=ke,tt.download=Ge||`${p?.name||"project"}_${new Date().toISOString().split("T")[0]}.zip`,tt.click(),URL.revokeObjectURL(ke),a(n("projectDetail.toast.projectExported"),"success")}catch(we){a(we.message,"error")}},Fe=ot({mutationFn:()=>ne.createTemplateFromProject(f),onSuccess:()=>{r.invalidateQueries({queryKey:["projects"]}),a(n("projectDetail.toast.templateCreated"),"success")},onError:we=>a(we.message,"error")}),fe=we=>Df(we,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(Pe,{variant:"secondary",className:"mt-4",onClick:()=>e("/projects"),children:n("projectDetail.backToProjects")})]});const xe=p.stats,Ne=xe?.progress_percent??0,be=xe?.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(cX,{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(lJe,{status:p.status,t:n})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Pe,{variant:"secondary",onClick:$e,disabled:!s("projects:read"),title:s("projects:read")?n("projectDetail.exportProject"):n("projectDetail.noExportPermission"),children:[i.jsx(da,{className:"w-4 h-4 mr-2"}),n("projectDetail.export")]}),i.jsxs(Pe,{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(wt,{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:[xe?.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(Ne,100)}%`,backgroundColor:Ne>=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:Ne.toFixed(0)})}),xe?.remaining_prints!=null&&xe.remaining_prints>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:xe.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:[xe?.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(be,100)}%`,backgroundColor:be>=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:be.toFixed(0)})}),xe?.remaining_parts!=null&&xe.remaining_parts>0&&i.jsx("span",{className:"text-xs text-bambu-gray/70",children:n("projectDetail.progress.remaining",{count:xe.remaining_parts})})]})]})]})}),xe&&i.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[i.jsx(wt,{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:[xe.total_archives," ",i.jsx("span",{className:"text-sm font-normal text-bambu-gray",children:n("projectDetail.stats.total")})]}),xe.failed_prints>0&&i.jsx("p",{className:"text-sm text-status-error",children:n("projectDetail.stats.failed",{count:xe.failed_prints})}),i.jsx("p",{className:"text-sm text-bambu-gray",children:n("projectDetail.stats.partsPrinted",{count:xe.completed_prints})})]})]})})}),i.jsx(aK,{icon:Wn,label:n("projectDetail.stats.printTime"),value:sJe(xe.total_print_time_hours),color:"text-yellow-400"}),i.jsx(aK,{icon:xr,label:n("projectDetail.stats.filamentUsed"),value:oJe(xe.total_filament_grams),color:"text-purple-400"})]}),xe&&(xe.estimated_cost>0||p.budget)&&i.jsx(wt,{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,xe.estimated_cost.toFixed(2)]})]}),xe.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:[xe.total_energy_kwh.toFixed(3)," kWh",xe.total_energy_cost>0&&i.jsxs("span",{className:"text-sm text-bambu-gray ml-1",children:["(",j,xe.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-xe.estimated_cost>=0?"text-bambu-green":"text-red-400"}`,children:[j,(p.budget-xe.estimated_cost).toFixed(2)]})]})]})]})]})}),p.children&&p.children.length>0&&i.jsx(wt,{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(wme,{className:"w-5 h-5"}),n("projectDetail.subProjects.title",{count:p.children.length})]}),i.jsx("div",{className:"space-y-2",children:p.children.map(we=>i.jsxs(Ks,{to:`/projects/${we.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:we.color||"#6b7280"}}),i.jsx("span",{className:"text-white",children:we.name}),i.jsx("span",{className:`text-xs px-2 py-0.5 rounded ${we.status==="completed"?"bg-status-ok/20 text-status-ok":we.status==="archived"?"bg-bambu-gray/20 text-bambu-gray":"bg-blue-500/20 text-blue-400"}`,children:we.status})]}),we.progress_percent!==null&&i.jsxs("span",{className:"text-sm text-bambu-gray",children:[we.progress_percent.toFixed(0),"%"]})]},we.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(uJe,{priority:p.priority,t:n})]}),p.due_date&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ra,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("span",{className:"text-sm text-white",children:dJe(p.due_date)}),jj(p.due_date,n)&&i.jsxs("span",{className:`text-xs ${jj(p.due_date,n).color}`,children:["(",jj(p.due_date,n).label,")"]})]}),p.tags&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Vh,{className:"w-4 h-4 text-bambu-gray"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:p.tags.split(",").map((we,Ge)=>i.jsx("span",{className:"px-2 py-0.5 bg-bambu-dark-tertiary text-bambu-gray text-xs rounded",children:we.trim()},Ge))})]})]}),i.jsx(wt,{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(Ts,{className:"w-5 h-5"}),n("projectDetail.notes.title")]}),c?i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(Pe,{variant:"secondary",size:"sm",onClick:B,disabled:E.isPending,children:[i.jsx(Ot,{className:"w-4 h-4 mr-1"}),n("common.cancel")]}),i.jsxs(Pe,{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(Pe,{variant:"secondary",size:"sm",onClick:U,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(YR,{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(wt,{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(Jl,{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(we=>i.jsxs(Ks,{to:`/files?folder=${we.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(Jl,{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:we.name}),i.jsx("p",{className:"text-xs text-bambu-gray",children:n("projectDetail.files.fileCount",{count:we.file_count})})]})]}),i.jsx(pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"})]},we.id))}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.files.empty")})]})}),i.jsx(wt,{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(vX,{className:"w-5 h-5"}),n("projectDetail.bom.title"),xe&&xe.bom_total_items>0&&i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",n("projectDetail.bom.acquired",{completed:xe.bom_completed_items,total:xe.bom_total_items}),")"]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[_&&_.some(we=>we.is_complete)&&i.jsx("button",{onClick:()=>J(!ce),className:`text-xs px-2 py-1 rounded transition-colors ${ce?"bg-bambu-green/20 text-bambu-green":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:n(ce?"projectDetail.bom.showAll":"projectDetail.bom.hideDone")}),!Z&&i.jsxs(Pe,{variant:"secondary",size:"sm",onClick:()=>ve(!0),disabled:!s("projects:update"),title:s("projects:update")?void 0:n("projectDetail.bom.noAddPermission"),children:[i.jsx(Yn,{className:"w-4 h-4 mr-1"}),n("projectDetail.bom.addPart")]})]})]}),Z&&i.jsxs("form",{onSubmit:q,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:D,onChange:we=>$(we.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:we=>z(parseInt(we.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:W,onChange:we=>X(we.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:we=>H(we.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:K,onChange:we=>ee(we.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(Pe,{type:"button",variant:"secondary",size:"sm",onClick:()=>ve(!1),children:n("common.cancel")}),i.jsx(Pe,{type:"submit",size:"sm",disabled:!D.trim()||ge.isPending,children:ge.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(we=>!ce||!we.is_complete).map(we=>i.jsx("div",{className:`p-3 rounded-lg transition-colors ${we.is_complete?"bg-status-ok/10":"bg-bambu-dark"}`,children:je?.id===we.id?i.jsxs("form",{onSubmit:Ue,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:Ge=>_e(Ge.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:Ge=>ze(parseInt(Ge.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:V,onChange:Ge=>Y(Ge.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:me,onChange:Ge=>Q(Ge.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:Ge=>ue(Ge.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(Pe,{type:"button",variant:"secondary",size:"sm",onClick:Ie,children:n("common.cancel")}),i.jsx(Pe,{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")&&le(we),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 ${we.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:we.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 ${we.is_complete?"text-bambu-gray line-through":"text-white"}`,children:[we.name,i.jsxs("span",{className:"text-bambu-gray font-normal ml-2",children:["x",we.quantity_needed]})]}),we.unit_price!==null&&i.jsxs("span",{className:"text-xs text-bambu-green whitespace-nowrap",children:[j,(we.unit_price*we.quantity_needed).toFixed(2)]})]}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{onClick:()=>s("projects:update")&&te(we),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")&&pe(we.id,we.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"})})]})]}),we.sourcing_url&&i.jsxs("a",{href:we.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:Ge=>Ge.stopPropagation(),children:[i.jsx(Xr,{className:"w-3 h-3 flex-shrink-0"}),i.jsx("span",{className:"truncate",children:(()=>{try{return new URL(we.sourcing_url).hostname.replace("www.","")}catch{return we.sourcing_url}})()})]}),we.remarks&&i.jsx("p",{className:"mt-1 text-xs text-bambu-gray/80 italic",children:we.remarks})]})]})},we.id)),_.some(we=>we.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((we,Ge)=>we+(Ge.unit_price||0)*Ge.quantity_needed,0).toFixed(2)]})]})]}):i.jsx("p",{className:"text-bambu-gray/70 text-sm italic",children:n("projectDetail.bom.empty")})]})}),i.jsx(wt,{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(pv,{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((we,Ge)=>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 ${we.event_type==="print_completed"?"bg-status-ok/20 text-status-ok":we.event_type==="print_failed"?"bg-status-error/20 text-status-error":we.event_type==="print_started"?"bg-yellow-500/20 text-yellow-400":"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[we.event_type==="print_completed"&&i.jsx(pr,{className:"w-4 h-4"}),we.event_type==="print_failed"&&i.jsx(hi,{className:"w-4 h-4"}),we.event_type==="print_started"&&i.jsx(xr,{className:"w-4 h-4"}),we.event_type==="queued"&&i.jsx(a3,{className:"w-4 h-4"}),we.event_type==="project_created"&&i.jsx(Yn,{className:"w-4 h-4"})]}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white",children:we.title}),we.description&&i.jsx("p",{className:"text-xs text-bambu-gray truncate",children:we.description}),i.jsx("p",{className:"text-xs text-bambu-gray/70",children:fe(we.timestamp)})]})]},Ge))}):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(Pe,{variant:"secondary",size:"sm",onClick:()=>Fe.mutate(),disabled:Fe.isPending||!s("projects:create"),title:s("projects:create")?void 0:n("projectDetail.template.noCreatePermission"),children:[Fe.isPending?i.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):i.jsx(Ql,{className:"w-4 h-4 mr-2"}),n("projectDetail.template.saveAsTemplate")]})}),xe&&(xe.queued_prints>0||xe.in_progress_prints>0)&&i.jsx(wt,{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(a3,{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:[xe.in_progress_prints>0&&i.jsx("span",{className:"text-yellow-400",children:n("projectDetail.queue.printing",{count:xe.in_progress_prints})}),xe.queued_prints>0&&i.jsx("span",{className:"text-bambu-gray",children:n("projectDetail.queue.queued",{count:xe.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(cJe,{archives:g||[],t:n})]}),o&&i.jsx(Yie,{t:n,project:{...p,archive_count:xe?.total_archives||0,total_items:xe?.total_items||0,completed_count:xe?.completed_prints||0,failed_count:xe?.failed_prints||0,queue_count:xe?.queued_prints||0,progress_percent:xe?.progress_percent||null,archives:[]},onClose:()=>l(!1),onSave:we=>E.mutate(we),isLoading:E.isPending}),Oe.isOpen&&i.jsx(bn,{title:Oe.title,message:Oe.message,confirmText:n("common.delete"),variant:"danger",onConfirm:Oe.onConfirm,onCancel:()=>Ce(we=>({...we,isOpen:!1}))})]})}function mJe({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(Pe,{type:"button",variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Pe,{type:"submit",disabled:!s.trim()||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("common.create")})]})]})]})})}function fJe({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(Pe,{type:"button",variant:"secondary",onClick:n,children:s("common.cancel")}),i.jsx(Pe,{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 pJe({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(Jl,{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(Pe,{type:"button",variant:"secondary",onClick:r,children:o("common.cancel")}),i.jsx(Pe,{onClick:()=>a(l),disabled:s,children:s?i.jsx(it,{className:"w-4 h-4 animate-spin"}):o("common.move")})]})]})]})})}function gJe({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(jh,{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(Ot,{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(uX,{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(Pe,{variant:"danger",onClick:f,disabled:r,children:[i.jsx(JC,{className:"w-4 h-4 mr-2"}),a("fileManager.unlink")]}),i.jsxs("div",{className:`flex gap-2 ${p?"":"ml-auto"}`,children:[i.jsx(Pe,{variant:"secondary",onClick:e,children:a("common.cancel")}),i.jsx(Pe,{onClick:h,disabled:!l||r,children:r?i.jsx(it,{className:"w-4 h-4 animate-spin"}):a("fileManager.link")})]})]})]})})}function bJe({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=$=>{$.preventDefault(),l(!0)},_=$=>{$.preventDefault(),l(!1)},N=$=>{$.preventDefault(),l(!1);const G=Array.from($.dataTransfer.files);A(G)},k=$=>{$.target.files&&A(Array.from($.target.files))},A=$=>{const G=$.map(z=>({file:z,status:"pending",isZip:z.name.toLowerCase().endsWith(".zip"),is3mf:z.name.toLowerCase().endsWith(".3mf")}));s(z=>[...z,...G])},T=$=>{s(G=>G.filter((z,W)=>W!==$))},C=a.some($=>$.isZip&&$.status==="pending"),j=a.some($=>$.file.name.toLowerCase().endsWith(".stl")&&$.status==="pending"),P=a.some($=>$.is3mf&&$.status==="pending"),E=async()=>{if(a.length!==0){u(!0);for(let $=0;$G.map((z,W)=>W===$?{...z,status:"uploading"}:z));try{if(a[$].isZip){const G=await ne.extractZipFile(a[$].file,t,d,f,x);s(z=>z.map((W,X)=>X===$?{...W,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}:W))}else await ne.uploadLibraryFile(a[$].file,t,x),s(G=>G.map((z,W)=>W===$?{...z,status:"success"}:z))}catch(G){s(z=>z.map((W,X)=>X===$?{...W,status:"error",error:G instanceof Error?G.message:"Upload failed"}:W))}}u(!1),n(),e()}},U=a.filter($=>$.status==="pending").length,O=a.filter($=>$.status==="success").length,B=a.filter($=>$.status==="error").length,D=a.length>0&&U===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(Ot,{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:$=>h($.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:$=>p($.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($.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(($,G)=>i.jsxs("div",{className:"flex items-center gap-3 p-2 bg-bambu-dark rounded-lg",children:[$.isZip?i.jsx(js,{className:"w-4 h-4 text-blue-400 flex-shrink-0"}):i.jsx(HC,{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:$.file.name}),i.jsxs("p",{className:"text-xs text-bambu-gray",children:[($.file.size/1024/1024).toFixed(2)," MB",$.isZip&&$.status==="pending"&&i.jsxs("span",{className:"text-blue-400 ml-2",children:["• ",r("fileManager.willBeExtracted")]}),$.extractedCount!==void 0&&i.jsxs("span",{className:"text-green-400 ml-2",children:["• ",r("fileManager.filesExtracted",{count:$.extractedCount})]})]})]}),$.status==="pending"&&i.jsx("button",{onClick:()=>T(G),className:"p-1 hover:bg-bambu-dark-tertiary rounded",children:i.jsx(Ot,{className:"w-4 h-4 text-bambu-gray"})}),$.status==="uploading"&&i.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),$.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-green-500"}),$.status==="error"&&i.jsx("span",{title:$.error,children:i.jsx(hi,{className:"w-4 h-4 text-red-500"})})]},G))}),D&&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}),B>0&&i.jsxs("span",{className:"text-red-400",children:[", ",r("fileManager.uploadFailed",{count:B})]})]})})]}),i.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[i.jsx(Pe,{variant:"secondary",onClick:e,children:r(D?"common.close":"common.cancel")}),!D&&i.jsx(Pe,{onClick:E,disabled:U===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")," ",U>0?`(${U})`:""]})})]})]})})}function Qie({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(Jl,{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(jh,{className:"w-3 h-3"}),t.project_name?i.jsx(uX,{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(jh,{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(Mh,{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(jh,{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(Qie,{folder:g,selectedFolderId:e,onSelect:n,onDelete:r,onLink:a,onRename:s,depth:o+1,wrapNames:l,hasPermission:c,t:u},g.id))})]})}function rF(t){const e=t.toLowerCase();return e.endsWith(".gcode")||e.includes(".gcode.")}function xJe({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(Wn,{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(Mh,{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&&rF(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&&rF(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(Wn,{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(da,{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 yJe(){const{t}=Rt(),e=tn(),{showToast:n}=cn(),{hasPermission:r,hasAnyPermission:a,canModify:s,authEnabled:o}=Ir(),[l]=pF(),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),[T,C]=w.useState(null),[j,P]=w.useState(null),[E,U]=w.useState(null),[O,B]=w.useState(null),[D,$]=w.useState(null),[G,z]=w.useState({}),[W,X]=w.useState(null),[ae,H]=w.useState(()=>localStorage.getItem("library-view-mode")||"grid"),[K,ee]=w.useState(()=>localStorage.getItem("library-wrap-folders")==="true"),[Z,ve]=w.useState(()=>{const Be=localStorage.getItem("library-sidebar-width");return Be?parseInt(Be,10):256}),[ce,J]=w.useState(!1),je=w.useRef(null);w.useEffect(()=>{if(!ce)return;document.body.style.userSelect="none",document.body.style.cursor="col-resize";const Be=yt=>{if(!je.current)return;const Gt=je.current.parentElement?.getBoundingClientRect();if(!Gt)return;const Cn=yt.clientX-Gt.left,yr=Math.min(500,Math.max(200,Cn));ve(yr)},bt=()=>{J(!1),document.body.style.userSelect="",document.body.style.cursor="",localStorage.setItem("library-sidebar-width",String(Z))};return document.addEventListener("mousemove",Be),document.addEventListener("mouseup",bt),()=>{document.removeEventListener("mousemove",Be),document.removeEventListener("mouseup",bt),document.body.style.userSelect="",document.body.style.cursor=""}},[ce,Z]);const[he,oe]=w.useState(""),[_e,se]=w.useState("all"),[ze,V]=w.useState(""),[Y,me]=w.useState(()=>localStorage.getItem("library-sort-field")||"name"),[Q,ie]=w.useState(()=>localStorage.getItem("library-sort-direction")||"asc"),ue=bne();w.useEffect(()=>{const Be=l.get("folder");if(Be){const bt=parseInt(Be,10);h(bt)}},[l]);const{data:Oe}=Je({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:Ce,isLoading:ge}=Je({queryKey:["library-folders"],queryFn:()=>ne.getLibraryFolders()}),{data:L,isLoading:R}=Je({queryKey:["library-files",d],queryFn:()=>ne.getLibraryFiles(d,d===null)}),{data:q}=Je({queryKey:["library-stats"],queryFn:()=>ne.getLibraryStats()}),{data:le}=Je({queryKey:["users"],queryFn:()=>ne.getUsers()}),pe=w.useMemo(()=>{if(!L)return[];const Be=new Set(L.map(bt=>bt.file_type));return Array.from(Be).sort()},[L]),te=w.useMemo(()=>{if(!L)return[];let Be=[...L];if(he.trim()){const bt=he.toLowerCase();Be=Be.filter(yt=>yt.filename.toLowerCase().includes(bt)||yt.print_name&&yt.print_name.toLowerCase().includes(bt))}if(_e!=="all"&&(Be=Be.filter(bt=>bt.file_type===_e)),ze.trim()){const bt=ze.toLowerCase();Be=Be.filter(yt=>yt.created_by_username&&yt.created_by_username.toLowerCase().includes(bt))}return Be.sort((bt,yt)=>{let Gt=0;switch(Y){case"name":Gt=(bt.print_name||bt.filename).localeCompare(yt.print_name||yt.filename);break;case"date":Gt=new Date(bt.created_at).getTime()-new Date(yt.created_at).getTime();break;case"size":Gt=bt.file_size-yt.file_size;break;case"type":Gt=bt.file_type.localeCompare(yt.file_type);break;case"prints":Gt=bt.print_count-yt.print_count;break}return Q==="asc"?Gt:-Gt}),Be},[L,he,_e,ze,Y,Q]),Ue=w.useMemo(()=>{if(!q||!Oe)return!1;const Be=(Oe.library_disk_warning_gb||5)*1024*1024*1024;return q.disk_free_bytesne.createLibraryFolder(Be),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),v(!1),n(t("fileManager.toast.folderCreated"),"success")},onError:Be=>n(Be.message,"error")}),$e=ot({mutationFn:Be=>ne.deleteLibraryFolder(Be),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-stats"]}),d===T?.id&&h(null),C(null),n(t("fileManager.toast.folderDeleted"),"success")},onError:Be=>{C(null),n(Be.message,"error")}}),Fe=ot({mutationFn:Be=>ne.deleteLibraryFile(Be),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]}),p(Be=>Be.filter(bt=>bt!==T?.id)),C(null),n(t("fileManager.toast.fileDeleted"),"success")},onError:Be=>{C(null),n(Be.message,"error")}}),fe=ot({mutationFn:Be=>ne.bulkDeleteLibrary(Be,[]),onSuccess:(Be,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:Be=>{C(null),n(Be.message,"error")}}),xe=ot({mutationFn:({fileIds:Be,folderId:bt})=>ne.moveLibraryFiles(Be,bt),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),p([]),y(!1),n(t("fileManager.toast.filesMoved"),"success")},onError:Be=>n(Be.message,"error")}),Ne=ot({mutationFn:({id:Be,data:bt})=>ne.updateLibraryFolder(Be,bt),onSuccess:(Be,bt)=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["project-folders"]}),e.invalidateQueries({queryKey:["archive-folders"]}),A(null);const yt=bt.data.project_id===0&&bt.data.archive_id===0;n(t(yt?"fileManager.toast.folderUnlinked":"fileManager.toast.folderLinked"),"success")},onError:Be=>n(Be.message,"error")}),be=ot({mutationFn:({id:Be,filename:bt})=>ne.updateLibraryFile(Be,{filename:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.fileRenamed"),"success")},onError:Be=>{$(null),n(Be.message,"error")}}),we=ot({mutationFn:({id:Be,name:bt})=>ne.updateLibraryFolder(Be,{name:bt}),onSuccess:()=>{e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-files"]}),$(null),n(t("fileManager.toast.folderRenamed"),"success")},onError:Be=>{$(null),n(Be.message,"error")}}),Ge=ot({mutationFn:()=>ne.batchGenerateStlThumbnails({all_missing:!0}),onSuccess:Be=>{if(e.invalidateQueries({queryKey:["library-files"]}),Be.succeeded>0){const bt=Date.now(),yt={};Be.results.forEach(Gt=>{Gt.success&&(yt[Gt.file_id]=bt)}),z(Gt=>({...Gt,...yt}))}Be.succeeded>0&&Be.failed===0?n(t("fileManager.toast.thumbnailsGenerated",{count:Be.succeeded}),"success"):Be.succeeded>0&&Be.failed>0?n(t("fileManager.toast.thumbnailsGeneratedPartial",{succeeded:Be.succeeded,failed:Be.failed}),"success"):Be.processed===0?n(t("fileManager.toast.noStlMissingThumbnails"),"info"):n(t("fileManager.toast.failedToGenerateThumbnails",{error:Be.results[0]?.error||"Unknown error"}),"error")},onError:Be=>n(Be.message,"error")}),ke=ot({mutationFn:Be=>ne.batchGenerateStlThumbnails({file_ids:[Be]}),onSuccess:Be=>{if(e.invalidateQueries({queryKey:["library-files"]}),Be.succeeded>0){const bt=Be.results[0]?.file_id;bt&&z(yt=>({...yt,[bt]:Date.now()})),n(t("fileManager.toast.thumbnailGenerated"),"success")}else n(t("fileManager.toast.failedToGenerateThumbnail",{error:Be.results[0]?.error||"Unknown error"}),"error")},onError:Be=>n(Be.message,"error")}),tt=w.useCallback(Be=>{const bt=Be.toLowerCase();return bt.endsWith(".gcode")||bt.includes(".gcode.")},[]),De=w.useMemo(()=>L?L.filter(Be=>f.includes(Be.id)&&tt(Be.filename)):[],[L,f,tt]),Ke=w.useCallback(Be=>{p(bt=>bt.includes(Be)?bt.filter(yt=>yt!==Be):[...bt,Be])},[]),Ae=w.useCallback(()=>{te.length>0&&p(te.map(Be=>Be.id))},[te]),Re=w.useCallback(()=>{p([])},[]),Ve=()=>{e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["library-folders"]}),e.invalidateQueries({queryKey:["library-stats"]})},ht=Be=>{ne.downloadLibraryFile(Be).catch(bt=>{console.error("Library file download failed:",bt)})},At=()=>{T&&(T.type==="file"?Fe.mutate(T.id):T.type==="folder"?$e.mutate(T.id):T.type==="bulk"&&fe.mutate(f))},Dt=$e.isPending||Fe.isPending||fe.isPending,It=Be=>{H(Be),localStorage.setItem("library-view-mode",Be)},kt=ge||R;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(Jl,{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:()=>It("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(d0,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>It("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(qC,{className:"w-4 h-4"})})]}),i.jsxs(Pe,{variant:"secondary",onClick:()=>Ge.mutate(),disabled:Ge.isPending||!a("library:update_own","library:update_all"),title:a("library:update_own","library:update_all")?t("fileManager.generateThumbnailsForMissing"):t("fileManager.noPermissionGenerateThumbnail"),children:[Ge.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(Pe,{variant:"secondary",onClick:()=>v(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionCreateFolder"),children:[i.jsx(yme,{className:"w-4 h-4 mr-2"}),t("fileManager.newFolder")]}),i.jsxs(Pe,{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")]})]})]}),Ue&&q&&Oe&&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(Mn,{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(q.disk_free_bytes),total:ul(q.disk_total_bytes),threshold:Oe.library_disk_warning_gb})})]})]}),q&&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(HC,{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:q.total_files})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx(Jl,{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:q.total_folders})]}),i.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[i.jsx($b,{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(q.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 ${Ue?"text-amber-500":"text-white"}`,children:ul(q.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:Be=>h(Be.target.value?parseInt(Be.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")]}),Ce&&(()=>{const Be=(bt,yt=0)=>{const Gt=[];for(const Cn of bt)Gt.push({id:Cn.id,name:Cn.name,fileCount:Cn.file_count,depth:yt}),Cn.children.length>0&&Gt.push(...Be(Cn.children,yt+1));return Gt};return Be(Ce).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:`${Z}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 ${ce?"bg-bambu-green":"hover:bg-bambu-green/50"}`,onMouseDown:Be=>{Be.preventDefault(),J(!0)},onDoubleClick:()=>{ve(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 ${ce?"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 Be=!K;ee(Be),localStorage.setItem("library-wrap-folders",String(Be))},className:`text-xs px-1.5 py-0.5 rounded transition-colors ${K?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:text-white hover:bg-bambu-dark"}`,title:t(K?"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")})]}),Ce?.map(Be=>i.jsx(Qie,{folder:Be,selectedFolderId:d,onSelect:h,onDelete:bt=>C({type:"folder",id:bt}),onLink:A,onRename:bt=>$({type:"folder",id:bt.id,name:bt.name}),wrapNames:K,hasPermission:r,t},Be.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:he,onChange:Be=>oe(Be.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($C,{className:"w-4 h-4 text-bambu-gray hidden sm:block"}),i.jsxs("select",{value:_e,onChange:Be=>se(Be.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")}),pe.map(Be=>i.jsx("option",{value:Be,children:Be.toUpperCase()},Be))]})]}),o&&i.jsxs("div",{className:"relative",children:[i.jsx("input",{type:"text",placeholder:t("fileManager.filterByUser",{defaultValue:"Filter by user"}),value:ze,onChange:Be=>V(Be.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 ${ze?"pr-7":""}`,style:ze?{WebkitAppearance:"none",MozAppearance:"textfield"}:void 0}),ze&&i.jsx("button",{onClick:()=>V(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white z-10",children:i.jsx(Ot,{className:"w-3 h-3"})}),i.jsx("datalist",{id:"usernames-list",children:le?.map(Be=>i.jsx("option",{value:Be.username},Be.id))})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("select",{value:Y,onChange:Be=>{const bt=Be.target.value;me(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(Be=>{const bt=Be==="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(Q==="asc"?"fileManager.ascending":"fileManager.descending"),children:Q==="asc"?i.jsx(Ode,{className:"w-4 h-4 text-white"}):i.jsx(Pde,{className:"w-4 h-4 text-white"})})]}),(he||_e!=="all"||ze)&&i.jsx("span",{className:"text-sm text-bambu-gray hidden sm:inline",children:t("fileManager.resultsCount",{showing:te.length,total:L.length})})]}),te.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===te.length&&f.length>0?i.jsxs(Pe,{variant:"secondary",size:"sm",onClick:Re,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(Pe,{variant:"secondary",size:"sm",onClick:Ae,children:[i.jsx(oo,{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:[De.length===1&&i.jsxs(Pe,{variant:"primary",size:"sm",onClick:()=>U(De[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")})]}),De.length===1&&i.jsxs(Pe,{variant:"secondary",size:"sm",onClick:()=>B(De[0]),disabled:!r("queue:create"),title:r("queue:create")?void 0:t("fileManager.noPermissionAddToQueue"),children:[i.jsx(Wn,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("fileManager.schedulePrint")})]}),i.jsxs(Pe,{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(Mfe,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.move")})]}),i.jsxs(Pe,{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(Pe,{variant:"secondary",size:"sm",onClick:Re,children:[i.jsx(Ot,{className:"w-4 h-4 sm:mr-1"}),i.jsx("span",{className:"hidden sm:inline",children:t("common.clear")})]})]})]})]}),kt?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(Pe,{onClick:()=>N(!0),disabled:!r("library:upload"),title:r("library:upload")?void 0:t("fileManager.noPermissionUpload"),children:[i.jsx(Yn,{className:"w-4 h-4 mr-2"}),t("fileManager.uploadFiles")]})]}):te.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(Pe,{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:te.map(Be=>i.jsx(xJe,{file:Be,isSelected:f.includes(Be.id),isMobile:ue,t,onSelect:Ke,onDelete:bt=>C({type:"file",id:bt}),onDownload:ht,onAddToQueue:bt=>{const yt=L?.find(Gt=>Gt.id===bt);yt&&B(yt)},onPrint:P,onPreview3d:X,onRename:bt=>$({type:"file",id:bt.id,name:bt.filename}),onGenerateThumbnail:bt=>ke.mutate(bt.id),thumbnailVersion:G[Be.id],hasPermission:r,canModify:s,authEnabled:o},Be.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",{})]}),te.map(Be=>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(Be.id)?"bg-bambu-green/10":""}`,onClick:()=>Ke(Be.id),children:[i.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center ${f.includes(Be.id)?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:f.includes(Be.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:Be.thumbnail_path?i.jsx("img",{src:`${ne.getLibraryFileThumbnailUrl(Be.id)}${G[Be.id]?`?v=${G[Be.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"})})}),Be.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(Be.id)}${G[Be.id]?`?v=${G[Be.id]}`:""}`,alt:Be.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:Be.print_name||Be.filename})})]}),o&&i.jsx("div",{className:"text-sm text-bambu-gray flex items-center gap-1",children:Be.created_by_username?i.jsxs(i.Fragment,{children:[i.jsx(td,{className:"w-3 h-3"}),i.jsx("span",{className:"truncate",children:Be.created_by_username})]}):"-"}),i.jsx("div",{children:i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded font-medium ${Be.file_type==="3mf"?"bg-bambu-green/20 text-bambu-green":Be.file_type==="gcode"?"bg-blue-500/20 text-blue-400":Be.file_type==="stl"?"bg-purple-500/20 text-purple-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:Be.file_type.toUpperCase()})}),i.jsx("div",{className:"text-sm text-bambu-gray",children:ul(Be.file_size)}),i.jsx("div",{className:"text-sm text-bambu-gray",children:Be.print_count>0?`${Be.print_count}x`:"-"}),i.jsxs("div",{className:"flex items-center gap-1",onClick:bt=>bt.stopPropagation(),children:[rF(Be.filename)&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>r("printers:control")&&P(Be),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")&&B(Be)},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(Wn,{className:"w-4 h-4"})})]}),(Be.file_type==="3mf"||Be.file_type==="gcode"||Be.file_type==="stl")&&i.jsx("button",{onClick:()=>r("library:read")&&X(Be),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")&&ht(Be.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(da,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","update",Be.created_by_id)&&$({type:"file",id:Be.id,name:Be.filename}),className:`p-1.5 rounded transition-colors ${s("library","update",Be.created_by_id)?"hover:bg-bambu-dark text-bambu-gray hover:text-white":"text-bambu-gray/50 cursor-not-allowed"}`,title:s("library","update",Be.created_by_id)?t("common.rename"):t("fileManager.noPermissionRenameFile"),disabled:!s("library","update",Be.created_by_id),children:i.jsx($a,{className:"w-4 h-4"})}),Be.file_type==="stl"&&i.jsx("button",{onClick:()=>s("library","update",Be.created_by_id)&&ke.mutate(Be.id),className:`p-1.5 rounded transition-colors ${s("library","update",Be.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",Be.created_by_id)?t("fileManager.generateThumbnail"):t("fileManager.noPermissionGenerateThumbnail"),disabled:ke.isPending||!s("library","update",Be.created_by_id),children:i.jsx(Ju,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>s("library","delete",Be.created_by_id)&&C({type:"file",id:Be.id}),className:`p-1.5 rounded transition-colors ${s("library","delete",Be.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",Be.created_by_id)?t("common.delete"):t("fileManager.noPermissionDeleteFile"),disabled:!s("library","delete",Be.created_by_id),children:i.jsx(Jt,{className:"w-4 h-4"})})]})]},Be.id))]})})]})]}),x&&i.jsx(mJe,{parentId:d,onClose:()=>v(!1),onSave:Be=>Ie.mutate(Be),isLoading:Ie.isPending,t}),g&&Ce&&i.jsx(pJe,{folders:Ce,selectedFiles:f,currentFolderId:d,onClose:()=>y(!1),onMove:Be=>xe.mutate({fileIds:f,folderId:Be}),isLoading:xe.isPending,t}),_&&i.jsx(bJe,{folderId:d,onClose:()=>N(!1),onUploadComplete:Ve,t}),k&&i.jsx(gJe,{folder:k,onClose:()=>A(null),onLink:Be=>Ne.mutate({id:k.id,data:Be}),isLoading:Ne.isPending,t}),T&&i.jsx(bn,{title:T.type==="folder"?t("fileManager.deleteFolder"):T.type==="bulk"?t("fileManager.deleteFilesCount",{count:T.count}):t("fileManager.deleteFile"),message:T.type==="folder"?t("fileManager.deleteFolderConfirm"):T.type==="bulk"?t("fileManager.deleteFilesConfirm",{count:T.count}):t("fileManager.deleteFileConfirm"),confirmText:t("common.delete"),variant:"danger",isLoading:Dt,loadingText:t("fileManager.deleting"),onConfirm:At,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:()=>U(null),onSuccess:()=>{U(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:()=>B(null),onSuccess:()=>{B(null),p([]),e.invalidateQueries({queryKey:["library-files"]}),e.invalidateQueries({queryKey:["queue"]}),e.invalidateQueries({queryKey:["archives"]})}}),W&&i.jsx(p4,{libraryFileId:W.id,title:W.print_name||W.filename,fileType:W.file_type,onClose:()=>X(null)}),D&&i.jsx(fJe,{type:D.type,currentName:D.name,onClose:()=>$(null),onSave:Be=>{D.type==="file"?be.mutate({id:D.id,filename:Be}):we.mutate({id:D.id,name:Be})},isLoading:be.isPending||we.isPending,t})]})}const Dj=5,vJe=2e3,wJe=3e4,SJe=5e3;function _Je(){const{t}=Rt(),e=tn(),{showToast:n}=cn(),{hasPermission:r}=Ir(),{printerId:a}=o0(),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),[T,C]=w.useState(!1),[j,P]=w.useState(0),[E,U]=w.useState(1),[O,B]=w.useState({x:0,y:0}),[D,$]=w.useState(!1),[G,z]=w.useState({x:0,y:0}),[W,X]=w.useState(null),[ae,H]=w.useState(null),K=w.useRef(null),ee=w.useRef(null),Z=w.useRef(null),ve=w.useRef(null),ce=w.useRef(null),{data:J}=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}),he=ot({mutationFn:xe=>ne.setChamberLight(s,xe),onMutate:async xe=>{await e.cancelQueries({queryKey:["printerStatus",s]});const Ne=e.getQueryData(["printerStatus",s]);return e.setQueryData(["printerStatus",s],be=>({...be,chamber_light:xe})),{previousStatus:Ne}},onSuccess:(xe,Ne)=>{n(`Chamber light ${Ne?"on":"off"}`)},onError:(xe,Ne,be)=>{be?.previousStatus&&e.setQueryData(["printerStatus",s],be.previousStatus),n(xe.message||t("printers.toast.failedToControlChamberLight"),"error")}}),oe=(je?.state==="RUNNING"||je?.state==="PAUSE")&&(je?.printable_objects_count??0)>=2;w.useEffect(()=>(J&&(document.title=`${J.name} - Camera`),()=>{document.title="Bambuddy"}),[J]);const _e=w.useRef(!1);w.useEffect(()=>{const xe=`/api/v1/printers/${s}/camera/stop`;_e.current=!1;const Ne=()=>{if(s>0&&!_e.current){_e.current=!0;const Ge={},ke=rd();ke&&(Ge.Authorization=`Bearer ${ke}`),fetch(xe,{method:"POST",keepalive:!0,headers:Ge}).catch(()=>{})}},be=()=>{Ne()};window.addEventListener("beforeunload",be);const we=K.current;return()=>{window.removeEventListener("beforeunload",be),we&&(we.src=""),Ne()}},[s]),w.useEffect(()=>{if(f&&!g){const Ne=setTimeout(()=>{p(!1)},o==="stream"?3e3:2e4);return()=>clearTimeout(Ne)}},[o,f,x,g]),w.useEffect(()=>{const xe=()=>{const Ne=!!document.fullscreenElement;N(Ne),U(1),B({x:0,y:0}),o==="stream"&&!g&&(K.current&&(K.current.src=""),setTimeout(()=>{p(!0),v(Date.now())},200))};return document.addEventListener("fullscreenchange",xe),()=>document.removeEventListener("fullscreenchange",xe)},[o,g]),w.useEffect(()=>{let xe;const Ne=()=>{clearTimeout(xe),xe=setTimeout(()=>{localStorage.setItem("cameraWindowState",JSON.stringify({width:window.outerWidth,height:window.outerHeight,left:window.screenX,top:window.screenY}))},500)};return window.addEventListener("resize",Ne),()=>{clearTimeout(xe),window.removeEventListener("resize",Ne)}},[]),w.useEffect(()=>()=>{Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),ce.current&&clearInterval(ce.current)},[]);const se=w.useCallback(()=>{if(k>=Dj){C(!1),h(!0);return}const xe=Math.min(vJe*Math.pow(2,k),wJe);C(!0),P(Math.ceil(xe/1e3)),ve.current=setInterval(()=>{P(Ne=>Ne<=1?(ve.current&&clearInterval(ve.current),0):Ne-1)},1e3),Z.current=setTimeout(()=>{A(Ne=>Ne+1),C(!1),p(!0),h(!1),K.current&&(K.current.src=""),v(Date.now())},xe)},[k]);w.useEffect(()=>{if(o!=="stream"||f||T||g){ce.current&&(clearInterval(ce.current),ce.current=null);return}return ce.current=setInterval(async()=>{try{const xe=await ne.getCameraStatus(s);(xe.stalled||!xe.active&&!d)&&(console.log(`Stream issue detected: stalled=${xe.stalled}, active=${xe.active}, reconnecting...`),ce.current&&(clearInterval(ce.current),ce.current=null),p(!1),se())}catch{}},SJe),()=>{ce.current&&(clearInterval(ce.current),ce.current=null)}},[o,f,d,T,g,s,se]);const ze=()=>{p(!1),o==="stream"&&k{if(p(!1),h(!1),A(0),C(!1),Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),K.current&&!localStorage.getItem("cameraWindowState")){const xe=K.current,Ne=xe.naturalWidth,be=xe.naturalHeight;if(Ne>0&&be>0){const ke=window.outerWidth-window.innerWidth,tt=window.outerHeight-window.innerHeight,De=Ne+16+ke,Ke=be+45+16+tt;try{window.resizeTo(De,Ke)}catch{}}}},Y=()=>{if(s>0){const xe={},Ne=rd();Ne&&(xe.Authorization=`Bearer ${Ne}`),fetch(`/api/v1/printers/${s}/camera/stop`,{method:"POST",headers:xe}).catch(()=>{})}},me=xe=>{o===xe||g||(y(!0),p(!0),h(!1),A(0),C(!1),U(1),B({x:0,y:0}),Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),K.current&&(K.current.src=""),o==="stream"&&Y(),setTimeout(()=>{l(xe),v(Date.now()),y(!1)},100))},Q=()=>{g||(y(!0),p(!0),h(!1),A(0),C(!1),Z.current&&clearTimeout(Z.current),ve.current&&clearInterval(ve.current),K.current&&(K.current.src=""),o==="stream"&&Y(),setTimeout(()=>{v(Date.now()),y(!1)},100))},ie=()=>{ee.current&&(document.fullscreenElement?document.exitFullscreen():ee.current.requestFullscreen())},ue=()=>{U(xe=>Math.min(xe+.5,4))},Oe=()=>{U(xe=>{const Ne=Math.max(xe-.5,1);return Ne===1&&B({x:0,y:0}),Ne})},Ce=xe=>{xe.preventDefault(),xe.deltaY<0?ue():Oe()},ge=xe=>{E>1&&(xe.preventDefault(),$(!0),z({x:xe.clientX-O.x,y:xe.clientY-O.y}))},L=w.useCallback(()=>{if(!ee.current)return{x:300,y:200};const xe=ee.current.getBoundingClientRect(),Ne=xe.width*(E-1)/2,be=xe.height*(E-1)/2;return{x:Math.max(50,Ne),y:Math.max(50,be)}},[E]),R=xe=>{if(D&&E>1){const Ne=xe.clientX-G.x,be=xe.clientY-G.y,we=L();B({x:Math.max(-we.x,Math.min(we.x,Ne)),y:Math.max(-we.y,Math.min(we.y,be))})}},q=()=>{$(!1)},le=xe=>{if(xe.length<2)return 0;const Ne=xe[0].clientX-xe[1].clientX,be=xe[0].clientY-xe[1].clientY;return Math.sqrt(Ne*Ne+be*be)},pe=xe=>xe.length<2?{x:xe[0].clientX,y:xe[0].clientY}:{x:(xe[0].clientX+xe[1].clientX)/2,y:(xe[0].clientY+xe[1].clientY)/2},te=xe=>{xe.touches.length===2?(xe.preventDefault(),X(le(xe.touches)),H(pe(xe.touches))):xe.touches.length===1&&E>1&&(xe.preventDefault(),$(!0),z({x:xe.touches[0].clientX-O.x,y:xe.touches[0].clientY-O.y}))},Ue=xe=>{if(xe.touches.length===2&&W!==null){xe.preventDefault();const Ne=le(xe.touches),be=Ne/W;U(Ge=>{const ke=Math.max(1,Math.min(4,Ge*be));return ke===1&&B({x:0,y:0}),ke}),X(Ne);const we=pe(xe.touches);if(ae){const Ge=L();B(ke=>({x:Math.max(-Ge.x,Math.min(Ge.x,ke.x+(we.x-ae.x))),y:Math.max(-Ge.y,Math.min(Ge.y,ke.y+(we.y-ae.y)))}))}H(we)}else if(xe.touches.length===1&&D&&E>1){xe.preventDefault();const Ne=xe.touches[0].clientX-G.x,be=xe.touches[0].clientY-G.y,we=L();B({x:Math.max(-we.x,Math.min(we.x,Ne)),y:Math.max(-we.y,Math.min(we.y,be))})}},Ie=xe=>{xe.touches.length<2&&(X(null),H(null)),xe.touches.length===0&&$(!1)},$e=()=>{U(1),B({x:0,y:0})},Fe=g?"":o==="stream"?`/api/v1/printers/${s}/camera/stream?fps=15&t=${x}`:`/api/v1/printers/${s}/camera/snapshot?t=${x}`,fe=f||g||T;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(cb,{className:"w-4 h-4"}),J?.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:()=>me("stream"),disabled:fe,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:()=>me("snapshot"),disabled:fe,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:()=>he.mutate(!je?.chamber_light),disabled:!je?.connected||he.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(oL,{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(dk,{className:"w-4 h-4 text-bambu-gray"})}),i.jsx("button",{onClick:Q,disabled:fe,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 ${fe?"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(xX,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(gfe,{className:"w-4 h-4 text-bambu-gray"})})]})]}),i.jsx("div",{className:"flex-1 flex items-center justify-center p-2 overflow-hidden",onWheel:Ce,onMouseMove:R,onMouseUp:q,onMouseLeave:q,onTouchStart:te,onTouchMove:Ue,onTouchEnd:Ie,style:{touchAction:"none"},children:i.jsxs("div",{className:"relative w-full h-full flex items-center justify-center",children:[(f||g)&&!T&&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")})]})}),T&&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(Ef,{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:Dj})}),i.jsx("button",{onClick:Q,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&&!T&&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(Mn,{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:Q,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:K,src:Fe,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?D?"grabbing":"grab":"default"},onError:Fe?ze:void 0,onLoad:Fe?V:void 0,onMouseDown:ge,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:Oe,disabled:E<=1,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomOut"),children:i.jsx(EF,{className:"w-4 h-4 text-white"})}),i.jsxs("button",{onClick:$e,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:ue,disabled:E>=4,className:"p-1.5 hover:bg-white/10 rounded disabled:opacity-30",title:t("camera.zoomIn"),children:i.jsx(PF,{className:"w-4 h-4 text-white"})})]})]})}),i.jsx(lL,{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 NJe(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 CJe(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 kJe(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 AJe(){const{printerId:t}=o0(),[e]=pF(),{t:n}=Rt(),r=tn(),a=parseInt(t||"0",10),[s,o]=w.useState(Date.now()),l=w.useMemo(()=>NJe(e),[e]),c=kJe(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:CJe(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(Wn,{className:c.icon}),i.jsxs("span",{className:`${c.text} text-white`,children:[n("streamOverlay.eta")," ",jF(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 MJe(){const{t}=Rt(),{id:e}=o0(),{mode:n}=ep(),{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(Mn,{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 iK(){const{id:t}=o0(),e=Al(),n=tn(),{t:r}=Rt(),{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")}}),T=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(W=>W.includes(z)?W.filter(X=>X!==z):[...W,z])},P=(z,W)=>{const X=z.permissions.map(ae=>ae.value);h(ae=>{const H=ae.filter(K=>!X.includes(K));return W?[...H,...X]:H})},E=z=>z.permissions.every(W=>d.includes(W.value)),U=z=>{const W=z.permissions.filter(X=>d.includes(X.value)).length;return W>0&&W{_&&h(_.all_permissions)},B=()=>{h([])},D=f.toLowerCase(),$=w.useMemo(()=>_?D?_.categories.map(z=>({...z,permissions:z.permissions.filter(W=>W.label.toLowerCase().includes(D))})).filter(z=>z.permissions.length>0):_.categories:[],[_,D]),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(cX,{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(Mn,{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(Pe,{size:"sm",variant:"ghost",onClick:O,children:r("groups.editor.selectAll")}),i.jsx(Pe,{size:"sm",variant:"ghost",onClick:B,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"})]})]}),$.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:$.map(z=>{const W=_.categories.find(ee=>ee.name===z.name),X=W.permissions.filter(ee=>d.includes(ee.value)).length,ae=W.permissions.length,H=E(W),K=U(W);return i.jsxs(wt,{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(W,!H),className:`w-5 h-5 rounded border flex items-center justify-center transition-colors shrink-0 ${H?"bg-bambu-green border-bambu-green":K?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:[H&&i.jsx(aa,{className:"w-3 h-3 text-white"}),K&&!H&&i.jsx(w1,{className:"w-3 h-3 text-white"})]}),i.jsx(o3,{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:[X,"/",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(Pe,{variant:"secondary",onClick:()=>e("/settings?tab=users"),children:r("common.cancel")}),i.jsx(Pe,{onClick:C,disabled:T||!o.trim(),children:T?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 sK={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 TJe(t,e=!1){const n={};return e?(t.material||(n.material="Material is required"),{isValid:Object.keys(n).length===0,errors:n}):(t.slicer_filament||(n.slicer_filament="Slicer preset is required"),t.material||(n.material="Material is required"),t.brand||(n.brand="Brand is required"),t.subtype||(n.subtype="Subtype is required"),{isValid:Object.keys(n).length===0,errors:n})}const PJe=["PLA","PETG","ABS","TPU","ASA","PC","PA","PVA","HIPS","PA-CF","PETG-CF","PLA-CF"],EJe=["Bambu","PolyLite","PolyTerra","eSUN","Overture","Fiberon","SUNLU","Inland","Hatchbox","Generic"],uv=["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"],Zie=[{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"}],jJe=[{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"}],oK=[...Zie,...jJe],Jie="bambuddy-recent-colors",DJe=8,RJe=[{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 Ob(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 uv)if(o.toLowerCase().includes(c.toLowerCase())){l=c;break}if(!l&&s)for(const c of uv){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 FJe(t,e){const n=new Set(EJe);for(const r of t){const{brand:a}=Ob(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}=Ob(r.name);a&&a.length>1&&n.add(a)}return Array.from(n).sort((r,a)=>r.localeCompare(a))}function LJe(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 OJe(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=LJe(n);if(r.length>0)return r}return RJe}function IJe(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 zJe(){try{const t=localStorage.getItem(Jie);if(t)return JSON.parse(t)}catch{}return[]}function UJe(t,e){const n=e.filter(a=>a.hex.toUpperCase()!==t.hex.toUpperCase()),r=[t,...n].slice(0,DJe);try{localStorage.setItem(Jie,JSON.stringify(r))}catch{}return r}function Rj(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=Ob(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 BJe({formData:t,updateField:e,cloudAuthenticated:n,loadingCloudPresets:r,presetInputValue:a,setPresetInputValue:s,selectedPresetOption:o,filamentOptions:l,availableBrands:c,availableMaterials:u,quickAdd:d,quantity:h,onQuantityChange:f,errors:p}){const{t:x}=Rt(),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(!1),[A,T]=w.useState(!1),[C,j]=w.useState(""),[P,E]=w.useState(""),[U,O]=w.useState(""),[B,D]=w.useState(String(t.label_weight)),[$,G]=w.useState(!1),z=w.useRef(null),W=w.useRef(null),X=w.useRef(null),ae=w.useRef(null);w.useEffect(()=>{const ce=J=>{z.current&&!z.current.contains(J.target)&&g(!1),ae.current&&!ae.current.contains(J.target)&&T(!1),W.current&&!W.current.contains(J.target)&&_(!1),X.current&&!X.current.contains(J.target)&&k(!1)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[]);const H=w.useMemo(()=>{if(!a)return l;const ce=a.toLowerCase();return l.filter(J=>J.displayName.toLowerCase().includes(ce)||J.code.toLowerCase().includes(ce))},[l,a]),K=w.useMemo(()=>{if(!C)return c;const ce=C.toLowerCase();return c.filter(je=>je.toLowerCase().includes(ce)).sort((je,he)=>{const oe=je.toLowerCase()===ce,_e=he.toLowerCase()===ce;return oe&&!_e?-1:!oe&&_e?1:je.localeCompare(he)})},[c,C]),ee=w.useMemo(()=>{if(!P)return uv;const ce=P.toLowerCase();return uv.filter(J=>J.toLowerCase().includes(ce))},[P]),Z=w.useMemo(()=>{if(!U)return u;const ce=U.toLowerCase();return u.filter(je=>je.toLowerCase().includes(ce)).sort((je,he)=>{const oe=je.toLowerCase()===ce,_e=he.toLowerCase()===ce;return oe&&!_e?-1:!oe&&_e?1:je.localeCompare(he)})},[U,u]);w.useEffect(()=>{$||D(String(t.label_weight))},[t.label_weight,$]);const ve=ce=>{e("slicer_filament",ce.code),s(ce.displayName),g(!1);const J=Ob(ce.name);J.material&&e("material",J.material),J.brand&&e("brand",J.brand),J.variant&&e("subtype",J.variant)};return i.jsxs("div",{className:"space-y-4",children:[!d&&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"})," ",x("inventory.loadingPresets")]}):n?i.jsxs(i.Fragment,{children:[i.jsx(Hb,{className:"w-3 h-3 text-bambu-green"})," ",x("inventory.cloudConnected")]}):i.jsxs(i.Fragment,{children:[i.jsx(Mhe,{className:"w-3 h-3"})," ",x("inventory.cloudNotConnected")]})}),!d&&i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.slicerPreset")," *"]}),i.jsxs("div",{className:"relative",ref:z,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:x("inventory.searchPresets"),value:a,onChange:ce=>{s(ce.target.value),g(!0)},onFocus:()=>{g(!0),s("")}}),v&&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:H.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noPresetsFound")}):H.map(ce=>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===ce.code?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>ve(ce),children:[i.jsx("span",{className:"truncate",children:ce.displayName}),i.jsx("span",{className:"font-mono text-xs text-bambu-gray ml-2 shrink-0",children:ce.code})]},ce.code))})]}),o&&i.jsxs("div",{className:"mt-1 text-xs text-bambu-gray",children:[x("inventory.selectedPreset"),": ",i.jsx("span",{className:"font-mono text-bambu-green",children:o.code})]}),p?.slicer_filament&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.slicer_filament})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.material")," *"]}),i.jsxs("div",{className:"relative",ref:ae,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:x("inventory.selectMaterial"),value:A?U:t.material,onChange:ce=>{O(ce.target.value),T(!0)},onFocus:()=>{T(!0),O("")}}),i.jsx(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),A&&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:[Z.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):Z.map(ce=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.material===ce?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("material",ce),T(!1),O("")},children:ce},ce)),U&&!Z.includes(U)&&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",U),T(!1),O("")},children:x("inventory.useCustomMaterial",{material:U})})]})]}),p?.material&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.material})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.brand"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:W,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:x("inventory.searchBrand"),value:y?C:t.brand,onChange:ce=>{j(ce.target.value),_(!0)},onFocus:()=>{_(!0),j("")}}),i.jsx(Pn,{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:[K.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):K.map(ce=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.brand===ce?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("brand",ce),_(!1),j("")},children:ce},ce)),C&&!K.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("brand",C),_(!1),j("")},children:x("inventory.useCustomBrand",{brand:C})})]})]}),p?.brand&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.brand})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:[x("inventory.subtype"),!d&&" *"]}),i.jsxs("div",{className:"relative",ref:X,children:[i.jsx("input",{type:"text",value:N?P:t.subtype,onChange:ce=>{E(ce.target.value),k(!0)},onFocus:()=>{k(!0),E("")},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(Pn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray/50 pointer-events-none"}),N&&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:[ee.length===0?i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:x("inventory.noResults")}):ee.map(ce=>i.jsx("button",{type:"button",className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${t.subtype===ce?"bg-bambu-green/10 text-bambu-green":"text-white"}`,onClick:()=>{e("subtype",ce),k(!1),E("")},children:ce},ce)),P&&!uv.some(ce=>ce.toLowerCase()===P.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",P),k(!1),E("")},children:x("inventory.useCustomBrand",{brand:P})})]})]}),p?.subtype&&i.jsx("p",{className:"mt-1 text-xs text-red-400",children:p.subtype})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:x("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:B,min:0,onFocus:()=>G(!0),onChange:ce=>D(ce.target.value),onBlur:()=>{G(!1);const ce=B.trim(),J=Number(ce);if(!ce||!Number.isFinite(J)||J<0){D(String(t.label_weight));return}const je=Math.round(J);e("label_weight",je),D(String(je))}}),i.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-bambu-gray",children:"g"})]})]}),d&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:x("inventory.quantity")}),i.jsx("input",{type:"number",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:outline-none focus:border-bambu-green",value:h,min:1,max:100,onChange:ce=>{const J=Math.max(1,Math.min(100,parseInt(ce.target.value)||1));f(J)}})]})]})}function HJe({formData:t,updateField:e,recentColors:n,onColorUsed:r,catalogColors:a}){const{t:s}=Rt(),[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 T=_&&N?`${_} ${N}`:"";if(T){const C=a.filter(P=>A(P.manufacturer)&&P.material?.toLowerCase()===T);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=T.replace(/\+$/,"");if(j!==T){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?oK.filter(y=>y.name.toLowerCase().includes(c.toLowerCase())):o?oK:Zie,[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(Wn,{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(Pn,{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 $Je({catalog:t,value:e,onChange:n,catalogId:r,onCatalogIdChange:a}){const{t:s}=Rt(),[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(Zfe,{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 VJe({formData:t,updateField:e,spoolCatalog:n,currencySymbol:r}){const{t:a}=Rt(),{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($Je,{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 qJe({formData:t,printersWithCalibrations:e,selectedProfiles:n,setSelectedProfiles:r,expandedPrinters:a,setExpandedPrinters:s}){const{t:o}=Rt(),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=>Rj(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,T)=>T.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=>Rj(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(db,{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=>Rj(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(Pn,{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 GJe(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 WJe={completed:"text-bambu-green",failed:"text-red-400",aborted:"text-yellow-400"};function KJe({spoolId:t}){const{t:e}=Rt(),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(Wn,{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(Pe,{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:GJe(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:WJe[l.status]||"text-bambu-gray",children:l.status})]})]},l.id))})]})}function XJe({isOpen:t,onClose:e,spool:n,printersWithCalibrations:r=[],currencySymbol:a}){const{t:s}=Rt(),o=tn(),{showToast:l}=cn(),c=!!n,[u,d]=w.useState(sK),[h,f]=w.useState({}),[p,x]=w.useState("filament"),[v,g]=w.useState(!1),[y,_]=w.useState(!1),[N,k]=w.useState(1),[A,T]=w.useState(!1),[C,j]=w.useState(!1),[P,E]=w.useState([]),[U,O]=w.useState(""),[B,D]=w.useState([]),[$,G]=w.useState([]),[z,W]=w.useState([]),[X,ae]=w.useState([]),[H,K]=w.useState([]),[ee,Z]=w.useState(new Set),[ve,ce]=w.useState(new Set),J=r.length>0?r:H,je=w.useMemo(()=>ee.size,[ee]);w.useEffect(()=>{ae(zJe())},[]),w.useEffect(()=>{t&&((async()=>{j(!0);try{const pe=await ne.getCloudStatus();if(T(pe.is_authenticated),pe.is_authenticated){const te=await ne.getFilamentPresets();E(te)}}catch(pe){console.error("Failed to fetch cloud presets:",pe),T(!1)}finally{j(!1)}})(),ne.getSpoolCatalog().then(D).catch(console.error),ne.getColorCatalog().then(W).catch(console.error),ne.getLocalPresets().then(pe=>G(pe.filament)).catch(console.error),r.length===0&&(async()=>{try{const pe=await ne.getPrinters(),te=await Promise.all(pe.map(Ie=>ne.getPrinterStatus(Ie.id).catch(()=>null))),Ue=[];for(let Ie=0;Ie({cali_idx:be.slot_id,filament_id:be.filament_id,setting_id:be.setting_id||"",name:be.name,k_value:parseFloat(be.k_value)||0,n_coef:parseFloat(be.n_coef)||0,extruder_id:be.extruder_id,nozzle_diameter:be.nozzle_diameter}))}catch{}Ue.push({printer:{...$e,connected:fe},calibrations:xe})}K(Ue)}catch(pe){console.error("Failed to fetch printer calibrations:",pe)}})())},[t,r.length]);const he=w.useMemo(()=>OJe(P,new Set,$),[P,$]),oe=w.useMemo(()=>{const le=FJe(P,$),pe=z.map(Ue=>Ue.manufacturer?.trim()).filter(Ue=>!!Ue),te=new Set([...le,...pe]);return Array.from(te).sort((Ue,Ie)=>Ue.localeCompare(Ie))},[P,$,z]),_e=w.useMemo(()=>{const le=z.map(te=>te.material?.trim()).filter(te=>!!te),pe=new Set([...PJe,...le]);return Array.from(pe).sort((te,Ue)=>te.localeCompare(Ue))},[z]),se=w.useMemo(()=>{const le=[];for(const pe of z){const te=pe.manufacturer?.trim(),Ue=pe.material?.trim();te&&Ue&&le.push({brand:te,material:Ue})}for(const pe of P){const te=Ob(pe.name);te.brand&&te.material&&le.push({brand:te.brand,material:te.material})}for(const pe of $){const te=Ob(pe.name),Ue=pe.filament_vendor?.trim()||te.brand,Ie=te.material;Ue&&Ie&&le.push({brand:Ue,material:Ie})}return le},[P,z,$]),ze=w.useMemo(()=>{const le=new Map;for(const pe of se){const te=pe.brand.toLowerCase(),Ue=pe.material.toLowerCase();le.has(te)||le.set(te,new Set),le.get(te).add(Ue)}return le},[se]),V=w.useMemo(()=>{const le=new Map;for(const pe of se){const te=pe.brand.toLowerCase(),Ue=pe.material.toLowerCase();le.has(Ue)||le.set(Ue,new Set),le.get(Ue).add(te)}return le},[se]),Y=w.useMemo(()=>{if(!u.material)return oe;const le=u.material.toLowerCase(),pe=V.get(le);return!pe||pe.size===0?oe:oe.filter(te=>pe.has(te.toLowerCase()))},[oe,u.material,V]),me=w.useMemo(()=>{if(!u.brand)return _e;const le=u.brand.toLowerCase(),pe=ze.get(le);return!pe||pe.size===0?_e:_e.filter(te=>pe.has(te.toLowerCase()))},[_e,u.brand,ze]),Q=w.useMemo(()=>IJe(u.slicer_filament,he),[u.slicer_filament,he]);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}),O(n.slicer_filament_name||n.slicer_filament||""),n.k_profiles&&n.k_profiles.length>0){const le=new Set;for(const pe of n.k_profiles)pe.cali_idx!==null&&pe.cali_idx!==void 0&&le.add(`${pe.printer_id}:${pe.cali_idx}:${pe.extruder??"null"}`);Z(le)}else Z(new Set);else d(sK),O(""),Z(new Set),_(!1),k(1);f({}),x("filament"),g(!1)}},[t,n]),w.useEffect(()=>{t&&J.length>0&&ce(new Set(J.map(le=>String(le.printer.id))))},[t,J]);const ie=(le,pe)=>{d(te=>({...te,[le]:pe})),le==="weight_used"&&g(!0),h[le]&&f(te=>({...te,[le]:void 0}))},ue=le=>{ae(pe=>UJe(le,pe))},Oe=ot({mutationFn:le=>ne.createSpool(le),onSuccess:async le=>{ee.size>0&&le?.id&&await L(le.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolCreated"),"success"),e()},onError:le=>{l(le.message,"error")}}),Ce=ot({mutationFn:({data:le,qty:pe})=>ne.bulkCreateSpools(le,pe),onSuccess:async le=>{if(ee.size>0)for(const pe of le)await L(pe.id);await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolsCreated",{count:le.length}),"success"),e()},onError:le=>{l(le.message,"error")}}),ge=ot({mutationFn:le=>ne.updateSpool(n.id,le),onSuccess:async()=>{n?.id&&await L(n.id),await o.invalidateQueries({queryKey:["inventory-spools"]}),l(s("inventory.spoolUpdated"),"success"),e()},onError:le=>{l(le.message,"error")}}),L=async le=>{if(ee.size===0){try{await ne.saveSpoolKProfiles(le,[])}catch{}return}const pe=[];for(const te of ee){const[Ue,Ie,$e]=te.split(":"),Fe=parseInt(Ue),fe=parseInt(Ie),xe=$e==="null"?0:parseInt($e),Ne=J.find(be=>be.printer.id===Fe);if(Ne){const be=Ne.calibrations.find(we=>we.cali_idx===fe);be&&pe.push({printer_id:Fe,extruder:xe,nozzle_diameter:be.nozzle_diameter||"0.4",k_value:be.k_value,name:be.name||null,cali_idx:be.cali_idx,setting_id:be.setting_id||null})}}if(pe.length>0)try{await ne.saveSpoolKProfiles(le,pe)}catch(te){console.error("Failed to save K-profiles:",te)}};if(w.useEffect(()=>{if(!t)return;const le=pe=>{pe.key==="Escape"&&e()};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[t,e]),!t)return null;const R=()=>{const le=TJe(u,y);if(!le.isValid){f(le.errors),(le.errors.slicer_filament||le.errors.material||le.errors.brand||le.errors.subtype)&&x("filament");return}const pe=Q?.displayName||U||null,te={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:pe,nozzle_temp_min:null,nozzle_temp_max:null,note:u.note||null,cost_per_kg:u.cost_per_kg};(!c||v)&&(te.weight_used=u.weight_used),c?ge.mutate(te):N>1?Ce.mutate({data:te,qty:N}):Oe.mutate(te)},q=Oe.isPending||Ce.isPending||ge.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(Ot,{className:"w-5 h-5"})})]}),!c&&i.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-bambu-dark-tertiary flex-shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(nd,{className:"w-4 h-4 text-amber-400"}),i.jsx("span",{className:"text-sm text-white",children:s("inventory.quickAdd")})]}),i.jsx("button",{type:"button",onClick:()=>{_(!y),y||x("filament")},className:`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${y?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:i.jsx("span",{className:`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${y?"translate-x-4":"translate-x-0.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(WC,{className:"w-4 h-4"}),s("inventory.filamentInfoTab")]}),!y&&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(Ude,{className:"w-4 h-4"}),s("inventory.paProfileTab"),je>0&&i.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded-full bg-bambu-green/20 text-bambu-green",children:je})]})]}),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(BJe,{formData:u,updateField:ie,cloudAuthenticated:A,loadingCloudPresets:C,presetInputValue:U,setPresetInputValue:O,selectedPresetOption:Q,filamentOptions:he,availableBrands:Y,availableMaterials:me,quickAdd:y,quantity:N,onQuantityChange:k,errors:h})]}),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(HJe,{formData:u,updateField:ie,recentColors:X,onColorUsed:ue,catalogColors:z})]}),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(VJe,{formData:u,updateField:ie,spoolCatalog:B,currencySymbol:a})]}),c&&n&&i.jsx("div",{children:i.jsx(KJe,{spoolId:n.id})})]}):i.jsx(qJe,{formData:u,updateField:ie,printersWithCalibrations:J,selectedProfiles:ee,setSelectedProfiles:Z,expandedPrinters:ve,setExpandedPrinters:ce})}),i.jsxs("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary flex-shrink-0",children:[i.jsx(Pe,{variant:"secondary",onClick:e,children:s("common.cancel")}),i.jsx(Pe,{onClick:R,disabled:q,children:q?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 YJe({isOpen:t,onClose:e,columns:n,defaultColumns:r,onSave:a}){const{t:s}=Rt(),[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((T,C)=>C===k?{...T,visible:!T.visible}:T))},f=(k,A)=>{A<0||A>=o.length||l(T=>{const C=[...T],[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 T=d.current;T!==null&&T!==A&&(f(T,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(wt,{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:T=>p(T,A),onDragOver:T=>x(T,A),onDrop:v,onDragEnd:g,children:[i.jsx("div",{className:"cursor-grab text-bambu-gray/50 hover:text-bambu-gray",children:i.jsx(Eh,{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(Pn,{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(Zl,{className:"w-4 h-4"}):i.jsx(c0,{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(Pe,{variant:"secondary",onClick:y,className:"mr-auto",children:[i.jsx(so,{className:"w-4 h-4"}),s("inventory.reset")]}),i.jsx(Pe,{variant:"secondary",onClick:e,children:s("inventory.cancel")}),i.jsx(Pe,{onClick:_,children:s("inventory.applyChanges")})]})]})})})}function lK(t){return`${t.material}|${t.subtype||""}|${t.brand||""}|${t.color_name||""}|${t.rgba||""}|${t.label_weight}`}const ese="bambuddy-inventory-columns",d1=[{id:"id",label:"#",visible:!0},{id:"added_time",label:"Added",visible:!0},{id:"encode_time",label:"Encoded",visible:!1},{id:"last_used_time",label:"Last Used",visible:!1},{id:"rgba",label:"Color",visible:!0},{id:"material",label:"Material",visible:!0},{id:"subtype",label:"Subtype",visible:!0},{id:"color_name",label:"Color Name",visible:!1},{id:"brand",label:"Brand",visible:!0},{id:"slicer_filament",label:"Slicer Filament",visible:!1},{id:"location",label:"Location",visible:!0},{id:"label_weight",label:"Label",visible:!0},{id:"net",label:"Net",visible:!0},{id:"gross",label:"Gross",visible:!1},{id:"added_full",label:"Full",visible:!1},{id:"used",label:"Used",visible:!1},{id:"printed_total",label:"Printed Total",visible:!1},{id:"printed_since_weight",label:"Printed Since Weight",visible:!1},{id:"note",label:"Note",visible:!1},{id:"pa_k",label:"PA(K)",visible:!0},{id:"tag_id",label:"Tag ID",visible:!1},{id:"data_origin",label:"Data Origin",visible:!1},{id:"tag_type",label:"Linked Tag Type",visible:!1},{id:"stock",label:"Stock",visible:!1},{id:"remaining",label:"Remaining",visible:!0},{id:"cost_per_kg",label:"Cost/kg",visible:!1}];function QJe(){try{const t=localStorage.getItem(ese);if(t){const e=JSON.parse(t),n=new Set(d1.map(o=>o.id)),r=new Set(e.map(o=>o.id)),a=e.filter(o=>n.has(o.id)),s=d1.filter(o=>!r.has(o.id));return[...a,...s]}}catch{}return d1.map(t=>({...t}))}function ZJe(t){try{localStorage.setItem(ese,JSON.stringify(t))}catch{}}function Pc(t,e=!1){return e&&t>=1e3?`${(t/1e3).toFixed(1)}kg`:`${Math.round(t)}g`}const JJe={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 Fj(t,e="system"){if(!t)return"-";const n=di(t);return n?c3(n,e):"-"}const eet={id:()=>"#",added_time:()=>"Added",encode_time:()=>"Encoded",last_used_time:()=>"Last Used",rgba:t=>t("inventory.color"),material:t=>t("inventory.material"),subtype:t=>t("inventory.subtype"),color_name:t=>t("inventory.colorName"),brand:t=>t("inventory.brand"),slicer_filament:t=>t("inventory.slicerFilament"),location:()=>"Location",label_weight:t=>t("inventory.labelWeight"),net:t=>t("inventory.net"),gross:()=>"Gross",added_full:()=>"Full",used:t=>t("inventory.weightUsed"),printed_total:()=>"Printed Total",printed_since_weight:()=>"Printed Since Weight",note:t=>t("inventory.note"),pa_k:()=>"PA(K)",tag_id:()=>"Tag ID",data_origin:()=>"Data Origin",tag_type:()=>"Linked Tag Type",stock:t=>t("inventory.stock"),remaining:t=>t("inventory.remaining"),cost_per_kg:t=>t("inventory.costPerKg")},aF={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:Fj(t.created_at,e)}),encode_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:Fj(t.encode_time,e)}),last_used_time:({spool:t,dateFormat:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:t.last_used?Fj(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:g4(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=h4(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:Pc(t.label_weight)}),net:({remaining:t})=>i.jsx("span",{className:"text-sm text-white",children:Pc(t)}),gross:({spool:t,remaining:e})=>i.jsx("span",{className:"text-sm text-bambu-gray",children:Pc(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?Pc(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||"-"}),stock:({spool:t,t:e})=>t.slicer_filament?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-amber-500/20 text-amber-400",children:e("inventory.stock")}),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)}`:"-"})},Lj={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||""} ${h4(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(),stock:t=>t.slicer_filament?1:0,cost_per_kg:t=>t.cost_per_kg??0},iF="bambuddy-inventory-sort";function tet(){try{const t=localStorage.getItem(iF);if(t)return JSON.parse(t)}catch{}return null}function net(t){try{t?localStorage.setItem(iF,JSON.stringify(t)):localStorage.removeItem(iF)}catch{}}function ret(){const{data:t}=Je({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings,staleTime:3e5});return t?.spoolman_enabled==="true"&&t?.spoolman_url?i.jsx("iframe",{src:t.spoolman_url,className:"h-full w-full border-0",title:"Spoolman",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}):i.jsx(aet,{})}function aet(){const{t}=Rt(),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("all"),[y,_]=w.useState(""),[N,k]=w.useState("table"),[A,T]=w.useState(tet),[C,j]=w.useState(QJe),[P,E]=w.useState(!1),[U,O]=w.useState(()=>{try{return localStorage.getItem("bambuddy-inventory-group")==="true"}catch{return!1}}),[B,D]=w.useState(new Set),[$,G]=w.useState(0),[z,W]=w.useState(()=>{try{const Fe=localStorage.getItem("bambuddy-inventory-pageSize");if(Fe){const fe=Number(Fe);if([15,30,50,100,-1].includes(fe))return fe}}catch{}return 15}),{data:X}=Je({queryKey:["settings"],queryFn:ne.getSettings}),ae=X?.date_format||"system",{data:H,isLoading:K}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!0),refetchInterval:3e4}),{data:ee}=Je({queryKey:["spool-assignments"],queryFn:()=>ne.getAssignments(),refetchInterval:3e4}),Z=ot({mutationFn:Fe=>ne.deleteSpool(Fe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolDeleted"),"success")}}),ve=ot({mutationFn:Fe=>ne.archiveSpool(Fe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolArchived"),"success")}}),ce=ot({mutationFn:Fe=>ne.restoreSpool(Fe),onSuccess:()=>{e.invalidateQueries({queryKey:["inventory-spools"]}),n(t("inventory.spoolRestored"),"success")}}),J=w.useMemo(()=>{if(!H)return null;let Fe=0,fe=0,xe=0,Ne=0;const be={};for(const we of H){if(we.archived_at)continue;Ne++;const Ge=Math.max(0,we.label_weight-we.weight_used);Fe+=Ge,fe+=we.weight_used,(we.label_weight>0?Ge/we.label_weight*100:0)<20&&xe++;const tt=we.material||"Unknown";be[tt]||(be[tt]={count:0,weight:0}),be[tt].count++,be[tt].weight+=Ge}return{totalWeight:Fe,totalConsumed:fe,lowStock:xe,byMaterial:be,totalSpools:Ne}},[H]),je=ee?.length??0,he=rl(X?.currency||"USD"),oe=w.useMemo(()=>{const Fe={};for(const fe of ee||[])Fe[fe.spool_id]=fe;return Fe},[ee]),_e=w.useMemo(()=>J?Object.entries(J.byMaterial).sort((Fe,fe)=>fe[1].weight-Fe[1].weight).slice(0,4):[],[J]),se=w.useMemo(()=>{let Fe=H||[];if(l==="active"?Fe=Fe.filter(fe=>!fe.archived_at):Fe=Fe.filter(fe=>!!fe.archived_at),u==="used"?Fe=Fe.filter(fe=>fe.weight_used>0):u==="new"&&(Fe=Fe.filter(fe=>fe.weight_used===0)),h&&(Fe=Fe.filter(fe=>fe.material===h)),p&&(Fe=Fe.filter(fe=>fe.brand===p)),v==="stock"?Fe=Fe.filter(fe=>!fe.slicer_filament):v==="configured"&&(Fe=Fe.filter(fe=>!!fe.slicer_filament)),y){const fe=y.toLowerCase();Fe=Fe.filter(xe=>xe.brand?.toLowerCase().includes(fe)||xe.material.toLowerCase().includes(fe)||xe.color_name?.toLowerCase().includes(fe)||xe.subtype?.toLowerCase().includes(fe)||xe.note?.toLowerCase().includes(fe)||xe.slicer_filament_name?.toLowerCase().includes(fe))}return Fe},[H,l,u,h,p,v,y]),ze=()=>G(0),V=[...new Set(H?.map(Fe=>Fe.material)||[])].sort(),Y=[...new Set(H?.map(Fe=>Fe.brand).filter(Boolean)||[])].sort(),me=l!=="active"||u!=="all"||!!h||!!p||v!=="all"||!!y,Q=Fe=>{j(Fe),ZJe(Fe)},ie=w.useMemo(()=>C.filter(Fe=>Fe.visible).map(Fe=>Fe.id),[C]),ue=Fe=>{Lj[Fe]&&(T(fe=>{let xe;return fe?.column===Fe?xe=fe.direction==="asc"?{column:Fe,direction:"desc"}:null:xe={column:Fe,direction:"asc"},net(xe),xe}),ze())},Oe=w.useMemo(()=>{if(!A)return se;const Fe=Lj[A.column];return Fe?[...se].sort((xe,Ne)=>{const be=Fe(xe,oe),we=Fe(Ne,oe);return bewe?A.direction==="asc"?1:-1:0}):se},[se,A,oe]),Ce=w.useMemo(()=>{if(!U)return Oe.map(Ne=>({type:"single",spool:Ne}));const Fe=new Map;for(const Ne of Oe)if(!(Ne.weight_used>0||oe[Ne.id])){const be=lK(Ne),we=Fe.get(be);we?we.push(Ne):Fe.set(be,[Ne])}const fe=[],xe=new Set;for(const Ne of Oe){if(Ne.weight_used>0||oe[Ne.id]){fe.push({type:"single",spool:Ne});continue}const be=lK(Ne);if(xe.has(be))continue;xe.add(be);const we=Fe.get(be);we.length===1?fe.push({type:"single",spool:we[0]}):fe.push({type:"group",key:be,spools:we,representative:we[0]})}return fe},[Oe,U,oe]),ge=z===-1,L=Ce.length,R=ge?L||1:z,q=Math.max(1,Math.ceil(L/R)),le=ge?0:Math.min($,q-1),pe=ge?Ce:Ce.slice(le*R,(le+1)*R),te=()=>{const Fe=!U;O(Fe),D(new Set),ze();try{localStorage.setItem("bambuddy-inventory-group",String(Fe))}catch{}},Ue=Fe=>{D(fe=>{const xe=new Set(fe);return xe.has(Fe)?xe.delete(Fe):xe.add(Fe),xe})},Ie=Fe=>{W(Fe),G(0);try{localStorage.setItem("bambuddy-inventory-pageSize",String(Fe))}catch{}},$e=()=>{c("active"),d("all"),f(""),x(""),g("all"),_(""),ze()};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(Pe,{onClick:()=>a({spool:null}),children:[i.jsx(Yn,{className:"w-4 h-4"}),t("inventory.addSpool")]})]}),J&&!K&&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:Pc(J.totalWeight,!0)}),i.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[J.totalSpools," ",J.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(MF,{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:Pc(J.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:_e.map(([Fe,fe])=>i.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${JJe[Fe]||"bg-bambu-dark-tertiary text-bambu-gray"}`,children:[Fe," ",i.jsx("span",{className:"opacity-70",children:Pc(fe.weight,!0)})]},Fe))})]}),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:je}),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(Mn,{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 ${J.lowStock>0?"text-yellow-400":"text-white"}`,children:J.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:y,onChange:Fe=>{_(Fe.target.value),ze()},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"}),y&&i.jsx("button",{onClick:()=>{_(""),ze()},className:"absolute right-3 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:i.jsx(Ot,{className:"w-4 h-4"})})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[N==="table"&&i.jsxs("button",{onClick:()=>E(!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(Uhe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.columns")})]}),i.jsxs("button",{onClick:te,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium border rounded-lg transition-colors ${U?"bg-bambu-green/20 text-bambu-green border-bambu-green/30":"text-bambu-gray border-bambu-dark-tertiary hover:bg-bambu-dark-tertiary"}`,title:t("inventory.groupSimilar"),children:[i.jsx(Rme,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.groupSimilar")})]}),i.jsxs("div",{className:"flex bg-bambu-dark-primary border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[i.jsxs("button",{onClick:()=>k("table"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${N==="table"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(kpe,{className:"w-4 h-4"}),i.jsx("span",{className:"hidden sm:inline",children:t("inventory.table")})]}),i.jsxs("button",{onClick:()=>k("cards"),className:`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${N==="cards"?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:[i.jsx(d0,{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"),ze()},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"),ze()},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"),ze()},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"),ze()},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(Wn,{className:"w-3.5 h-3.5"}),t("inventory.used")]}),i.jsx("button",{onClick:()=>{d("new"),ze()},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.jsxs("div",{className:"flex items-center rounded-lg border border-bambu-dark-tertiary overflow-hidden",children:[i.jsx("button",{onClick:()=>{g("all"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${v==="all"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.all")}),i.jsx("button",{onClick:()=>{g("stock"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${v==="stock"?"bg-amber-500/20 text-amber-400":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.stock")}),i.jsx("button",{onClick:()=>{g("configured"),ze()},className:`px-3 py-1.5 text-xs font-medium transition-colors ${v==="configured"?"bg-bambu-green/20 text-bambu-green":"text-bambu-gray hover:bg-bambu-dark-tertiary"}`,children:t("inventory.configured")})]}),i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("select",{value:h,onChange:Fe=>{f(Fe.target.value),ze()},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")}),V.map(Fe=>i.jsx("option",{value:Fe,children:Fe},Fe))]}),i.jsxs("select",{value:p,onChange:Fe=>{x(Fe.target.value),ze()},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")}),Y.map(Fe=>i.jsx("option",{value:Fe,children:Fe},Fe))]}),me&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"w-px h-5 bg-bambu-dark-tertiary"}),i.jsxs("button",{onClick:$e,className:"flex items-center gap-1 text-xs text-bambu-gray hover:text-bambu-green transition-colors",children:[i.jsx(Ot,{className:"w-3.5 h-3.5"}),t("inventory.clearFilters")]})]}),i.jsxs("span",{className:"ml-auto text-xs text-bambu-gray",children:[Oe.length," ",Oe.length!==1?t("inventory.spools"):t("inventory.spool"),U&&L0?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:pe.map(Fe=>{if(Fe.type==="group"){const{key:we,spools:Ge,representative:ke}=Fe,tt=ke.rgba?`#${ke.rgba.substring(0,6)}`:"#808080",De=B.has(we);return i.jsxs("div",{className:"col-span-full",children:[i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg overflow-hidden border border-bambu-green/30 hover:border-bambu-green transition-colors cursor-pointer",onClick:()=>Ue(we),children:[i.jsx("div",{className:"h-10 flex items-center px-4 gap-3",style:{backgroundColor:tt},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:g4(ke.color_name,ke.rgba)||"-"})}),i.jsxs("div",{className:"px-4 py-3 flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx(Pn,{className:`w-4 h-4 text-bambu-gray transition-transform ${De?"":"-rotate-90"}`}),i.jsxs("div",{children:[i.jsxs("h3",{className:"font-semibold text-white",children:[ke.material,ke.subtype?` ${ke.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:ke.brand||"-"})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-sm text-bambu-gray",children:Pc(ke.label_weight)}),i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:t("inventory.groupedSpools",{count:Ge.length})})]})]})]}),De&&i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mt-2 ml-4",children:Ge.map(Ke=>{const Ae=Math.max(0,Ke.label_weight-Ke.weight_used),Re=Ke.label_weight>0?Ae/Ke.label_weight*100:0,Ve=Ke.rgba?`#${Ke.rgba.substring(0,6)}`:"#808080";return i.jsx(cK,{spool:Ke,remaining:Ae,pct:Re,colorStyle:Ve,onClick:()=>a({spool:Ke}),t},Ke.id)})})]},`group-${we}`)}const fe=Fe.spool,xe=Math.max(0,fe.label_weight-fe.weight_used),Ne=fe.label_weight>0?xe/fe.label_weight*100:0,be=fe.rgba?`#${fe.rgba.substring(0,6)}`:"#808080";return i.jsx(cK,{spool:fe,remaining:xe,pct:Ne,colorStyle:be,onClick:()=>a({spool:fe}),t},fe.id)})}),i.jsx(iet,{pageIndex:le,pageSize:z,totalRows:L,totalPages:q,onPageChange:G,onPageSizeChange:Ie,t})]}):i.jsx(uK,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}):pe.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:[ie.map(Fe=>{const fe=!!Lj[Fe],xe=A?.column===Fe;return i.jsx("th",{className:`text-left py-3 px-4 text-xs font-medium uppercase tracking-wide select-none ${Fe==="remaining"?"min-w-[150px]":""} ${fe?"cursor-pointer hover:text-bambu-green transition-colors":""} ${xe?"text-bambu-green":"text-bambu-gray"}`,onClick:fe?()=>ue(Fe):void 0,children:i.jsxs("span",{className:"inline-flex items-center gap-1",children:[eet[Fe]?.(t)??Fe,fe&&(xe?A.direction==="asc"?i.jsx(Mf,{className:"w-3 h-3"}):i.jsx(lb,{className:"w-3 h-3"}):i.jsx(_F,{className:"w-3 h-3 opacity-30"}))]})},Fe)}),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:pe.map(Fe=>{if(Fe.type==="group"){const{key:be,spools:we,representative:Ge}=Fe,ke=B.has(be),tt=Math.max(0,Ge.label_weight-Ge.weight_used),De=Ge.label_weight>0?tt/Ge.label_weight*100:0;return i.jsx(set,{spools:we,representative:Ge,remaining:tt,pct:De,isExpanded:ke,onToggle:()=>Ue(be),onEdit:Ke=>a({spool:Ke}),onArchive:Ke=>o({type:"archive",spoolId:Ke}),onDelete:Ke=>o({type:"delete",spoolId:Ke}),visibleColumns:ie,assignmentMap:oe,currencySymbol:he,dateFormat:ae,t},`group-${be}`)}const fe=Fe.spool,xe=Math.max(0,fe.label_weight-fe.weight_used),Ne=fe.label_weight>0?xe/fe.label_weight*100:0;return i.jsx(tse,{spool:fe,remaining:xe,pct:Ne,onEdit:()=>a({spool:fe}),onRestore:()=>ce.mutate(fe.id),onArchive:()=>o({type:"archive",spoolId:fe.id}),onDelete:()=>o({type:"delete",spoolId:fe.id}),visibleColumns:ie,assignmentMap:oe,currencySymbol:he,dateFormat:ae,t},fe.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:ge?`${L} ${t(L!==1?"inventory.spools":"inventory.spool")}`:i.jsxs(i.Fragment,{children:[t("inventory.showing")," ",le*R+1," ",t("inventory.to")," ",Math.min((le+1)*R,L)," ",t("inventory.of")," ",L," ",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:z,onChange:Fe=>Ie(Number(Fe.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(Fe=>i.jsx("option",{value:Fe,children:Fe},Fe)),i.jsx("option",{value:-1,children:t("inventory.all")})]}),!ge&&i.jsxs(i.Fragment,{children:[i.jsx("button",{onClick:()=>G(0),disabled:le===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(dX,{className:"w-4 h-4"})}),i.jsx("button",{onClick:()=>G(Fe=>Math.max(0,Fe-1)),disabled:le===0,className:"p-1.5 rounded text-bambu-gray hover:text-white disabled:opacity-30 disabled:cursor-not-allowed transition-colors",children:i.jsx(Yl,{className:"w-4 h-4"})}),i.jsxs("span",{className:"text-bambu-gray px-2 whitespace-nowrap",children:[t("inventory.page")," ",le+1," ",t("inventory.of")," ",q]}),i.jsx("button",{onClick:()=>G(Fe=>Math.min(q-1,Fe+1)),disabled:le>=q-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:()=>G(q-1),disabled:le>=q-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(hX,{className:"w-4 h-4"})})]})]})]})]}):i.jsx(uK,{hasFilters:me,onAddSpool:()=>a({spool:null}),t}),r!==null&&i.jsx(XJe,{isOpen:!0,onClose:()=>a(null),spool:r.spool,currencySymbol:he}),s&&i.jsx(bn,{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"?Z.mutate(s.spoolId):ve.mutate(s.spoolId),o(null)},onCancel:()=>o(null)}),i.jsx(YJe,{isOpen:P,onClose:()=>E(!1),columns:C,defaultColumns:d1,onSave:Q})]})}function iet({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(dX,{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(Yl,{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(hX,{className:"w-4 h-4"})})]})]})]})}function cK({spool:t,remaining:e,pct:n,colorStyle:r,onClick:a,t:s}){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 ${t.archived_at?"opacity-50":""}`,onClick:a,children:[i.jsx("div",{className:"h-14 flex items-center justify-center",style:{backgroundColor:r},children:i.jsx("span",{className:"bg-white/90 text-gray-800 px-3 py-0.5 rounded-full text-sm font-medium",children:g4(t.color_name,t.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:[t.material,t.subtype?` ${t.subtype}`:""]}),i.jsx("p",{className:"text-sm text-bambu-gray",children:t.brand||"-"})]}),i.jsxs("span",{className:"text-xs font-mono text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:["#",t.id]})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray mb-1",children:[i.jsx("span",{children:s("inventory.remaining")}),i.jsxs("span",{children:[Math.round(n),"%"]})]}),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 ${n>50?"bg-bambu-green":n>20?"bg-yellow-500":"bg-red-500"}`,style:{width:`${Math.min(n,100)}%`}})}),i.jsxs("span",{className:"text-xs text-bambu-gray min-w-[40px] text-right",children:[Math.round(e),"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:[s("inventory.labelWeight"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:Pc(t.label_weight)})]}),i.jsxs("div",{children:[i.jsxs("span",{className:"text-bambu-gray/60",children:[s("inventory.weightUsed"),": "]}),i.jsx("span",{className:"text-bambu-gray",children:t.weight_used>0?Pc(t.weight_used):"-"})]})]}),t.note&&i.jsx("div",{className:"text-xs text-bambu-gray/60 pt-2 border-t border-bambu-dark-tertiary truncate",title:t.note,children:t.note})]})]})}function tse({spool:t,remaining:e,pct:n,onEdit:r,onRestore:a,onArchive:s,onDelete:o,visibleColumns:l,assignmentMap:c,currencySymbol:u,dateFormat:d,t:h}){return i.jsxs("tr",{className:`border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer ${t.archived_at?"opacity-50":""}`,onClick:r,children:[l.map(f=>i.jsx("td",{className:"py-3 px-4",children:aF[f]?.({spool:t,remaining:e,pct:n,assignmentMap:c,currencySymbol:u,dateFormat:d,t:h})},f)),i.jsx("td",{className:"py-3 px-4",children:i.jsxs("div",{className:"flex items-center justify-end gap-1",onClick:f=>f.stopPropagation(),children:[i.jsx("button",{onClick:r,className:"p-1.5 text-bambu-gray hover:text-white rounded transition-colors",title:h("inventory.editSpool"),children:i.jsx(Jm,{className:"w-4 h-4"})}),t.archived_at?i.jsx("button",{onClick:a,className:"p-1.5 text-bambu-gray hover:text-bambu-green rounded transition-colors",title:h("inventory.restore"),children:i.jsx(so,{className:"w-4 h-4"})}):i.jsx("button",{onClick:s,className:"p-1.5 text-bambu-gray hover:text-yellow-400 rounded transition-colors",title:h("inventory.archive"),children:i.jsx(js,{className:"w-4 h-4"})}),i.jsx("button",{onClick:o,className:"p-1.5 text-bambu-gray hover:text-red-400 rounded transition-colors",title:h("common.delete"),children:i.jsx(Jt,{className:"w-4 h-4"})})]})})]})}function set({spools:t,representative:e,remaining:n,pct:r,isExpanded:a,onToggle:s,onEdit:o,onArchive:l,onDelete:c,visibleColumns:u,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p}){return i.jsxs(i.Fragment,{children:[i.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-tertiary/30 transition-colors cursor-pointer bg-bambu-green/5",onClick:s,children:[u.map((x,v)=>i.jsx("td",{className:"py-3 px-4",children:v===0?i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Pn,{className:`w-4 h-4 text-bambu-gray transition-transform ${a?"":"-rotate-90"}`}),aF[x]?.({spool:e,remaining:n,pct:r,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p})]}):x==="id"?i.jsx("span",{className:"text-xs font-medium bg-bambu-green/20 text-bambu-green px-2 py-0.5 rounded-full",children:p("inventory.groupedSpools",{count:t.length})}):aF[x]?.({spool:e,remaining:n,pct:r,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p})},x)),i.jsx("td",{className:"py-3 px-4",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:t.map(x=>`#${x.id}`).join(", ")})})]}),a&&t.map(x=>{const v=Math.max(0,x.label_weight-x.weight_used),g=x.label_weight>0?v/x.label_weight*100:0;return i.jsx(tse,{spool:x,remaining:v,pct:g,onEdit:()=>o(x),onRestore:()=>{},onArchive:()=>l(x.id),onDelete:()=>c(x.id),visibleColumns:u,assignmentMap:d,currencySymbol:h,dateFormat:f,t:p},x.id)})]})}function uK({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(Pe,{onClick:e,children:[i.jsx(fi,{className:"w-4 h-4"}),n("inventory.addSpool")]})]})}const dK=["DEBUG","INFO","WARNING","ERROR"],Oj={DEBUG:"text-gray-400",INFO:"text-blue-400",WARNING:"text-yellow-400",ERROR:"text-red-400"},oet={DEBUG:UC,INFO:Zs,WARNING:Mn,ERROR:Ba};function cet(){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:()=>Wg.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:()=>Wg.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]),T=({level:C})=>{const j=oet[C]||Zs;return i.jsx(j,{className:`w-3.5 h-3.5 ${Oj[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(UC,{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(Pn,{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(Ot,{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"}),dK.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===dK.length-1?"rounded-r":""} ${l===C?`${Oj[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(T,{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 ${Oj[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(Pn,{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 uet(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 hK({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 rh({title:t,icon:e,children:n}){return i.jsxs(wt,{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 det(){const{t}=Rt(),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:Wg.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 Wg.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 Wg.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(rh,{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:Wn,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(rh,{title:t("support.title","Support & Troubleshooting"),icon:Ume,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(UC,{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(da,{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(cet,{})]})}),i.jsxs(rh,{title:t("system.database","Database"),icon:Ec,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:ub,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:WC,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:Wn,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(rh,{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(rh,{title:t("system.storage","Storage"),icon:$b,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(hK,{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:Ec,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&i.jsx(ka,{icon:Jl,label:t("system.fileManagerStorage","File Manager"),value:uet(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(rh,{title:t("system.memory","Memory"),icon:xfe,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(hK,{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(rh,{title:t("system.cpu","CPU"),icon:tS,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(ka,{icon:tS,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),i.jsx(ka,{icon:tS,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),i.jsx(rh,{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:tS,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:Wn,label:t("system.bootTime","Boot Time"),value:Df(c.system.boot_time,v)})]})})]})}function het(){const t=Al(),{t:e}=Rt(),{login:n}=Ir(),{showToast:r}=cn(),{mode:a}=ep(),[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(wt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(gv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),i.jsx(Pe,{variant:"ghost",size:"sm",onClick:()=>{d(!1),f("")},children:i.jsx(Ot,{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(Pe,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),f("")},children:e("login.cancel")||"Cancel"}),i.jsx(Pe,{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(Pe,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function met(){const t=Al(),{t:e}=Rt(),{showToast:n}=cn(),{mode:r}=ep(),{refreshAuth:a}=Ir(),[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 fet(){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=T=>{try{const C=JSON.parse(T.data);C.type==="printer_status"&&C.printer_id!==void 0&&C.data?h.current(C):(u.current.push(C),f())}catch{}},k.onclose=T=>{console.log("[WebSocket] Closed",T.code,T.reason),A&&(clearInterval(A),A=null),a(!1),t.current=null,e.current=window.setTimeout(()=>{p()},3e3)},k.onerror=T=>{console.error("[WebSocket] Error",T),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((T,C)=>{n.setQueryData(["printerStatus",C],j=>{const P={...j,...T};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;case"spoolbuddy_weight":window.dispatchEvent(new CustomEvent("spoolbuddy-weight",{detail:_}));break;case"spoolbuddy_tag_matched":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-matched",{detail:_})),v("inventory-spools");break;case"spoolbuddy_unknown_tag":window.dispatchEvent(new CustomEvent("spoolbuddy-unknown-tag",{detail:_}));break;case"spoolbuddy_tag_removed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-removed",{detail:_}));break;case"spoolbuddy_online":window.dispatchEvent(new CustomEvent("spoolbuddy-online",{detail:_}));break;case"spoolbuddy_offline":window.dispatchEvent(new CustomEvent("spoolbuddy-offline",{detail:_}));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}}function pet({selectedPrinterId:t,onPrinterChange:e,deviceOnline:n}){const{t:r}=Rt(),[a,s]=w.useState(new Date),{data:o=[]}=Je({queryKey:["printers"],queryFn:()=>ne.getPrinters()});w.useEffect(()=>{!t&&o.length>0&&e(o[0].id)},[o,t,e]),w.useEffect(()=>{const c=setInterval(()=>s(new Date),3e4);return()=>clearInterval(c)},[]);const l=c=>c.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return i.jsxs("div",{className:"h-11 bg-zinc-950 border-b border-zinc-800 flex items-center px-3 gap-4 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[i.jsx("div",{className:"w-6 h-6 rounded bg-green-600 flex items-center justify-center",children:i.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),i.jsx("span",{className:"text-white font-semibold text-sm hidden sm:inline",children:"SpoolBuddy"})]}),i.jsx("div",{className:"flex-1 flex justify-center",children:i.jsx("select",{value:t??"",onChange:c=>e(Number(c.target.value)),className:"bg-zinc-800 text-white text-sm px-3 py-1.5 rounded border border-zinc-700 focus:outline-none focus:border-green-500 min-w-[150px]",children:o.length===0?i.jsx("option",{value:"",children:r("spoolbuddy.status.noPrinters","No printers")}):o.map(c=>i.jsx("option",{value:c.id,children:c.name},c.id))})}),i.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:n?r("spoolbuddy.status.online","Online"):r("spoolbuddy.status.offline","Offline"),children:[i.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${n?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400",children:n?r("spoolbuddy.status.online","Online"):r("spoolbuddy.status.offline","Offline")})]}),i.jsx("span",{className:"text-zinc-400 text-sm font-mono min-w-[50px] text-right",children:l(a)})]})]})}const get=[{to:"/spoolbuddy",labelKey:"spoolbuddy.nav.dashboard",fallback:"Dashboard",icon:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"})})},{to:"/spoolbuddy/ams",labelKey:"spoolbuddy.nav.ams",fallback:"AMS",icon:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})},{to:"/spoolbuddy/inventory",labelKey:"spoolbuddy.nav.inventory",fallback:"Inventory",icon:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})},{to:"/spoolbuddy/settings",labelKey:"spoolbuddy.nav.settings",fallback:"Settings",icon:i.jsxs("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}];function bet(){const{t}=Rt();return i.jsx("nav",{className:"h-12 bg-zinc-950 border-t border-zinc-800 flex items-stretch shrink-0",children:get.map(e=>i.jsxs(Lg,{to:e.to,end:e.to==="/spoolbuddy",className:({isActive:n})=>`flex-1 flex flex-col items-center justify-center gap-0.5 transition-colors ${n?"text-green-500 bg-zinc-900":"text-zinc-500 hover:text-zinc-300 hover:bg-zinc-900/50"}`,children:[e.icon,i.jsx("span",{className:"text-[10px] font-medium",children:t(e.labelKey,e.fallback)})]},e.to))})}const xet={weight:null,weightStable:!1,rawAdc:null,matchedSpool:null,unknownTagUid:null,deviceOnline:!1,deviceId:null};function yet(t,e){switch(e.type){case"WEIGHT_UPDATE":return{...t,weight:e.weight,weightStable:e.stable,rawAdc:e.rawAdc,deviceId:e.deviceId,deviceOnline:!0};case"TAG_MATCHED":return{...t,matchedSpool:e.spool,unknownTagUid:null,deviceId:e.deviceId};case"UNKNOWN_TAG":return{...t,matchedSpool:null,unknownTagUid:e.tagUid,deviceId:e.deviceId};case"TAG_REMOVED":return{...t,matchedSpool:null,unknownTagUid:null};case"DEVICE_ONLINE":return{...t,deviceOnline:!0,deviceId:e.deviceId};case"DEVICE_OFFLINE":return{...t,deviceOnline:!1,weight:null,weightStable:!1,rawAdc:null};default:return t}}function vet(){const[t,e]=w.useReducer(yet,xet),n=w.useCallback(d=>{const h=d.detail;e({type:"WEIGHT_UPDATE",weight:h.weight_grams??h.data?.weight_grams,stable:h.stable??h.data?.stable??!1,rawAdc:h.raw_adc??h.data?.raw_adc??null,deviceId:h.device_id??h.data?.device_id??""})},[]),r=w.useCallback(d=>{const h=d.detail,f=h.spool??h.data?.spool;f&&e({type:"TAG_MATCHED",spool:{id:f.id,tag_uid:h.tag_uid??h.data?.tag_uid??"",material:f.material??"",color_name:f.color_name??null,rgba:f.rgba??null,brand:f.brand??null,label_weight:f.label_weight??0,core_weight:f.core_weight??0,weight_used:f.weight_used??0},deviceId:h.device_id??h.data?.device_id??""})},[]),a=w.useCallback(d=>{const h=d.detail;e({type:"UNKNOWN_TAG",tagUid:h.tag_uid??h.data?.tag_uid??"",deviceId:h.device_id??h.data?.device_id??""})},[]),s=w.useCallback(d=>{const h=d.detail;e({type:"TAG_REMOVED",deviceId:h.device_id??h.data?.device_id??""})},[]),o=w.useCallback(d=>{const h=d.detail;e({type:"DEVICE_ONLINE",deviceId:h.device_id??h.data?.device_id??""})},[]),l=w.useCallback(d=>{const h=d.detail;e({type:"DEVICE_OFFLINE",deviceId:h.device_id??h.data?.device_id??""})},[]);w.useEffect(()=>(window.addEventListener("spoolbuddy-weight",n),window.addEventListener("spoolbuddy-tag-matched",r),window.addEventListener("spoolbuddy-unknown-tag",a),window.addEventListener("spoolbuddy-tag-removed",s),window.addEventListener("spoolbuddy-online",o),window.addEventListener("spoolbuddy-offline",l),()=>{window.removeEventListener("spoolbuddy-weight",n),window.removeEventListener("spoolbuddy-tag-matched",r),window.removeEventListener("spoolbuddy-unknown-tag",a),window.removeEventListener("spoolbuddy-tag-removed",s),window.removeEventListener("spoolbuddy-online",o),window.removeEventListener("spoolbuddy-offline",l)}),[n,r,a,s,o,l]);const c=t.matchedSpool?Math.max(0,t.matchedSpool.label_weight-t.matchedSpool.weight_used):null,u=t.weight!==null&&t.matchedSpool?Math.max(0,t.weight-t.matchedSpool.core_weight):null;return{...t,remainingWeight:c,netWeight:u}}function wet(){const[t,e]=w.useState(null),n=vet();return w.useEffect(()=>{const r=document.documentElement,a=r.classList.contains("dark");return r.classList.add("dark"),()=>{a||r.classList.remove("dark")}},[]),i.jsxs("div",{className:"w-screen h-screen bg-zinc-900 text-zinc-100 flex flex-col overflow-hidden",children:[i.jsx(pet,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:n.deviceOnline}),i.jsx("main",{className:"flex-1 overflow-y-auto",children:i.jsx(BK,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:n}})}),i.jsx(bet,{})]})}function _et({weight:t,weightStable:e,deviceOnline:n,deviceId:r}){const{t:a}=Rt(),s=async()=>{if(r)try{await Kg.tare(r)}catch(l){console.error("Failed to tare:",l)}},o=l=>l===null?"--.-":l.toFixed(1);return i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsxs("div",{className:"flex items-baseline gap-2",children:[i.jsx("span",{className:"text-5xl font-light tabular-nums text-zinc-100",children:o(t)}),i.jsx("span",{className:"text-xl text-zinc-400",children:"g"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]":"bg-amber-500 animate-pulse":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400",children:n?e?a("spoolbuddy.weight.stable","Stable"):a("spoolbuddy.weight.measuring","Measuring..."):a("spoolbuddy.weight.noReading","No reading")})]}),i.jsx("button",{onClick:s,disabled:!n||!r,className:"px-4 py-2 text-sm font-medium rounded-lg bg-zinc-800 text-zinc-300 hover:bg-zinc-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[40px]",children:a("spoolbuddy.weight.tare","Tare")})]})}function Net({spool:t,scaleWeight:e,weightStable:n,onClose:r}){const{t:a}=Rt(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),u=Math.max(0,t.label_weight-t.weight_used),d=t.label_weight>0?u/t.label_weight*100:0,h=e!==null?Math.max(0,e-t.core_weight):null,f=async()=>{if(!(e===null||!n)){o(!0);try{await Kg.updateSpoolWeight(t.id,Math.round(e)),c(!0),setTimeout(()=>c(!1),3e3)}catch(x){console.error("Failed to sync weight:",x)}finally{o(!1)}}},p=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080";return i.jsxs("div",{className:"bg-zinc-800 rounded-xl p-4 relative",children:[r&&i.jsx("button",{onClick:r,className:"absolute top-3 right-3 p-1 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full border-2 border-zinc-700 shrink-0",style:{backgroundColor:p}}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"text-base font-medium text-zinc-100 truncate",children:[t.material,t.color_name&&i.jsxs("span",{className:"text-zinc-400 ml-1.5",children:["- ",t.color_name]})]}),t.brand&&i.jsx("div",{className:"text-sm text-zinc-400 truncate",children:t.brand})]})]}),i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex justify-between text-xs text-zinc-400 mb-1",children:[i.jsx("span",{children:a("spoolbuddy.spool.remaining","Remaining")}),i.jsxs("span",{children:[Math.round(u),"g / ",t.label_weight,"g"]})]}),i.jsx("div",{className:"w-full h-2 bg-zinc-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Math.min(100,d)}%`,backgroundColor:d>50?"#22c55e":d>15?"#f59e0b":"#ef4444"}})})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm mb-4",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.labelWeight","Label")}),i.jsxs("span",{className:"text-zinc-300",children:[t.label_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"text-zinc-300",children:[t.core_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.scaleWeight","Scale")}),i.jsx("span",{className:"text-zinc-300",children:e!==null?`${e.toFixed(1)}g`:"--"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.netWeight","Net")}),i.jsx("span",{className:"text-zinc-300",children:h!==null?`${h.toFixed(1)}g`:"--"})]})]}),i.jsx("div",{className:"flex gap-2",children:i.jsx("button",{onClick:f,disabled:!n||e===null||s,className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${l?"bg-green-600/20 text-green-400":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:s?a("common.saving","Saving..."):l?a("spoolbuddy.dashboard.weightSynced","Synced!"):a("spoolbuddy.dashboard.syncWeight","Sync Weight")})})]})}function Cet({tagUid:t,onLinkSpool:e,onClose:n}){const{t:r}=Rt();return i.jsxs("div",{className:"bg-zinc-800 rounded-xl p-4 relative",children:[n&&i.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-amber-500/20 flex items-center justify-center shrink-0",children:i.jsx("svg",{className:"w-5 h-5 text-amber-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),i.jsxs("div",{children:[i.jsx("div",{className:"text-base font-medium text-zinc-100",children:r("spoolbuddy.dashboard.unknownTag","Unknown Tag")}),i.jsx("div",{className:"text-xs text-zinc-500 font-mono",children:t})]})]}),i.jsx("button",{onClick:e,className:"w-full px-4 py-2.5 rounded-lg text-sm font-medium bg-amber-600 text-white hover:bg-amber-700 transition-colors min-h-[44px]",children:r("spoolbuddy.dashboard.linkSpool","Link to Spool")})]})}const mK=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function ket(){const{t}=Rt(),[e,n]=w.useState(0);w.useEffect(()=>{const a=setInterval(()=>{n(s=>(s+1)%mK.length)},2e3);return()=>clearInterval(a)},[]);const r=mK[e];return i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center px-4",children:[i.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:140,height:140},children:[i.jsx("div",{className:"absolute w-20 h-20 rounded-full border-2 border-green-500/30 animate-ping",style:{animationDuration:"2.5s"}}),i.jsx("div",{className:"absolute w-28 h-28 rounded-full border border-green-500/20 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.4s"}}),i.jsx("div",{className:"absolute w-36 h-36 rounded-full border border-green-500/10 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.8s"}}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute -inset-4 rounded-full blur-2xl opacity-30 transition-colors duration-1000",style:{backgroundColor:r}}),i.jsxs("svg",{viewBox:"0 0 80 80",className:"w-20 h-20 transition-all duration-1000",children:[i.jsx("circle",{cx:"40",cy:"40",r:"38",fill:r}),i.jsx("circle",{cx:"40",cy:"40",r:"30",fill:r,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"30",cy:"30",rx:"8",ry:"5",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"40",cy:"40",r:"12",fill:"#27272a"}),i.jsx("circle",{cx:"40",cy:"40",r:"7",fill:"#18181b"})]})]})]}),i.jsx("p",{className:"text-lg text-zinc-300 mb-1",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),i.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]})}function Aet(){const{t}=Rt();return i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center px-4",children:[i.jsx("div",{className:"w-20 h-20 rounded-full bg-zinc-800 flex items-center justify-center mb-6",children:i.jsx("svg",{className:"w-10 h-10 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})}),i.jsx("p",{className:"text-lg text-zinc-400 mb-1",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),i.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})}function Met(){const{sbState:t}=uF(),e=Al(),{t:n}=Rt(),[r,a]=w.useState(null),[s,o]=w.useState(null),l=t.matchedSpool?.tag_uid??t.unknownTagUid??null;w.useEffect(()=>{l?(r!==null&&r!==l||!(s===l)&&r!==l)&&(a(l),o(null)):s&&(a(null),o(null))},[l,r,s]);const c=()=>{o(r)},u=()=>{e("/spoolbuddy/inventory")},d=r&&s!==r,h=t.matchedSpool&&r===t.matchedSpool.tag_uid;return t.deviceOnline?i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100 mb-4",children:n("spoolbuddy.nav.dashboard","Dashboard")}),i.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[i.jsxs("div",{className:"w-[40%] flex flex-col items-center justify-center gap-4",children:[i.jsx(_et,{weight:t.weight,weightStable:t.weightStable,deviceOnline:t.deviceOnline,deviceId:t.deviceId}),i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${t.deviceOnline?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:"text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.nfcReady","NFC Ready"):n("spoolbuddy.status.nfcOff","NFC Off")})]})]}),i.jsx("div",{className:"w-[60%] flex flex-col justify-center",children:d&&h&&t.matchedSpool?i.jsx(Net,{spool:t.matchedSpool,scaleWeight:t.weight,weightStable:t.weightStable,onClose:c}):d&&t.unknownTagUid?i.jsx(Cet,{tagUid:t.unknownTagUid,onLinkSpool:u,onClose:c}):i.jsx(ket,{})})]})]}):i.jsx("div",{className:"h-full flex flex-col",children:i.jsx(Aet,{})})}function Tet(t){return t?`#${t.slice(0,6)}`:"#808080"}function Pet(t){return!t.tray_type||t.tray_type===""}function Eet({tray:t,slotIndex:e,isActive:n}){const r=Pet(t),a=Tet(t.tray_color);return i.jsxs("div",{className:`relative flex flex-col items-center p-2 rounded-lg transition-all ${n?"ring-2 ring-green-500":""}`,children:[i.jsxs("div",{className:"relative w-14 h-14 mb-1",children:[r?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-zinc-600 flex items-center justify-center",children:i.jsx("div",{className:"w-3 h-3 rounded-full bg-zinc-700"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:a}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:a,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#27272a"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#18181b"})]}),n&&i.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2 h-2 bg-green-500 rounded-full"})]}),i.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-full",children:r?"Empty":t.tray_type||"Unknown"}),!r&&t.remain!==null&&t.remain!==void 0&&t.remain>=0&&i.jsx("div",{className:"w-full h-1 bg-zinc-700 rounded-full overflow-hidden mt-1",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${t.remain}%`,backgroundColor:t.remain>50?"#22c55e":t.remain>15?"#f59e0b":"#ef4444"}})}),i.jsx("span",{className:"absolute top-1 right-1 text-[10px] text-zinc-600",children:e+1})]})}function jet({unit:t,activeSlot:e}){const{t:n}=Rt(),r=t.tray||[],a=t.is_ams_ht,s=l=>l<=3?`AMS ${String.fromCharCode(65+l)}`:l>=128&&l<=135?`AMS HT ${String.fromCharCode(65+l-128)}`:`AMS ${l}`,o=a?1:4;return i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("span",{className:"text-white font-medium",children:s(t.id)}),t.humidity!==null&&t.humidity!==void 0&&i.jsxs("div",{className:"flex items-center gap-1 text-xs text-zinc-500",children:[i.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"})}),i.jsx("span",{children:t.humidity>5?`${t.humidity}%`:`${n("spoolbuddy.ams.level","Level")} ${t.humidity}`})]})]}),i.jsx("div",{className:`grid ${a?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:o}).map((l,c)=>{const u=r[c]||{id:c,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return i.jsx(Eet,{tray:u,slotIndex:c,isActive:e===c},c)})})]})}function Det(){const{selectedPrinterId:t}=uF(),{t:e}=Rt(),{data:n}=Je({queryKey:["printerStatus",t],enabled:t!==null}),r=n?.ams??[],a=n?.tray_now??255,s=o=>a===255||a===254?null:o<=3&&Math.floor(a/4)===o?a%4:null;return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100 mb-4",children:e("spoolbuddy.nav.ams","AMS")}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:t?r.length===0?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-zinc-500",children:[i.jsx("svg",{className:"w-12 h-12 mx-auto mb-3 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})}),i.jsx("p",{className:"text-lg mb-1",children:e("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:e("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.map(o=>i.jsx(jet,{unit:o,activeSlot:s(o.id)},o.id))}):i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-zinc-500",children:[i.jsx("svg",{className:"w-12 h-12 mx-auto mb-3 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"})}),i.jsx("p",{className:"text-lg mb-1",children:e("spoolbuddy.ams.noPrinter","No printer selected")}),i.jsx("p",{className:"text-sm",children:e("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})})]})}function Ret(t){if(!t)return"-";try{return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return"-"}}function Fet({spool:t}){const{t:e}=Rt(),[n,r]=w.useState(!1),a=Math.max(0,t.label_weight-t.weight_used),s=t.label_weight>0?a/t.label_weight*100:0,o=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080";return i.jsxs("button",{className:"w-full bg-zinc-800 rounded-lg p-3 text-left transition-colors hover:bg-zinc-750 active:bg-zinc-700",onClick:()=>r(!n),children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-8 h-8 rounded-full border border-zinc-700 shrink-0",style:{backgroundColor:o}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("span",{className:"text-sm font-medium text-zinc-100 truncate",children:[t.material,t.color_name&&i.jsxs("span",{className:"text-zinc-400 ml-1",children:["- ",t.color_name]})]})}),t.brand&&i.jsx("span",{className:"text-xs text-zinc-500 truncate block",children:t.brand})]}),i.jsxs("div",{className:"text-right shrink-0",children:[i.jsxs("div",{className:"text-sm text-zinc-300",children:[Math.round(a),"g"]}),i.jsx("div",{className:"text-xs text-zinc-500",children:e("spoolbuddy.spool.remaining","Remaining")})]})]}),i.jsx("div",{className:"w-full h-1 bg-zinc-700 rounded-full overflow-hidden mt-2",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Math.min(100,s)}%`,backgroundColor:s>50?"#22c55e":s>15?"#f59e0b":"#ef4444"}})}),n&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-zinc-700 grid grid-cols-2 gap-x-4 gap-y-1 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.labelWeight","Label")}),i.jsxs("span",{className:"text-zinc-400",children:[t.label_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"text-zinc-400",children:[t.core_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.material","Material")}),i.jsxs("span",{className:"text-zinc-400",children:[t.material,t.subtype?` ${t.subtype}`:""]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.lastUsed","Last used")}),i.jsx("span",{className:"text-zinc-400",children:Ret(t.last_used)})]}),t.tag_uid&&i.jsxs("div",{className:"col-span-2 flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"Tag"}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.tag_uid})]})]})]})}function Let(){const{t}=Rt(),[e,n]=w.useState(""),{data:r=[],isLoading:a}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!1)}),s=w.useMemo(()=>{if(!e.trim())return r;const o=e.toLowerCase();return r.filter(l=>l.material.toLowerCase().includes(o)||l.brand?.toLowerCase().includes(o)||l.color_name?.toLowerCase().includes(o))},[r,e]);return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100",children:t("spoolbuddy.nav.inventory","Inventory")}),i.jsxs("span",{className:"text-sm text-zinc-500",children:[r.length," ",t("spoolbuddy.inventory.spools","spools")]})]}),i.jsxs("div",{className:"relative mb-4",children:[i.jsx("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),i.jsx("input",{type:"text",value:e,onChange:o=>n(o.target.value),placeholder:t("spoolbuddy.inventory.search","Search spools..."),className:"w-full pl-10 pr-4 py-2.5 bg-zinc-800 border border-zinc-700 rounded-lg text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none focus:border-green-500 min-h-[44px]"})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:a?i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("span",{className:"text-zinc-500",children:t("common.loading","Loading...")})}):s.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-zinc-500",children:[i.jsx("svg",{className:"w-10 h-10 mb-2 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),i.jsx("p",{className:"text-sm",children:e?t("spoolbuddy.inventory.noResults","No matching spools"):t("spoolbuddy.inventory.empty","No spools in inventory")})]}):s.map(o=>i.jsx(Fet,{spool:o},o.id))})]})}function Oet(t){if(t<60)return`${t}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return`${e}h ${n}m`}function Iet({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=Rt(),[s,o]=w.useState(!1),[l,c]=w.useState("idle"),[u,d]=w.useState(500),[h,f]=w.useState(!1),p=async()=>{f(!0);try{await Kg.tare(t.device_id)}catch(g){console.error("Failed to tare:",g)}finally{f(!1)}},x=()=>{c("tare")},v=async()=>{if(l==="tare"){o(!0);try{await Kg.tare(t.device_id),c("weight")}catch(g){console.error("Failed to tare:",g)}finally{o(!1)}}else if(l==="weight"){if(r===null)return;o(!0);try{await Kg.setCalibrationFactor(t.device_id,u,r),c("idle")}catch(g){console.error("Failed to calibrate:",g)}finally{o(!1)}}};return i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-100 mb-4",children:a("spoolbuddy.settings.scaleCalibration","Scale Calibration")}),i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("span",{className:"text-sm text-zinc-400",children:a("spoolbuddy.settings.currentWeight","Current weight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4 mb-4 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.tareOffset","Tare offset")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.calFactor","Cal. factor")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]}),l==="idle"?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:p,disabled:h,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]",children:h?"...":a("spoolbuddy.weight.tare","Tare")}),i.jsx("button",{onClick:x,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]}):i.jsxs("div",{className:"border border-zinc-700 rounded-lg p-3 space-y-3",children:[i.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?a("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):a("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-xs text-zinc-400",children:a("spoolbuddy.settings.knownWeight","Known weight (g)")}),i.jsx("input",{type:"number",value:u,onChange:g=>d(Number(g.target.value)),className:"w-24 px-2 py-1.5 bg-zinc-900 border border-zinc-600 rounded text-sm text-zinc-100 focus:outline-none focus:border-green-500",min:1})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>c("idle"),className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]",children:a("common.cancel","Cancel")}),i.jsx("button",{onClick:v,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function zet({device:t}){const{t:e}=Rt();return i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-100 mb-4",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),i.jsxs("div",{className:"space-y-2 text-sm",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"Device ID"}),i.jsx("span",{className:"text-zinc-300 font-mono text-xs",children:t.device_id})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Hostname")}),i.jsx("span",{className:"text-zinc-300",children:t.hostname})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"IP"}),i.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.firmware","Firmware")}),i.jsx("span",{className:"text-zinc-300",children:t.firmware_version??"-"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"NFC"}),i.jsx("span",{className:t.nfc_ok?"text-green-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):e("spoolbuddy.status.nfcOff","Off")})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.scale","Scale")}),i.jsx("span",{className:t.scale_ok?"text-green-400":"text-red-400",children:t.scale_ok?"OK":e("common.error","Error")})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),i.jsx("span",{className:"text-zinc-300",children:Oet(t.uptime_s)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),i.jsx("span",{className:t.online?"text-green-400":"text-zinc-500",children:t.online?e("spoolbuddy.status.online","Online"):e("spoolbuddy.status.offline","Offline")})]})]})]})}function Uet(){const{sbState:t}=uF(),{t:e}=Rt(),{data:n=[]}=Je({queryKey:["spoolbuddy-devices"],queryFn:()=>Kg.getDevices(),refetchInterval:1e4}),r=t.deviceId?n.find(a=>a.device_id===t.deviceId)??n[0]:n[0];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100 mb-4",children:e("spoolbuddy.nav.settings","Settings")}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-4",children:r?i.jsxs(i.Fragment,{children:[i.jsx(Iet,{device:r,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),i.jsx(zet,{device:r})]}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const Bet=new gde({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function fK({children:t}){return fet(),i.jsx(i.Fragment,{children:t})}function pK({children:t}){const{authEnabled:e,loading:n,user:r}=Ir();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Ij({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Ir();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(ob,{to:"/",replace:!0}):i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Het({children:t}){const{authEnabled:e,loading:n}=Ir();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function $et(){return i.jsx(dge,{children:i.jsx(yge,{children:i.jsx(bde,{client:Bet,children:i.jsx(bge,{children:i.jsx(Lue,{children:i.jsxs(due,{children:[i.jsx(jr,{path:"/setup",element:i.jsx(Het,{children:i.jsx(met,{})})}),i.jsx(jr,{path:"/login",element:i.jsx(het,{})}),i.jsx(jr,{path:"/camera/:printerId",element:i.jsx(_Je,{})}),i.jsx(jr,{path:"/overlay/:printerId",element:i.jsx(AJe,{})}),i.jsxs(jr,{element:i.jsx(pK,{children:i.jsx(fK,{children:i.jsx(wet,{})})}),children:[i.jsx(jr,{path:"spoolbuddy",element:i.jsx(Met,{})}),i.jsx(jr,{path:"spoolbuddy/ams",element:i.jsx(Det,{})}),i.jsx(jr,{path:"spoolbuddy/inventory",element:i.jsx(Let,{})}),i.jsx(jr,{path:"spoolbuddy/settings",element:i.jsx(Uet,{})})]}),i.jsxs(jr,{element:i.jsx(pK,{children:i.jsx(fK,{children:i.jsx(_ge,{})})}),children:[i.jsx(jr,{index:!0,element:i.jsx(S$e,{})}),i.jsx(jr,{path:"archives",element:i.jsx(cYe,{})}),i.jsx(jr,{path:"queue",element:i.jsx(WQe,{})}),i.jsx(jr,{path:"stats",element:i.jsx(oZe,{})}),i.jsx(jr,{path:"profiles",element:i.jsx(ZZe,{})}),i.jsx(jr,{path:"maintenance",element:i.jsx(rJe,{})}),i.jsx(jr,{path:"projects",element:i.jsx(iJe,{})}),i.jsx(jr,{path:"projects/:id",element:i.jsx(hJe,{})}),i.jsx(jr,{path:"inventory",element:i.jsx(ret,{})}),i.jsx(jr,{path:"files",element:i.jsx(yJe,{})}),i.jsx(jr,{path:"settings",element:i.jsx(Ij,{children:i.jsx(IZe,{})})}),i.jsx(jr,{path:"groups/new",element:i.jsx(Ij,{children:i.jsx(iK,{})})}),i.jsx(jr,{path:"groups/:id/edit",element:i.jsx(Ij,{children:i.jsx(iK,{})})}),i.jsx(jr,{path:"users",element:i.jsx(ob,{to:"/settings?tab=users",replace:!0})}),i.jsx(jr,{path:"groups",element:i.jsx(ob,{to:"/settings?tab=users",replace:!0})}),i.jsx(jr,{path:"system",element:i.jsx(det,{})}),i.jsx(jr,{path:"external/:id",element:i.jsx(MJe,{})})]})]})})})})})})}ole.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx($et,{})})); +`)[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(Pn,{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 uet(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 hK({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 rh({title:t,icon:e,children:n}){return i.jsxs(wt,{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 det(){const{t}=Rt(),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:Wg.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 Wg.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 Wg.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(rh,{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:Wn,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(rh,{title:t("support.title","Support & Troubleshooting"),icon:Ume,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(UC,{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(da,{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.jsxs("li",{children:["• ",t("support.notItem7","IP addresses")]})]})]})]}),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], serial numbers with [SERIAL], and IP addresses with [IP].")})]}),i.jsx(cet,{})]})}),i.jsxs(rh,{title:t("system.database","Database"),icon:Ec,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:ub,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:WC,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:Wn,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(rh,{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(rh,{title:t("system.storage","Storage"),icon:$b,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(hK,{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:Ec,label:t("system.databaseSize","Database Size"),value:c.storage.database_size_formatted}),x&&i.jsx(ka,{icon:Jl,label:t("system.fileManagerStorage","File Manager"),value:uet(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(rh,{title:t("system.memory","Memory"),icon:xfe,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(hK,{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(rh,{title:t("system.cpu","CPU"),icon:tS,children:i.jsx("div",{className:"space-y-4",children:i.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[i.jsx(ka,{icon:tS,label:t("system.cores","Cores"),value:c.cpu.count,subValue:`${c.cpu.count_logical} logical`}),i.jsx(ka,{icon:tS,label:t("system.usage","Usage"),value:`${c.cpu.percent}%`})]})})})]}),i.jsx(rh,{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:tS,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:Wn,label:t("system.bootTime","Boot Time"),value:Df(c.system.boot_time,v)})]})})]})}function het(){const t=Al(),{t:e}=Rt(),{login:n}=Ir(),{showToast:r}=cn(),{mode:a}=ep(),[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(wt,{className:"w-full max-w-md",onClick:_=>_.stopPropagation(),children:[i.jsx(zn,{children:i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(gv,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:e("login.forgotPasswordTitle")})]}),i.jsx(Pe,{variant:"ghost",size:"sm",onClick:()=>{d(!1),f("")},children:i.jsx(Ot,{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(Pe,{type:"button",variant:"secondary",className:"flex-1",onClick:()=>{d(!1),f("")},children:e("login.cancel")||"Cancel"}),i.jsx(Pe,{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(Pe,{variant:"secondary",className:"w-full",onClick:()=>d(!1),children:e("login.gotIt")})]})})]})})]})}function met(){const t=Al(),{t:e}=Rt(),{showToast:n}=cn(),{mode:r}=ep(),{refreshAuth:a}=Ir(),[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 fet(){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=T=>{try{const C=JSON.parse(T.data);C.type==="printer_status"&&C.printer_id!==void 0&&C.data?h.current(C):(u.current.push(C),f())}catch{}},k.onclose=T=>{console.log("[WebSocket] Closed",T.code,T.reason),A&&(clearInterval(A),A=null),a(!1),t.current=null,e.current=window.setTimeout(()=>{p()},3e3)},k.onerror=T=>{console.error("[WebSocket] Error",T),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((T,C)=>{n.setQueryData(["printerStatus",C],j=>{const P={...j,...T};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;case"spoolbuddy_weight":window.dispatchEvent(new CustomEvent("spoolbuddy-weight",{detail:_}));break;case"spoolbuddy_tag_matched":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-matched",{detail:_})),v("inventory-spools");break;case"spoolbuddy_unknown_tag":window.dispatchEvent(new CustomEvent("spoolbuddy-unknown-tag",{detail:_}));break;case"spoolbuddy_tag_removed":window.dispatchEvent(new CustomEvent("spoolbuddy-tag-removed",{detail:_}));break;case"spoolbuddy_online":window.dispatchEvent(new CustomEvent("spoolbuddy-online",{detail:_}));break;case"spoolbuddy_offline":window.dispatchEvent(new CustomEvent("spoolbuddy-offline",{detail:_}));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}}function pet({selectedPrinterId:t,onPrinterChange:e,deviceOnline:n}){const{t:r}=Rt(),[a,s]=w.useState(new Date),{data:o=[]}=Je({queryKey:["printers"],queryFn:()=>ne.getPrinters()});w.useEffect(()=>{!t&&o.length>0&&e(o[0].id)},[o,t,e]),w.useEffect(()=>{const c=setInterval(()=>s(new Date),3e4);return()=>clearInterval(c)},[]);const l=c=>c.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});return i.jsxs("div",{className:"h-11 bg-zinc-950 border-b border-zinc-800 flex items-center px-3 gap-4 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[i.jsx("div",{className:"w-6 h-6 rounded bg-green-600 flex items-center justify-center",children:i.jsx("svg",{className:"w-4 h-4 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})}),i.jsx("span",{className:"text-white font-semibold text-sm hidden sm:inline",children:"SpoolBuddy"})]}),i.jsx("div",{className:"flex-1 flex justify-center",children:i.jsx("select",{value:t??"",onChange:c=>e(Number(c.target.value)),className:"bg-zinc-800 text-white text-sm px-3 py-1.5 rounded border border-zinc-700 focus:outline-none focus:border-green-500 min-w-[150px]",children:o.length===0?i.jsx("option",{value:"",children:r("spoolbuddy.status.noPrinters","No printers")}):o.map(c=>i.jsx("option",{value:c.id,children:c.name},c.id))})}),i.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-1.5",title:n?r("spoolbuddy.status.online","Online"):r("spoolbuddy.status.offline","Offline"),children:[i.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${n?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400",children:n?r("spoolbuddy.status.online","Online"):r("spoolbuddy.status.offline","Offline")})]}),i.jsx("span",{className:"text-zinc-400 text-sm font-mono min-w-[50px] text-right",children:l(a)})]})]})}const get=[{to:"/spoolbuddy",labelKey:"spoolbuddy.nav.dashboard",fallback:"Dashboard",icon:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"})})},{to:"/spoolbuddy/ams",labelKey:"spoolbuddy.nav.ams",fallback:"AMS",icon:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})},{to:"/spoolbuddy/inventory",labelKey:"spoolbuddy.nav.inventory",fallback:"Inventory",icon:i.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})})},{to:"/spoolbuddy/settings",labelKey:"spoolbuddy.nav.settings",fallback:"Settings",icon:i.jsxs("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:[i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}];function bet(){const{t}=Rt();return i.jsx("nav",{className:"h-12 bg-zinc-950 border-t border-zinc-800 flex items-stretch shrink-0",children:get.map(e=>i.jsxs(Lg,{to:e.to,end:e.to==="/spoolbuddy",className:({isActive:n})=>`flex-1 flex flex-col items-center justify-center gap-0.5 transition-colors ${n?"text-green-500 bg-zinc-900":"text-zinc-500 hover:text-zinc-300 hover:bg-zinc-900/50"}`,children:[e.icon,i.jsx("span",{className:"text-[10px] font-medium",children:t(e.labelKey,e.fallback)})]},e.to))})}const xet={weight:null,weightStable:!1,rawAdc:null,matchedSpool:null,unknownTagUid:null,deviceOnline:!1,deviceId:null};function yet(t,e){switch(e.type){case"WEIGHT_UPDATE":return{...t,weight:e.weight,weightStable:e.stable,rawAdc:e.rawAdc,deviceId:e.deviceId,deviceOnline:!0};case"TAG_MATCHED":return{...t,matchedSpool:e.spool,unknownTagUid:null,deviceId:e.deviceId};case"UNKNOWN_TAG":return{...t,matchedSpool:null,unknownTagUid:e.tagUid,deviceId:e.deviceId};case"TAG_REMOVED":return{...t,matchedSpool:null,unknownTagUid:null};case"DEVICE_ONLINE":return{...t,deviceOnline:!0,deviceId:e.deviceId};case"DEVICE_OFFLINE":return{...t,deviceOnline:!1,weight:null,weightStable:!1,rawAdc:null};default:return t}}function vet(){const[t,e]=w.useReducer(yet,xet),n=w.useCallback(d=>{const h=d.detail;e({type:"WEIGHT_UPDATE",weight:h.weight_grams??h.data?.weight_grams,stable:h.stable??h.data?.stable??!1,rawAdc:h.raw_adc??h.data?.raw_adc??null,deviceId:h.device_id??h.data?.device_id??""})},[]),r=w.useCallback(d=>{const h=d.detail,f=h.spool??h.data?.spool;f&&e({type:"TAG_MATCHED",spool:{id:f.id,tag_uid:h.tag_uid??h.data?.tag_uid??"",material:f.material??"",color_name:f.color_name??null,rgba:f.rgba??null,brand:f.brand??null,label_weight:f.label_weight??0,core_weight:f.core_weight??0,weight_used:f.weight_used??0},deviceId:h.device_id??h.data?.device_id??""})},[]),a=w.useCallback(d=>{const h=d.detail;e({type:"UNKNOWN_TAG",tagUid:h.tag_uid??h.data?.tag_uid??"",deviceId:h.device_id??h.data?.device_id??""})},[]),s=w.useCallback(d=>{const h=d.detail;e({type:"TAG_REMOVED",deviceId:h.device_id??h.data?.device_id??""})},[]),o=w.useCallback(d=>{const h=d.detail;e({type:"DEVICE_ONLINE",deviceId:h.device_id??h.data?.device_id??""})},[]),l=w.useCallback(d=>{const h=d.detail;e({type:"DEVICE_OFFLINE",deviceId:h.device_id??h.data?.device_id??""})},[]);w.useEffect(()=>(window.addEventListener("spoolbuddy-weight",n),window.addEventListener("spoolbuddy-tag-matched",r),window.addEventListener("spoolbuddy-unknown-tag",a),window.addEventListener("spoolbuddy-tag-removed",s),window.addEventListener("spoolbuddy-online",o),window.addEventListener("spoolbuddy-offline",l),()=>{window.removeEventListener("spoolbuddy-weight",n),window.removeEventListener("spoolbuddy-tag-matched",r),window.removeEventListener("spoolbuddy-unknown-tag",a),window.removeEventListener("spoolbuddy-tag-removed",s),window.removeEventListener("spoolbuddy-online",o),window.removeEventListener("spoolbuddy-offline",l)}),[n,r,a,s,o,l]);const c=t.matchedSpool?Math.max(0,t.matchedSpool.label_weight-t.matchedSpool.weight_used):null,u=t.weight!==null&&t.matchedSpool?Math.max(0,t.weight-t.matchedSpool.core_weight):null;return{...t,remainingWeight:c,netWeight:u}}function wet(){const[t,e]=w.useState(null),n=vet();return w.useEffect(()=>{const r=document.documentElement,a=r.classList.contains("dark");return r.classList.add("dark"),()=>{a||r.classList.remove("dark")}},[]),i.jsxs("div",{className:"w-screen h-screen bg-zinc-900 text-zinc-100 flex flex-col overflow-hidden",children:[i.jsx(pet,{selectedPrinterId:t,onPrinterChange:e,deviceOnline:n.deviceOnline}),i.jsx("main",{className:"flex-1 overflow-y-auto",children:i.jsx(BK,{context:{selectedPrinterId:t,setSelectedPrinterId:e,sbState:n}})}),i.jsx(bet,{})]})}function _et({weight:t,weightStable:e,deviceOnline:n,deviceId:r}){const{t:a}=Rt(),s=async()=>{if(r)try{await Kg.tare(r)}catch(l){console.error("Failed to tare:",l)}},o=l=>l===null?"--.-":l.toFixed(1);return i.jsxs("div",{className:"flex flex-col items-center gap-3",children:[i.jsxs("div",{className:"flex items-baseline gap-2",children:[i.jsx("span",{className:"text-5xl font-light tabular-nums text-zinc-100",children:o(t)}),i.jsx("span",{className:"text-xl text-zinc-400",children:"g"})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.5)]":"bg-amber-500 animate-pulse":"bg-zinc-600"}`}),i.jsx("span",{className:"text-xs text-zinc-400",children:n?e?a("spoolbuddy.weight.stable","Stable"):a("spoolbuddy.weight.measuring","Measuring..."):a("spoolbuddy.weight.noReading","No reading")})]}),i.jsx("button",{onClick:s,disabled:!n||!r,className:"px-4 py-2 text-sm font-medium rounded-lg bg-zinc-800 text-zinc-300 hover:bg-zinc-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors min-h-[40px]",children:a("spoolbuddy.weight.tare","Tare")})]})}function Net({spool:t,scaleWeight:e,weightStable:n,onClose:r}){const{t:a}=Rt(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),u=Math.max(0,t.label_weight-t.weight_used),d=t.label_weight>0?u/t.label_weight*100:0,h=e!==null?Math.max(0,e-t.core_weight):null,f=async()=>{if(!(e===null||!n)){o(!0);try{await Kg.updateSpoolWeight(t.id,Math.round(e)),c(!0),setTimeout(()=>c(!1),3e3)}catch(x){console.error("Failed to sync weight:",x)}finally{o(!1)}}},p=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080";return i.jsxs("div",{className:"bg-zinc-800 rounded-xl p-4 relative",children:[r&&i.jsx("button",{onClick:r,className:"absolute top-3 right-3 p-1 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full border-2 border-zinc-700 shrink-0",style:{backgroundColor:p}}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"text-base font-medium text-zinc-100 truncate",children:[t.material,t.color_name&&i.jsxs("span",{className:"text-zinc-400 ml-1.5",children:["- ",t.color_name]})]}),t.brand&&i.jsx("div",{className:"text-sm text-zinc-400 truncate",children:t.brand})]})]}),i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex justify-between text-xs text-zinc-400 mb-1",children:[i.jsx("span",{children:a("spoolbuddy.spool.remaining","Remaining")}),i.jsxs("span",{children:[Math.round(u),"g / ",t.label_weight,"g"]})]}),i.jsx("div",{className:"w-full h-2 bg-zinc-700 rounded-full overflow-hidden",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Math.min(100,d)}%`,backgroundColor:d>50?"#22c55e":d>15?"#f59e0b":"#ef4444"}})})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm mb-4",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.labelWeight","Label")}),i.jsxs("span",{className:"text-zinc-300",children:[t.label_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"text-zinc-300",children:[t.core_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.scaleWeight","Scale")}),i.jsx("span",{className:"text-zinc-300",children:e!==null?`${e.toFixed(1)}g`:"--"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.spool.netWeight","Net")}),i.jsx("span",{className:"text-zinc-300",children:h!==null?`${h.toFixed(1)}g`:"--"})]})]}),i.jsx("div",{className:"flex gap-2",children:i.jsx("button",{onClick:f,disabled:!n||e===null||s,className:`flex-1 px-4 py-2.5 rounded-lg text-sm font-medium transition-colors min-h-[44px] ${l?"bg-green-600/20 text-green-400":"bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 disabled:cursor-not-allowed"}`,children:s?a("common.saving","Saving..."):l?a("spoolbuddy.dashboard.weightSynced","Synced!"):a("spoolbuddy.dashboard.syncWeight","Sync Weight")})})]})}function Cet({tagUid:t,onLinkSpool:e,onClose:n}){const{t:r}=Rt();return i.jsxs("div",{className:"bg-zinc-800 rounded-xl p-4 relative",children:[n&&i.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1 rounded-lg text-zinc-500 hover:text-zinc-300 hover:bg-zinc-700 transition-colors",children:i.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),i.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[i.jsx("div",{className:"w-10 h-10 rounded-full bg-amber-500/20 flex items-center justify-center shrink-0",children:i.jsx("svg",{className:"w-5 h-5 text-amber-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),i.jsxs("div",{children:[i.jsx("div",{className:"text-base font-medium text-zinc-100",children:r("spoolbuddy.dashboard.unknownTag","Unknown Tag")}),i.jsx("div",{className:"text-xs text-zinc-500 font-mono",children:t})]})]}),i.jsx("button",{onClick:e,className:"w-full px-4 py-2.5 rounded-lg text-sm font-medium bg-amber-600 text-white hover:bg-amber-700 transition-colors min-h-[44px]",children:r("spoolbuddy.dashboard.linkSpool","Link to Spool")})]})}const mK=["#00AE42","#FF6B35","#3B82F6","#EF4444","#A855F7","#FBBF24","#14B8A6","#EC4899","#F97316","#22C55E"];function ket(){const{t}=Rt(),[e,n]=w.useState(0);w.useEffect(()=>{const a=setInterval(()=>{n(s=>(s+1)%mK.length)},2e3);return()=>clearInterval(a)},[]);const r=mK[e];return i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center px-4",children:[i.jsxs("div",{className:"relative mb-6 flex items-center justify-center",style:{width:140,height:140},children:[i.jsx("div",{className:"absolute w-20 h-20 rounded-full border-2 border-green-500/30 animate-ping",style:{animationDuration:"2.5s"}}),i.jsx("div",{className:"absolute w-28 h-28 rounded-full border border-green-500/20 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.4s"}}),i.jsx("div",{className:"absolute w-36 h-36 rounded-full border border-green-500/10 animate-ping",style:{animationDuration:"2.5s",animationDelay:"0.8s"}}),i.jsxs("div",{className:"relative",children:[i.jsx("div",{className:"absolute -inset-4 rounded-full blur-2xl opacity-30 transition-colors duration-1000",style:{backgroundColor:r}}),i.jsxs("svg",{viewBox:"0 0 80 80",className:"w-20 h-20 transition-all duration-1000",children:[i.jsx("circle",{cx:"40",cy:"40",r:"38",fill:r}),i.jsx("circle",{cx:"40",cy:"40",r:"30",fill:r,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"30",cy:"30",rx:"8",ry:"5",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"40",cy:"40",r:"12",fill:"#27272a"}),i.jsx("circle",{cx:"40",cy:"40",r:"7",fill:"#18181b"})]})]})]}),i.jsx("p",{className:"text-lg text-zinc-300 mb-1",children:t("spoolbuddy.dashboard.readyToScan","Ready to scan")}),i.jsx("p",{className:"text-sm text-zinc-500",children:t("spoolbuddy.dashboard.idleMessage","Place a spool on the scale to identify it")})]})}function Aet(){const{t}=Rt();return i.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center px-4",children:[i.jsx("div",{className:"w-20 h-20 rounded-full bg-zinc-800 flex items-center justify-center mb-6",children:i.jsx("svg",{className:"w-10 h-10 text-zinc-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M18.364 5.636a9 9 0 010 12.728m0 0l-12.728-12.728m12.728 12.728L5.636 5.636m12.728 0a9 9 0 00-12.728 0m0 12.728a9 9 0 010-12.728"})})}),i.jsx("p",{className:"text-lg text-zinc-400 mb-1",children:t("spoolbuddy.status.deviceOffline","Device Offline")}),i.jsx("p",{className:"text-sm text-zinc-600",children:t("spoolbuddy.status.waitingConnection","Waiting for device connection...")})]})}function Met(){const{sbState:t}=uF(),e=Al(),{t:n}=Rt(),[r,a]=w.useState(null),[s,o]=w.useState(null),l=t.matchedSpool?.tag_uid??t.unknownTagUid??null;w.useEffect(()=>{l?(r!==null&&r!==l||!(s===l)&&r!==l)&&(a(l),o(null)):s&&(a(null),o(null))},[l,r,s]);const c=()=>{o(r)},u=()=>{e("/spoolbuddy/inventory")},d=r&&s!==r,h=t.matchedSpool&&r===t.matchedSpool.tag_uid;return t.deviceOnline?i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100 mb-4",children:n("spoolbuddy.nav.dashboard","Dashboard")}),i.jsxs("div",{className:"flex-1 flex gap-4 min-h-0",children:[i.jsxs("div",{className:"w-[40%] flex flex-col items-center justify-center gap-4",children:[i.jsx(_et,{weight:t.weight,weightStable:t.weightStable,deviceOnline:t.deviceOnline,deviceId:t.deviceId}),i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${t.deviceOnline?"bg-green-500":"bg-zinc-600"}`}),i.jsx("span",{className:"text-zinc-400",children:t.deviceOnline?n("spoolbuddy.status.nfcReady","NFC Ready"):n("spoolbuddy.status.nfcOff","NFC Off")})]})]}),i.jsx("div",{className:"w-[60%] flex flex-col justify-center",children:d&&h&&t.matchedSpool?i.jsx(Net,{spool:t.matchedSpool,scaleWeight:t.weight,weightStable:t.weightStable,onClose:c}):d&&t.unknownTagUid?i.jsx(Cet,{tagUid:t.unknownTagUid,onLinkSpool:u,onClose:c}):i.jsx(ket,{})})]})]}):i.jsx("div",{className:"h-full flex flex-col",children:i.jsx(Aet,{})})}function Tet(t){return t?`#${t.slice(0,6)}`:"#808080"}function Pet(t){return!t.tray_type||t.tray_type===""}function Eet({tray:t,slotIndex:e,isActive:n}){const r=Pet(t),a=Tet(t.tray_color);return i.jsxs("div",{className:`relative flex flex-col items-center p-2 rounded-lg transition-all ${n?"ring-2 ring-green-500":""}`,children:[i.jsxs("div",{className:"relative w-14 h-14 mb-1",children:[r?i.jsx("div",{className:"w-full h-full rounded-full border-2 border-dashed border-zinc-600 flex items-center justify-center",children:i.jsx("div",{className:"w-3 h-3 rounded-full bg-zinc-700"})}):i.jsxs("svg",{viewBox:"0 0 56 56",className:"w-full h-full",children:[i.jsx("circle",{cx:"28",cy:"28",r:"26",fill:a}),i.jsx("circle",{cx:"28",cy:"28",r:"20",fill:a,style:{filter:"brightness(0.85)"}}),i.jsx("ellipse",{cx:"20",cy:"20",rx:"6",ry:"4",fill:"white",opacity:"0.3"}),i.jsx("circle",{cx:"28",cy:"28",r:"8",fill:"#27272a"}),i.jsx("circle",{cx:"28",cy:"28",r:"5",fill:"#18181b"})]}),n&&i.jsx("div",{className:"absolute -bottom-1 left-1/2 -translate-x-1/2 w-2 h-2 bg-green-500 rounded-full"})]}),i.jsx("span",{className:"text-xs text-zinc-400 truncate max-w-full",children:r?"Empty":t.tray_type||"Unknown"}),!r&&t.remain!==null&&t.remain!==void 0&&t.remain>=0&&i.jsx("div",{className:"w-full h-1 bg-zinc-700 rounded-full overflow-hidden mt-1",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${t.remain}%`,backgroundColor:t.remain>50?"#22c55e":t.remain>15?"#f59e0b":"#ef4444"}})}),i.jsx("span",{className:"absolute top-1 right-1 text-[10px] text-zinc-600",children:e+1})]})}function jet({unit:t,activeSlot:e}){const{t:n}=Rt(),r=t.tray||[],a=t.is_ams_ht,s=l=>l<=3?`AMS ${String.fromCharCode(65+l)}`:l>=128&&l<=135?`AMS HT ${String.fromCharCode(65+l-128)}`:`AMS ${l}`,o=a?1:4;return i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-3",children:[i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("span",{className:"text-white font-medium",children:s(t.id)}),t.humidity!==null&&t.humidity!==void 0&&i.jsxs("div",{className:"flex items-center gap-1 text-xs text-zinc-500",children:[i.jsx("svg",{className:"w-4 h-4",fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{d:"M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"})}),i.jsx("span",{children:t.humidity>5?`${t.humidity}%`:`${n("spoolbuddy.ams.level","Level")} ${t.humidity}`})]})]}),i.jsx("div",{className:`grid ${a?"grid-cols-1 max-w-[100px] mx-auto":"grid-cols-4"} gap-2`,children:Array.from({length:o}).map((l,c)=>{const u=r[c]||{id:c,tray_color:null,tray_type:"",tray_sub_brands:null,tray_id_name:null,tray_info_idx:null,remain:-1,k:null,cali_idx:null,tag_uid:null,tray_uuid:null,nozzle_temp_min:null,nozzle_temp_max:null};return i.jsx(Eet,{tray:u,slotIndex:c,isActive:e===c},c)})})]})}function Det(){const{selectedPrinterId:t}=uF(),{t:e}=Rt(),{data:n}=Je({queryKey:["printerStatus",t],enabled:t!==null}),r=n?.ams??[],a=n?.tray_now??255,s=o=>a===255||a===254?null:o<=3&&Math.floor(a/4)===o?a%4:null;return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100 mb-4",children:e("spoolbuddy.nav.ams","AMS")}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:t?r.length===0?i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-zinc-500",children:[i.jsx("svg",{className:"w-12 h-12 mx-auto mb-3 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})}),i.jsx("p",{className:"text-lg mb-1",children:e("spoolbuddy.ams.noData","No AMS detected")}),i.jsx("p",{className:"text-sm",children:e("spoolbuddy.ams.connectAms","Connect an AMS to see filament slots")})]})}):i.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.map(o=>i.jsx(jet,{unit:o,activeSlot:s(o.id)},o.id))}):i.jsx("div",{className:"flex items-center justify-center h-full",children:i.jsxs("div",{className:"text-center text-zinc-500",children:[i.jsx("svg",{className:"w-12 h-12 mx-auto mb-3 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"})}),i.jsx("p",{className:"text-lg mb-1",children:e("spoolbuddy.ams.noPrinter","No printer selected")}),i.jsx("p",{className:"text-sm",children:e("spoolbuddy.ams.selectPrinter","Select a printer from the top bar")})]})})})]})}function Ret(t){if(!t)return"-";try{return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return"-"}}function Fet({spool:t}){const{t:e}=Rt(),[n,r]=w.useState(!1),a=Math.max(0,t.label_weight-t.weight_used),s=t.label_weight>0?a/t.label_weight*100:0,o=t.rgba?`#${t.rgba.slice(0,6)}`:"#808080";return i.jsxs("button",{className:"w-full bg-zinc-800 rounded-lg p-3 text-left transition-colors hover:bg-zinc-750 active:bg-zinc-700",onClick:()=>r(!n),children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("div",{className:"w-8 h-8 rounded-full border border-zinc-700 shrink-0",style:{backgroundColor:o}}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("div",{className:"flex items-center gap-2",children:i.jsxs("span",{className:"text-sm font-medium text-zinc-100 truncate",children:[t.material,t.color_name&&i.jsxs("span",{className:"text-zinc-400 ml-1",children:["- ",t.color_name]})]})}),t.brand&&i.jsx("span",{className:"text-xs text-zinc-500 truncate block",children:t.brand})]}),i.jsxs("div",{className:"text-right shrink-0",children:[i.jsxs("div",{className:"text-sm text-zinc-300",children:[Math.round(a),"g"]}),i.jsx("div",{className:"text-xs text-zinc-500",children:e("spoolbuddy.spool.remaining","Remaining")})]})]}),i.jsx("div",{className:"w-full h-1 bg-zinc-700 rounded-full overflow-hidden mt-2",children:i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Math.min(100,s)}%`,backgroundColor:s>50?"#22c55e":s>15?"#f59e0b":"#ef4444"}})}),n&&i.jsxs("div",{className:"mt-3 pt-3 border-t border-zinc-700 grid grid-cols-2 gap-x-4 gap-y-1 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.labelWeight","Label")}),i.jsxs("span",{className:"text-zinc-400",children:[t.label_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.coreWeight","Core")}),i.jsxs("span",{className:"text-zinc-400",children:[t.core_weight,"g"]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.material","Material")}),i.jsxs("span",{className:"text-zinc-400",children:[t.material,t.subtype?` ${t.subtype}`:""]})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.spool.lastUsed","Last used")}),i.jsx("span",{className:"text-zinc-400",children:Ret(t.last_used)})]}),t.tag_uid&&i.jsxs("div",{className:"col-span-2 flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"Tag"}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.tag_uid})]})]})]})}function Let(){const{t}=Rt(),[e,n]=w.useState(""),{data:r=[],isLoading:a}=Je({queryKey:["inventory-spools"],queryFn:()=>ne.getSpools(!1)}),s=w.useMemo(()=>{if(!e.trim())return r;const o=e.toLowerCase();return r.filter(l=>l.material.toLowerCase().includes(o)||l.brand?.toLowerCase().includes(o)||l.color_name?.toLowerCase().includes(o))},[r,e]);return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100",children:t("spoolbuddy.nav.inventory","Inventory")}),i.jsxs("span",{className:"text-sm text-zinc-500",children:[r.length," ",t("spoolbuddy.inventory.spools","spools")]})]}),i.jsxs("div",{className:"relative mb-4",children:[i.jsx("svg",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),i.jsx("input",{type:"text",value:e,onChange:o=>n(o.target.value),placeholder:t("spoolbuddy.inventory.search","Search spools..."),className:"w-full pl-10 pr-4 py-2.5 bg-zinc-800 border border-zinc-700 rounded-lg text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none focus:border-green-500 min-h-[44px]"})]}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:a?i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("span",{className:"text-zinc-500",children:t("common.loading","Loading...")})}):s.length===0?i.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-zinc-500",children:[i.jsx("svg",{className:"w-10 h-10 mb-2 opacity-50",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:i.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),i.jsx("p",{className:"text-sm",children:e?t("spoolbuddy.inventory.noResults","No matching spools"):t("spoolbuddy.inventory.empty","No spools in inventory")})]}):s.map(o=>i.jsx(Fet,{spool:o},o.id))})]})}function Oet(t){if(t<60)return`${t}s`;if(t<3600)return`${Math.floor(t/60)}m`;const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return`${e}h ${n}m`}function Iet({device:t,weight:e,weightStable:n,rawAdc:r}){const{t:a}=Rt(),[s,o]=w.useState(!1),[l,c]=w.useState("idle"),[u,d]=w.useState(500),[h,f]=w.useState(!1),p=async()=>{f(!0);try{await Kg.tare(t.device_id)}catch(g){console.error("Failed to tare:",g)}finally{f(!1)}},x=()=>{c("tare")},v=async()=>{if(l==="tare"){o(!0);try{await Kg.tare(t.device_id),c("weight")}catch(g){console.error("Failed to tare:",g)}finally{o(!1)}}else if(l==="weight"){if(r===null)return;o(!0);try{await Kg.setCalibrationFactor(t.device_id,u,r),c("idle")}catch(g){console.error("Failed to calibrate:",g)}finally{o(!1)}}};return i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-100 mb-4",children:a("spoolbuddy.settings.scaleCalibration","Scale Calibration")}),i.jsxs("div",{className:"flex items-center justify-between mb-3",children:[i.jsx("span",{className:"text-sm text-zinc-400",children:a("spoolbuddy.settings.currentWeight","Current weight")}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${n?"bg-green-500":"bg-amber-500 animate-pulse"}`}),i.jsx("span",{className:"text-sm font-mono text-zinc-200",children:e!==null?`${e.toFixed(1)} g`:"-- g"})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-4 mb-4 text-xs",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.tareOffset","Tare offset")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.tare_offset})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:a("spoolbuddy.settings.calFactor","Cal. factor")}),i.jsx("span",{className:"text-zinc-400 font-mono",children:t.calibration_factor.toFixed(2)})]})]}),l==="idle"?i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:p,disabled:h,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-zinc-700 text-zinc-200 hover:bg-zinc-600 disabled:opacity-40 transition-colors min-h-[44px]",children:h?"...":a("spoolbuddy.weight.tare","Tare")}),i.jsx("button",{onClick:x,className:"flex-1 px-4 py-2.5 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 transition-colors min-h-[44px]",children:a("spoolbuddy.weight.calibrate","Calibrate")})]}):i.jsxs("div",{className:"border border-zinc-700 rounded-lg p-3 space-y-3",children:[i.jsx("div",{className:"text-sm font-medium text-zinc-200",children:l==="tare"?a("spoolbuddy.settings.calStep1","Step 1: Remove all items from the scale"):a("spoolbuddy.settings.calStep2","Step 2: Place known weight on scale")}),l==="weight"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("label",{className:"text-xs text-zinc-400",children:a("spoolbuddy.settings.knownWeight","Known weight (g)")}),i.jsx("input",{type:"number",value:u,onChange:g=>d(Number(g.target.value)),className:"w-24 px-2 py-1.5 bg-zinc-900 border border-zinc-600 rounded text-sm text-zinc-100 focus:outline-none focus:border-green-500",min:1})]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx("button",{onClick:()=>c("idle"),className:"flex-1 px-4 py-2 rounded-lg text-sm bg-zinc-700 text-zinc-300 hover:bg-zinc-600 transition-colors min-h-[40px]",children:a("common.cancel","Cancel")}),i.jsx("button",{onClick:v,disabled:s,className:"flex-1 px-4 py-2 rounded-lg text-sm font-medium bg-green-600 text-white hover:bg-green-700 disabled:opacity-40 transition-colors min-h-[40px]",children:s?"...":l==="tare"?a("spoolbuddy.settings.setZero","Set Zero"):a("spoolbuddy.settings.calibrateNow","Calibrate")})]})]})]})}function zet({device:t}){const{t:e}=Rt();return i.jsxs("div",{className:"bg-zinc-800 rounded-lg p-4",children:[i.jsx("h3",{className:"text-sm font-semibold text-zinc-100 mb-4",children:e("spoolbuddy.settings.deviceInfo","Device Info")}),i.jsxs("div",{className:"space-y-2 text-sm",children:[i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"Device ID"}),i.jsx("span",{className:"text-zinc-300 font-mono text-xs",children:t.device_id})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.hostname","Hostname")}),i.jsx("span",{className:"text-zinc-300",children:t.hostname})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"IP"}),i.jsx("span",{className:"text-zinc-300",children:t.ip_address})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.firmware","Firmware")}),i.jsx("span",{className:"text-zinc-300",children:t.firmware_version??"-"})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:"NFC"}),i.jsx("span",{className:t.nfc_ok?"text-green-400":"text-zinc-500",children:t.nfc_ok?e("spoolbuddy.status.nfcReady","Ready"):e("spoolbuddy.status.nfcOff","Off")})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.scale","Scale")}),i.jsx("span",{className:t.scale_ok?"text-green-400":"text-red-400",children:t.scale_ok?"OK":e("common.error","Error")})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.settings.uptime","Uptime")}),i.jsx("span",{className:"text-zinc-300",children:Oet(t.uptime_s)})]}),i.jsxs("div",{className:"flex justify-between",children:[i.jsx("span",{className:"text-zinc-500",children:e("spoolbuddy.status.status","Status")}),i.jsx("span",{className:t.online?"text-green-400":"text-zinc-500",children:t.online?e("spoolbuddy.status.online","Online"):e("spoolbuddy.status.offline","Offline")})]})]})]})}function Uet(){const{sbState:t}=uF(),{t:e}=Rt(),{data:n=[]}=Je({queryKey:["spoolbuddy-devices"],queryFn:()=>Kg.getDevices(),refetchInterval:1e4}),r=t.deviceId?n.find(a=>a.device_id===t.deviceId)??n[0]:n[0];return i.jsxs("div",{className:"h-full flex flex-col p-4",children:[i.jsx("h1",{className:"text-lg font-semibold text-zinc-100 mb-4",children:e("spoolbuddy.nav.settings","Settings")}),i.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-4",children:r?i.jsxs(i.Fragment,{children:[i.jsx(Iet,{device:r,weight:t.weight,weightStable:t.weightStable,rawAdc:t.rawAdc}),i.jsx(zet,{device:r})]}):i.jsx("div",{className:"flex items-center justify-center h-32",children:i.jsx("div",{className:"text-center text-zinc-500",children:i.jsx("p",{className:"text-sm",children:e("spoolbuddy.settings.noDevice","No SpoolBuddy device found")})})})})]})}const Bet=new gde({defaultOptions:{queries:{staleTime:1e3*60,retry:1}}});function fK({children:t}){return fet(),i.jsx(i.Fragment,{children:t})}function pK({children:t}){const{authEnabled:e,loading:n,user:r}=Ir();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e&&!r?i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Ij({children:t}){const{authEnabled:e,loading:n,user:r,isAdmin:a}=Ir();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(ob,{to:"/",replace:!0}):i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function Het({children:t}){const{authEnabled:e,loading:n}=Ir();return n?i.jsx("div",{className:"min-h-screen flex items-center justify-center",children:"Loading..."}):e?i.jsx(ob,{to:"/login",replace:!0}):i.jsx(i.Fragment,{children:t})}function $et(){return i.jsx(dge,{children:i.jsx(yge,{children:i.jsx(bde,{client:Bet,children:i.jsx(bge,{children:i.jsx(Lue,{children:i.jsxs(due,{children:[i.jsx(jr,{path:"/setup",element:i.jsx(Het,{children:i.jsx(met,{})})}),i.jsx(jr,{path:"/login",element:i.jsx(het,{})}),i.jsx(jr,{path:"/camera/:printerId",element:i.jsx(_Je,{})}),i.jsx(jr,{path:"/overlay/:printerId",element:i.jsx(AJe,{})}),i.jsxs(jr,{element:i.jsx(pK,{children:i.jsx(fK,{children:i.jsx(wet,{})})}),children:[i.jsx(jr,{path:"spoolbuddy",element:i.jsx(Met,{})}),i.jsx(jr,{path:"spoolbuddy/ams",element:i.jsx(Det,{})}),i.jsx(jr,{path:"spoolbuddy/inventory",element:i.jsx(Let,{})}),i.jsx(jr,{path:"spoolbuddy/settings",element:i.jsx(Uet,{})})]}),i.jsxs(jr,{element:i.jsx(pK,{children:i.jsx(fK,{children:i.jsx(_ge,{})})}),children:[i.jsx(jr,{index:!0,element:i.jsx(S$e,{})}),i.jsx(jr,{path:"archives",element:i.jsx(cYe,{})}),i.jsx(jr,{path:"queue",element:i.jsx(WQe,{})}),i.jsx(jr,{path:"stats",element:i.jsx(oZe,{})}),i.jsx(jr,{path:"profiles",element:i.jsx(ZZe,{})}),i.jsx(jr,{path:"maintenance",element:i.jsx(rJe,{})}),i.jsx(jr,{path:"projects",element:i.jsx(iJe,{})}),i.jsx(jr,{path:"projects/:id",element:i.jsx(hJe,{})}),i.jsx(jr,{path:"inventory",element:i.jsx(ret,{})}),i.jsx(jr,{path:"files",element:i.jsx(yJe,{})}),i.jsx(jr,{path:"settings",element:i.jsx(Ij,{children:i.jsx(IZe,{})})}),i.jsx(jr,{path:"groups/new",element:i.jsx(Ij,{children:i.jsx(iK,{})})}),i.jsx(jr,{path:"groups/:id/edit",element:i.jsx(Ij,{children:i.jsx(iK,{})})}),i.jsx(jr,{path:"users",element:i.jsx(ob,{to:"/settings?tab=users",replace:!0})}),i.jsx(jr,{path:"groups",element:i.jsx(ob,{to:"/settings?tab=users",replace:!0})}),i.jsx(jr,{path:"system",element:i.jsx(det,{})}),i.jsx(jr,{path:"external/:id",element:i.jsx(MJe,{})})]})]})})})})})})}ole.createRoot(document.getElementById("root")).render(i.jsx(w.StrictMode,{children:i.jsx($et,{})})); diff --git a/static/index.html b/static/index.html index 158ee960e..55901f6a7 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +