diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d955c3a1..31c002c99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to Bambuddy will be documented in this file. ## [0.2.2b3] - Unreleased +### New Features +- **Malaysian Ringgit Currency** ([#634](https://github.com/maziggy/bambuddy/issues/634)) — Added MYR (RM) to the list of supported currencies for filament cost tracking. Requested by @cynogen127. + +### Improved +- **Separate Permission for AMS Spool Assignments** ([#635](https://github.com/maziggy/bambuddy/issues/635)) — Added a new `inventory:view_assignments` permission that controls whether spool-to-AMS-slot assignment data is visible on the Printers page. Previously, viewing spool assignments on printer cards required `inventory:read`, which also exposed the full Inventory page in the sidebar. Admins can now grant `inventory:view_assignments` without `inventory:read` so users can see what's loaded in the AMS without accessing the full spool inventory. All default groups (Administrators, Operators, Viewers) include the new permission automatically. Also fixed multi-word permission labels in the group editor (e.g. "Update_Own" → "Update Own"). Reported by @Minebuddy. + ### Fixed - **Dispatch Toast Stuck After Second Print** — The print dispatch progress toast ("Starting prints…") stayed visible forever after the second print dispatch in a session. The dedup guard (`lastDispatchSummaryRef`) that prevents duplicate completion toasts was never reset between batches, so every single-printer dispatch produced the same summary key (`"first-complete:1:0"`). The first print completed normally, but subsequent completions matched the stale ref and skipped creating the done toast — leaving the progress toast stuck in "Processing" state with no way to dismiss except a page reload. Now resets the dedup guard whenever the dispatch toast is dismissed (auto-dismiss timeout, cleanup events) and when a new batch starts. diff --git a/README.md b/README.md index 2ad579ed0..064793eee 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,7 @@ Perfect for remote print farms, traveling makers, or accessing your home printer ### 🔒 Optional Authentication - Enable/disable authentication any time -- Group-based permissions (50+ granular permissions) +- Group-based permissions (80+ granular permissions) - Default groups: Administrators, Operators, Viewers - JWT tokens with secure password hashing - Comprehensive API protection (200+ endpoints secured) diff --git a/backend/app/api/routes/groups.py b/backend/app/api/routes/groups.py index 926489c08..54f1c16a1 100644 --- a/backend/app/api/routes/groups.py +++ b/backend/app/api/routes/groups.py @@ -35,7 +35,7 @@ def _permission_label(perm: Permission) -> str: if len(parts) == 2: resource, action = parts resource = resource.replace("_", " ").title() - action = action.title() + action = action.replace("_", " ").title() return f"{action} {resource}" return perm.value diff --git a/backend/app/api/routes/inventory.py b/backend/app/api/routes/inventory.py index 3ca2b7635..9478f60bb 100644 --- a/backend/app/api/routes/inventory.py +++ b/backend/app/api/routes/inventory.py @@ -636,7 +636,7 @@ async def replace_k_profiles( async def list_assignments( printer_id: int | None = None, db: AsyncSession = Depends(get_db), - _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_READ), + _: User | None = RequirePermissionIfAuthEnabled(Permission.INVENTORY_VIEW_ASSIGNMENTS), ): """List spool assignments, optionally filtered by printer.""" from backend.app.services.printer_manager import printer_manager diff --git a/backend/app/core/permissions.py b/backend/app/core/permissions.py index 29f1aab0a..91183ce8d 100644 --- a/backend/app/core/permissions.py +++ b/backend/app/core/permissions.py @@ -68,6 +68,7 @@ class Permission(StrEnum): INVENTORY_CREATE = "inventory:create" INVENTORY_UPDATE = "inventory:update" INVENTORY_DELETE = "inventory:delete" + INVENTORY_VIEW_ASSIGNMENTS = "inventory:view_assignments" # View spool-to-AMS assignments on printer cards # Smart Plugs SMART_PLUGS_READ = "smart_plugs:read" @@ -214,6 +215,7 @@ PERMISSION_CATEGORIES = { Permission.INVENTORY_CREATE, Permission.INVENTORY_UPDATE, Permission.INVENTORY_DELETE, + Permission.INVENTORY_VIEW_ASSIGNMENTS, ], "Smart Plugs": [ Permission.SMART_PLUGS_READ, @@ -355,6 +357,7 @@ DEFAULT_GROUPS = { Permission.INVENTORY_CREATE.value, Permission.INVENTORY_UPDATE.value, Permission.INVENTORY_DELETE.value, + Permission.INVENTORY_VIEW_ASSIGNMENTS.value, # Smart Plugs - full access Permission.SMART_PLUGS_READ.value, Permission.SMART_PLUGS_CREATE.value, @@ -411,6 +414,7 @@ DEFAULT_GROUPS = { Permission.PROJECTS_READ.value, Permission.FILAMENTS_READ.value, Permission.INVENTORY_READ.value, + Permission.INVENTORY_VIEW_ASSIGNMENTS.value, Permission.SMART_PLUGS_READ.value, Permission.CAMERA_VIEW.value, Permission.MAINTENANCE_READ.value, diff --git a/backend/tests/unit/test_permissions.py b/backend/tests/unit/test_permissions.py index caa8c7156..b49066e37 100644 --- a/backend/tests/unit/test_permissions.py +++ b/backend/tests/unit/test_permissions.py @@ -74,3 +74,41 @@ class TestPermissionCategoriesCompleteness: for perm in perms: assert perm not in seen, f"{perm} in both '{seen[perm]}' and '{cat_name}'" seen[perm] = cat_name + + +class TestInventoryViewAssignmentsPermission: + """Test the INVENTORY_VIEW_ASSIGNMENTS permission.""" + + def test_view_assignments_permission_exists(self): + """inventory:view_assignments permission should exist in the enum.""" + assert hasattr(Permission, "INVENTORY_VIEW_ASSIGNMENTS") + assert Permission.INVENTORY_VIEW_ASSIGNMENTS == "inventory:view_assignments" + + def test_view_assignments_in_all_permissions(self): + """inventory:view_assignments should be in ALL_PERMISSIONS list.""" + assert "inventory:view_assignments" in ALL_PERMISSIONS + + def test_view_assignments_in_inventory_category(self): + """inventory:view_assignments should be in the Inventory permission category.""" + inventory_perms = PERMISSION_CATEGORIES["Inventory"] + assert Permission.INVENTORY_VIEW_ASSIGNMENTS in inventory_perms + + def test_view_assignments_separate_from_read(self): + """view_assignments and read should be distinct permissions.""" + assert Permission.INVENTORY_VIEW_ASSIGNMENTS != Permission.INVENTORY_READ + assert Permission.INVENTORY_VIEW_ASSIGNMENTS.value != Permission.INVENTORY_READ.value + + def test_operators_have_view_assignments(self): + """Operators group should include inventory:view_assignments.""" + operators = DEFAULT_GROUPS["Operators"] + assert "inventory:view_assignments" in operators["permissions"] + + def test_viewers_have_view_assignments(self): + """Viewers group should include inventory:view_assignments.""" + viewers = DEFAULT_GROUPS["Viewers"] + assert "inventory:view_assignments" in viewers["permissions"] + + def test_administrators_have_view_assignments(self): + """Administrators should have all permissions including view_assignments.""" + admins = DEFAULT_GROUPS["Administrators"] + assert "inventory:view_assignments" in admins["permissions"] diff --git a/frontend/src/__tests__/utils/currency.test.ts b/frontend/src/__tests__/utils/currency.test.ts index 6bbab097b..25cff52aa 100644 --- a/frontend/src/__tests__/utils/currency.test.ts +++ b/frontend/src/__tests__/utils/currency.test.ts @@ -22,6 +22,10 @@ describe('getCurrencySymbol', () => { expect(getCurrencySymbol('HKD')).toBe('HK$'); }); + it('returns RM for MYR', () => { + expect(getCurrencySymbol('MYR')).toBe('RM'); + }); + it('returns the code itself for unknown currencies', () => { expect(getCurrencySymbol('XYZ')).toBe('XYZ'); }); @@ -37,7 +41,11 @@ describe('SUPPORTED_CURRENCIES', () => { expect(SUPPORTED_CURRENCIES.find((c) => c.code === 'INR')).toBeDefined(); }); - it('has 26 entries', () => { - expect(SUPPORTED_CURRENCIES).toHaveLength(26); + it('contains MYR', () => { + expect(SUPPORTED_CURRENCIES.find((c) => c.code === 'MYR')).toBeDefined(); + }); + + it('has 27 entries', () => { + expect(SUPPORTED_CURRENCIES).toHaveLength(27); }); }); diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 6a55ae269..9938180d4 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -2023,7 +2023,7 @@ export type Permission = | 'library:update_own' | 'library:update_all' | 'library:delete_own' | 'library:delete_all' | 'projects:read' | 'projects:create' | 'projects:update' | 'projects:delete' | 'filaments:read' | 'filaments:create' | 'filaments:update' | 'filaments:delete' - | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' + | 'inventory:read' | 'inventory:create' | 'inventory:update' | 'inventory:delete' | 'inventory:view_assignments' | 'smart_plugs:read' | 'smart_plugs:create' | 'smart_plugs:update' | 'smart_plugs:delete' | 'smart_plugs:control' | 'camera:view' | 'maintenance:read' | 'maintenance:create' | 'maintenance:update' | 'maintenance:delete' diff --git a/frontend/src/pages/PrintersPage.tsx b/frontend/src/pages/PrintersPage.tsx index d477cc50d..3390dafb9 100644 --- a/frontend/src/pages/PrintersPage.tsx +++ b/frontend/src/pages/PrintersPage.tsx @@ -1337,7 +1337,7 @@ export function AmsNameHoverCard({ }); } }, [isVisible, amsLabels, ams.id]); - + const handleMouseEnter = () => { if (timeoutRef.current) clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => setIsVisible(true), 80); @@ -5368,6 +5368,7 @@ export function PrintersPage() { const { data: spoolAssignments } = useQuery({ queryKey: ['spool-assignments'], queryFn: () => api.getAssignments(), + enabled: hasPermission('inventory:view_assignments'), staleTime: 30 * 1000, }); diff --git a/static/assets/index-DCHZw0ab.js b/static/assets/index-BpZJje_K.js similarity index 98% rename from static/assets/index-DCHZw0ab.js rename to static/assets/index-BpZJje_K.js index 994191549..4e226eddc 100644 --- a/static/assets/index-DCHZw0ab.js +++ b/static/assets/index-BpZJje_K.js @@ -8533,7 +8533,7 @@ void main() { flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${nn&&C("printers:control")?It?"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green/30":"bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"} - `,title:C("printers:control")?g(It?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[It?i.jsx(uo,{className:"w-3 h-3"}):i.jsx(hC,{className:"w-3 h-3"}),g(It?"printers.resume":"printers.pause")]})]})]})]})})(),(Fn?.length>0||we.vt_tray.length>0)&&r==="expanded"&&(()=>{const bt=Fn.filter(Nt=>Nt.tray.length>1),It=Fn.filter(Nt=>Nt.tray.length===1),nn=t.nozzle_count===2||we?.temperatures?.nozzle_2!==void 0;return i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:g("printers.filaments")}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),i.jsxs("div",{className:"space-y-3",children:[bt.length>0&&i.jsx("div",{className:"grid grid-cols-2 gap-3",children:bt.map(Nt=>{const wn=Rn[String(Nt.id)],Nr=Nt.id>=128?Nt.id-128:Nt.id,$t=wn!==void 0?wn:Nr,vr=$t===1,xi=$t===0;return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(DG,{ams:Nt,printerId:t.id,label:Cc(Nt.id,Nt.tray.length),amsLabels:ht,canEdit:C("printers:update"),onSaved:ft,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:ht?.[Nt.id]||Cc(Nt.id,Nt.tray.length)})}),nn&&(vr||xi)&&i.jsx(AG,{side:vr?"L":"R"})]}),(Nt.humidity!=null||Nt.temp!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[Nt.humidity!=null&&i.jsx(EG,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0}),Nt.temp!=null&&i.jsx(jG,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(rn=>{const Ln=Nt.tray[rn]||Nt.tray.find(Fr=>Fr.id===rn),Ho=Ln?.tray_type&&Ln.remain>=0,Gs=!Ln?.tray_type,bo=Nt.id*4+rn,Se=Je===bo,Dt=Ln?.tray_info_idx?kt?.[Ln.tray_info_idx]:null,sr=qe?.[bo],hr=Ln?.tray_uuid?.toUpperCase(),Ti=hr?c?.[hr]:void 0,Ua=uj(Ti),Xi=u?.(t.id,Nt.id,rn),Wn=(()=>{const Fr=Xi?.spool;return Fr&&Fr.label_weight>0&&Fr.weight_used!=null?Math.round(Math.max(0,Fr.label_weight-Fr.weight_used)/Fr.label_weight*100):null})(),Cs=Ua??Wn??(Ho?Ln.remain:null),Pf=Ua!==null?"spoolman":Wn!==null?"inventory":Ho?"ams":void 0,yi=Ln?.tray_type?{vendor:mj(Ln)?"Bambu Lab":"Generic",profile:Dt?.name||sr?.preset_name||Ln.tray_sub_brands||Ln.tray_type,colorName:oj(Ln.tray_id_name)||N1(Ln.tray_color),colorHex:Ln.tray_color||null,kFactor:lj(Ln.k),fillLevel:Cs,trayUuid:Ln.tray_uuid||null,tagUid:Ln.tag_uid||null,fillSource:Pf}:null,Ba=yr?.amsId===Nt.id&&yr?.slotId===rn,sd=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Gs?"opacity-50":""} ${Se?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(sj,{trayColor:Ln?.tray_color,trayType:Ln?.tray_type,isEmpty:Gs,slotNumber:rn+1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Ln?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Cs!==null&&Cs>=0&&Ln&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Cs}%`,backgroundColor:dj(Cs)}})})]});return i.jsxs("div",{className:"relative group",children:[Ba&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),we?.state!=="RUNNING"&&i.jsx("button",{onClick:Fr=>{Fr.stopPropagation(),Vs(ks?.amsId===Nt.id&&ks?.slotId===rn?null:{amsId:Nt.id,slotId:rn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Bm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),we?.state!=="RUNNING"&&ks?.amsId===Nt.id&&ks?.slotId===rn&&i.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 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-xs flex items-center gap-2 ${C("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Fr=>{Fr.stopPropagation(),C("printers:ams_rfid")&&(fi.mutate({amsId:Nt.id,slotId:rn}),Vs(null))},disabled:Ba||!C("printers:ams_rfid"),title:C("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${Ba?"animate-spin":""}`}),g("printers.rfid.reread")]})}),yi?i.jsx(ij,{data:yi,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:yi.trayUuid?c?.[yi.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&yi.trayUuid?Fr=>{xe({tagUid:yi.tagUid||"",trayUuid:Fr,printerId:t.id,amsId:Nt.id,trayId:rn})}:void 0},inventory:o?void 0:(()=>{const Fr=u?.(t.id,Nt.id,rn);return{assignedSpool:Fr?.spool?{id:Fr.spool.id,material:Fr.spool.material,brand:Fr.spool.brand,color_name:Fr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Fr.spool.label_weight-Fr.spool.weight_used))}:null,onAssignSpool:yi.vendor!=="Bambu Lab"?()=>de({printerId:t.id,amsId:Nt.id,trayId:rn,trayInfo:{type:yi.profile,color:yi.colorHex||"",location:`${Cc(Nt.id,Nt.tray.length)} Slot ${rn+1}`}}):void 0,onUnassignSpool:Fr&&yi.vendor!=="Bambu Lab"?()=>m?.(t.id,Nt.id,rn):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:rn,trayCount:Nt.tray.length,trayType:Ln?.tray_type||void 0,trayColor:Ln?.tray_color||void 0,traySubBrands:Ln?.tray_sub_brands||void 0,trayInfoIdx:Ln?.tray_info_idx||void 0,extruderId:wn,caliIdx:Ln?.cali_idx,savedPresetId:sr?.preset_id})},children:sd}):i.jsx(aj,{configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:rn,trayCount:Nt.tray.length,extruderId:wn})},children:sd})]},rn)})})]},Nt.id)})}),(It.length>0||we.vt_tray.length>0)&&i.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[It.map(Nt=>{const wn=Rn[String(Nt.id)],Nr=Nt.id>=128?Nt.id-128:Nt.id,$t=wn!==void 0?wn:Nr,vr=$t===1,xi=$t===0,rn=Nt.tray[0],Ln=rn?.tray_type&&rn.remain>=0,Ho=!rn?.tray_type,Gs=sk(Nt.id,rn?.id??0,!1),bo=Je===Gs,Se=rn?.tray_info_idx?kt?.[rn.tray_info_idx]:null,Dt=qe?.[Gs],sr=rn?.tray_uuid?.toUpperCase(),hr=sr?c?.[sr]:void 0,Ti=uj(hr),Ua=rn?.id??0,Xi=u?.(t.id,Nt.id,Ua),Wn=(()=>{const vi=Xi?.spool;return vi&&vi.label_weight>0&&vi.weight_used!=null?Math.round(Math.max(0,vi.label_weight-vi.weight_used)/vi.label_weight*100):null})(),Cs=Ti??Wn??(Ln?rn.remain:null),Pf=Ti!==null?"spoolman":Wn!==null?"inventory":Ln?"ams":void 0,yi=rn?.tray_type?{vendor:mj(rn)?"Bambu Lab":"Generic",profile:Se?.name||Dt?.preset_name||rn.tray_sub_brands||rn.tray_type,colorName:oj(rn.tray_id_name)||N1(rn.tray_color),colorHex:rn.tray_color||null,kFactor:lj(rn.k),fillLevel:Cs,trayUuid:rn.tray_uuid||null,tagUid:rn.tag_uid||null,fillSource:Pf}:null,Ba=rn?.id??0,sd=yr?.amsId===Nt.id&&yr?.slotId===Ba,Fr=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ho?"opacity-50":""} ${bo?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(sj,{trayColor:rn?.tray_color,trayType:rn?.tray_type,isEmpty:Ho,slotNumber:1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:rn?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Cs!==null&&Cs>=0&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Cs}%`,backgroundColor:dj(Cs)}})})]});return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[i.jsx(DG,{ams:Nt,printerId:t.id,label:Cc(Nt.id,Nt.tray.length),amsLabels:ht,canEdit:C("printers:update"),onSaved:ft,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:ht?.[Nt.id]||Cc(Nt.id,Nt.tray.length)})}),nn&&(vr||xi)&&i.jsx(AG,{side:vr?"L":"R"})]}),i.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[i.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[sd&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),we?.state!=="RUNNING"&&i.jsx("button",{onClick:vi=>{vi.stopPropagation(),Vs(ks?.amsId===Nt.id&&ks?.slotId===Ba?null:{amsId:Nt.id,slotId:Ba})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Bm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),we?.state!=="RUNNING"&&ks?.amsId===Nt.id&&ks?.slotId===Ba&&i.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 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-xs flex items-center gap-2 ${C("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:vi=>{vi.stopPropagation(),C("printers:ams_rfid")&&(fi.mutate({amsId:Nt.id,slotId:Ba}),Vs(null))},disabled:sd||!C("printers:ams_rfid"),title:C("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${sd?"animate-spin":""}`}),g("printers.rfid.reread")]})}),yi?i.jsx(ij,{data:yi,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:yi.trayUuid?c?.[yi.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&yi.trayUuid?vi=>{xe({tagUid:yi.tagUid||"",trayUuid:vi,printerId:t.id,amsId:Nt.id,trayId:Ba})}:void 0},inventory:o?void 0:(()=>{const vi=u?.(t.id,Nt.id,Ba);return{assignedSpool:vi?.spool?{id:vi.spool.id,material:vi.spool.material,brand:vi.spool.brand,color_name:vi.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(vi.spool.label_weight-vi.spool.weight_used))}:null,onAssignSpool:yi.vendor!=="Bambu Lab"?()=>de({printerId:t.id,amsId:Nt.id,trayId:Ba,trayInfo:{type:yi.profile,color:yi.colorHex||"",location:Cc(Nt.id,Nt.tray.length)}}):void 0,onUnassignSpool:vi&&yi.vendor!=="Bambu Lab"?()=>m?.(t.id,Nt.id,Ba):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:Ba,trayCount:Nt.tray.length,trayType:rn?.tray_type||void 0,trayColor:rn?.tray_color||void 0,traySubBrands:rn?.tray_sub_brands||void 0,trayInfoIdx:rn?.tray_info_idx||void 0,extruderId:wn,caliIdx:rn?.cali_idx,savedPresetId:Dt?.preset_id})},children:Fr}):i.jsx(aj,{configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:Ba,trayCount:Nt.tray.length,extruderId:wn})},children:Fr})]}),(Nt.humidity!=null||Nt.temp!=null)&&i.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[Nt.temp!=null&&i.jsx(jG,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0}),Nt.humidity!=null&&i.jsx(EG,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0})]})]})]},Nt.id)}),we.vt_tray.length>0&&i.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${we.vt_tray.length===1?"max-w-[50%]":""}`,children:[i.jsx("div",{className:"flex items-center gap-1 mb-2",children:i.jsx("span",{className:"text-[10px] text-white font-medium",children:g("printers.external")})}),i.jsx("div",{className:`grid ${we.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...we.vt_tray].sort((Nt,wn)=>(Nt.id??254)-(wn.id??254)).map(Nt=>{const wn=Nt.id??254,Nr=nn&&Je===254?wn===254&&we.active_extruder===1||wn===255&&we.active_extruder===0:Je===wn,$t=wn-254,vr=nn?g(wn===254?"printers.extL":"printers.extR"):"",xi=Nt.tray_info_idx?kt?.[Nt.tray_info_idx]:null,rn=qe?.[1020+$t],Ln=Nt.tray_uuid?.toUpperCase(),Ho=Ln?c?.[Ln]:void 0,Gs=uj(Ho),bo=u?.(t.id,255,$t),Se=(()=>{const Wn=bo?.spool;return Wn&&Wn.label_weight>0&&Wn.weight_used!=null?Math.round(Math.max(0,Wn.label_weight-Wn.weight_used)/Wn.label_weight*100):null})(),Dt=Nt.tray_type&&Nt.remain>=0,sr=Gs??Se??(Dt?Nt.remain:null),hr=Gs!==null?"spoolman":Se!==null?"inventory":Dt?"ams":void 0,Ti={vendor:mj(Nt)?"Bambu Lab":"Generic",profile:xi?.name||rn?.preset_name||Nt.tray_sub_brands||Nt.tray_type||"Unknown",colorName:oj(Nt.tray_id_name)||N1(Nt.tray_color),colorHex:Nt.tray_color||null,kFactor:lj(Nt.k),fillLevel:sr,trayUuid:Nt.tray_uuid||null,tagUid:Nt.tag_uid||null,fillSource:hr},Ua=!Nt.tray_type,Xi=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ua?"opacity-50":""} ${Nr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(sj,{trayColor:Nt.tray_color,trayType:Nt.tray_type,isEmpty:Ua,slotNumber:$t+1}),i.jsx("div",{className:`text-[9px] font-bold truncate ${Ua?"text-white/40":"text-white"}`,children:Nt.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:sr!==null&&sr>=0&&!Ua&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${sr}%`,backgroundColor:dj(sr)}})}),vr&&i.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:vr})]});return i.jsx("div",{className:"relative group",children:Ua?i.jsx(aj,{configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:255,trayId:$t,trayCount:1,extruderId:nn?wn===254?1:0:void 0})},children:Xi}):i.jsx(ij,{data:Ti,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Ti.trayUuid?c?.[Ti.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Ti.trayUuid?Wn=>{xe({tagUid:Ti.tagUid||"",trayUuid:Wn,printerId:t.id,amsId:255,trayId:$t})}:void 0},inventory:o?void 0:(()=>{const Wn=u?.(t.id,255,$t);return{assignedSpool:Wn?.spool?{id:Wn.spool.id,material:Wn.spool.material,brand:Wn.spool.brand,color_name:Wn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Wn.spool.label_weight-Wn.spool.weight_used))}:null,onAssignSpool:()=>de({printerId:t.id,amsId:255,trayId:$t,trayInfo:{type:Ti.profile,color:Ti.colorHex||"",location:vr||g("printers.external")}}),onUnassignSpool:Wn?()=>m?.(t.id,255,$t):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:255,trayId:$t,trayCount:1,trayType:Nt.tray_type||void 0,trayColor:Nt.tray_color||void 0,traySubBrands:Nt.tray_sub_brands||void 0,trayInfoIdx:Nt.tray_info_idx||void 0,extruderId:nn?wn===254?1:0:void 0,caliIdx:Nt.cali_idx,savedPresetId:rn?.preset_id})},children:Xi})},wn)})})]})]})]})]})})()]}),tt&&r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx(ac,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"text-sm text-white truncate",children:tt.name}),Rt&&i.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Rt.state==="ON"?"bg-bambu-green/20 text-bambu-green":Rt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Rt.state||"?",Rt.state==="ON"&&Rt.energy?.power!=null&&i.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Rt.energy.power,"W"]})]})]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{onClick:()=>le(!0),disabled:jt.isPending||Rt?.state==="ON"||!C("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${C("smart_plugs:control")?Rt?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:C("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(Su,{className:"w-3 h-3"}),"On"]}),i.jsxs("button",{onClick:()=>he(!0),disabled:jt.isPending||Rt?.state==="OFF"||!C("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${C("smart_plugs:control")?Rt?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:C("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(pC,{className:"w-3 h-3"}),"Off"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx("span",{className:`text-xs hidden sm:inline ${tt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:tt.auto_off_executed?"Auto-off done":"Auto-off"}),i.jsx("button",{onClick:()=>Ft.mutate(!tt.auto_off),disabled:Ft.isPending||tt.auto_off_executed||!C("smart_plugs:control"),title:C("smart_plugs:control")?tt.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${C("smart_plugs:control")?tt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":tt.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:i.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${tt.auto_off||tt.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Ye&&Ye.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[i.jsx(j0,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Ye.map(bt=>i.jsxs("button",{onClick:()=>cn.mutate(bt.id),disabled:cn.isPending,title:`Run ${bt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[i.jsx(uo,{className:"w-2.5 h-2.5"}),bt.name]},bt.id))})]})]}),r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[i.jsx(Oe,{variant:"secondary",size:"sm",onClick:()=>In.mutate(!we?.chamber_light),disabled:!we?.connected||In.isPending||!C("printers:control"),title:C("printers:control")?we?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:we?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:i.jsx(ML,{on:we?.chamber_light??!1,className:`w-4 h-4 ${we?.chamber_light?"text-yellow-400":""}`})}),i.jsx(Oe,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&x)x(t.id,t.name);else{const bt=localStorage.getItem("cameraWindowState"),It=bt?JSON.parse(bt):{width:640,height:400},nn=[`width=${It.width}`,`height=${It.height}`,It.left!==void 0?`left=${It.left}`:"",It.top!==void 0?`top=${It.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,nn)}},disabled:!we?.connected||!C("camera:view"),title:C("camera:view")?g(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):g("printers.permission.noCamera"),children:i.jsx(ZF,{className:"w-4 h-4"})}),i.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[i.jsx(Oe,{variant:"secondary",size:"sm",onClick:_h,disabled:!we?.connected||Xt.isPending||!C("printers:update"),title:C("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Xt.isPending?i.jsx(lt,{className:"w-4 h-4 animate-spin"}):i.jsx(V1,{className:"w-4 h-4"})}),i.jsx(Oe,{variant:"secondary",size:"sm",onClick:kf,disabled:!we?.connected||Me||!C("printers:update"),title:C("printers:update")?g("printers.plateDetection.manageCalibration"):g("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Me?i.jsx(lt,{className:"w-3 h-3 animate-spin"}):i.jsx(jn,{className:"w-3 h-3"})})]}),i.jsxs(Oe,{variant:"secondary",size:"sm",onClick:()=>O(!0),disabled:!on||!C("printers:files"),title:C("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[i.jsx(cx,{className:"w-4 h-4"}),g("printers.files")]}),on&&we?.state!=="RUNNING"&&we?.state!=="PAUSE"&&i.jsxs(Oe,{size:"sm",onClick:()=>B(!0),disabled:!C("printers:control"),title:C("printers:control")?g("common.print"):g("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[i.jsx(_r,{className:"w-4 h-4"}),g("common.print")]})]})]}),W&&i.jsx(gAe,{printerId:t.id,printerName:t.name,onClose:()=>O(!1)}),G&&i.jsx(Yne,{folderId:null,onClose:()=>B(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:bt=>{const It=bt.name.toLowerCase();if(!It.endsWith(".gcode")&&!It.includes(".gcode."))return g("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:bt=>{const It=bt.metadata?.sliced_for_model,nn=pv(t.model);if(It&&nn&&It.toLowerCase()!==nn.toLowerCase())return fe.deleteLibraryFile(bt.id).catch(()=>{}),g("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:It,printerModel:nn});Z({id:bt.id,filename:bt.filename})}}),ee&&i.jsx(Vc,{mode:"reprint",libraryFileId:ee.id,archiveName:ee.filename,initialSelectedPrinterIds:[t.id],onClose:()=>Z(null),onSuccess:()=>Z(null)}),te&&i.jsx(SAe,{printerId:t.id,printerName:t.name,onClose:()=>re(!1)}),ie&&i.jsx(iqe,{printer:t,status:we,totalPrintHours:n?.total_print_hours,onClose:V}),Fe&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>za(),children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:bt=>bt.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[Fe.needs_calibration?i.jsx(V1,{className:"w-5 h-5 text-blue-500"}):Fe.is_empty?i.jsx(pr,{className:"w-5 h-5 text-green-500"}):i.jsx(Vi,{className:"w-5 h-5 text-yellow-500"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Fe.reference_count!==void 0&&Fe.max_references&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Fe.reference_count,"/",Fe.max_references," refs"]})]}),i.jsx("button",{onClick:()=>za(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[Fe.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[i.jsx("p",{className:"font-medium text-blue-400",children:g("printers.plateDetection.calibrationRequired")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),i.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[i.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),i.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`p-3 rounded-lg ${Fe.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[i.jsx("p",{className:`font-medium ${Fe.is_empty?"text-green-400":"text-yellow-400"}`,children:Fe.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),i.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(Fe.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Fe.difference_percent.toFixed(1),"%"]})]}),Fe.debug_image_url&&i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),i.jsx("img",{src:Fe.debug_image_url,alt:g("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:g("printers.plateDetection.analysisLegend")})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:Fe.message})]}),Zn&&Zn.references.length>0&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:g("printers.plateDetection.savedReferences",{count:Zn.references.length,max:Zn.max_references})}),i.jsx("div",{className:"grid grid-cols-5 gap-2",children:Zn.references.map(bt=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:fe.getPlateReferenceThumbnailUrl(t.id,bt.index),alt:bt.label||`Reference ${bt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),i.jsx("button",{onClick:()=>hc(bt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:i.jsx(zt,{className:"w-3 h-3 text-white"})}),ni?.index===bt.index?i.jsx("input",{type:"text",value:ni.label,onChange:It=>Rr({...ni,label:It.target.value}),onBlur:()=>mc(bt.index,ni.label),onKeyDown:It=>{It.key==="Enter"&&mc(bt.index,ni.label),It.key==="Escape"&&Rr(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:g("printers.plateDetection.labelPlaceholder")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Rr({index:bt.index,label:bt.label}),title:bt.label?g("printers.plateDetection.clickToEdit",{label:bt.label}):g("printers.plateDetection.clickToAddLabel"),children:bt.label||i.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),i.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:bt.timestamp?er(bt.timestamp)?.toLocaleDateString()??"":""})]},bt.index))})]}),!Fe.needs_calibration&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:g("printers.roi.title")}),be?i.jsxs("div",{className:"flex gap-1",children:[i.jsx(Oe,{variant:"ghost",size:"sm",onClick:()=>He(null),disabled:Ce,children:g("common.cancel")}),i.jsx(Oe,{size:"sm",onClick:Yi,disabled:Ce,children:Ce?i.jsx(lt,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):i.jsxs(Oe,{variant:"ghost",size:"sm",onClick:()=>He(Fe.roi||{x:.15,y:.35,w:.7,h:.55}),children:[i.jsx(Ki,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),be?i.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.xStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:be.x,onChange:bt=>He({...be,x:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.x*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:be.y,onChange:bt=>He({...be,y:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.y*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:be.w,onChange:bt=>He({...be,w:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.w*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:be.h,onChange:bt=>He({...be,h:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.h*100),"%"]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Fe.roi?.x||.15)*100),"%, Y=",Math.round((Fe.roi?.y||.35)*100),"%, W=",Math.round((Fe.roi?.w||.7)*100),"%, H=",Math.round((Fe.roi?.h||.55)*100),"%"]})]})]}),i.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Fe.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsx(Oe,{variant:"ghost",onClick:()=>za(),children:g("common.cancel")}),i.jsx(Oe,{onClick:()=>Cf(),disabled:Pe,children:Pe?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):i.jsxs(i.Fragment,{children:[i.jsx(Oe,{variant:"ghost",onClick:()=>Cf(),disabled:Pe,children:Pe?"Adding...":`Add Reference (${Zn?.references.length||0}/${Zn?.max_references||5})`}),i.jsx(Oe,{onClick:()=>za(),children:"Close"})]})})]})}),J&&tt&&i.jsx(_n,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{jt.mutate("on"),le(!1)},onCancel:()=>le(!1)}),me&&tt&&i.jsx(_n,{title:g("printers.confirm.powerOffTitle"),message:we?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{jt.mutate("off"),he(!1)},onCancel:()=>he(!1)}),oe&&i.jsx(_n,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Jt.mutate(),ye(!1)},onCancel:()=>ye(!1)}),Ee&&i.jsx(_n,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{fn.mutate(),q(!1)},onCancel:()=>q(!1)}),K&&i.jsx(_n,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Pn.mutate(),E(!1)},onCancel:()=>E(!1)}),i.jsx(EL,{printerId:t.id,isOpen:j,onClose:()=>L(!1)}),X&&i.jsx(CAe,{printerName:t.name,errors:we?.hms_errors||[],onClose:()=>ae(!1),printerId:t.id,hasPermission:C}),I&&i.jsx(L$e,{isOpen:!!I,onClose:()=>F(null),printerId:t.id,printerName:t.name,amsId:I.amsId,amsLabel:I.amsLabel,initialMode:I.mode,thresholds:s}),Q&&i.jsx(O$e,{isOpen:!!Q,onClose:()=>xe(null),tagUid:Q.tagUid,trayUuid:Q.trayUuid,printerId:Q.printerId,amsId:Q.amsId,trayId:Q.trayId}),pe&&i.jsx(I$e,{isOpen:!!pe,onClose:()=>de(null),printerId:pe.printerId,amsId:pe.amsId,trayId:pe.trayId,trayInfo:pe.trayInfo}),Ae&&i.jsx(Kne,{isOpen:!!Ae,onClose:()=>_e(null),printerId:t.id,slotInfo:Ae,printerModel:pv(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),$&&i.jsx(xqe,{printer:t,onClose:()=>U(!1)}),Ue&&Ge&&i.jsx(bqe,{printer:t,firmwareInfo:Ge,onClose:()=>$e(!1)}),ks&&i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Vs(null)})]})}function gqe({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Mt(),[a,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[C,T]=w.useState({scanned:0,total:0});w.useEffect(()=>{yc.getInfo().then(A=>{v(A.is_docker),A.subnets.length>0&&(y(A.subnets),N(A.subnets[0]))}).catch(()=>{})},[]);const P=c.filter(A=>!n.includes(A.serial)),k=async()=>{m(""),d([]),l(!0),f(!1),T({scanned:0,total:0});try{if(x){await yc.startSubnetScan(_);const A=setInterval(async()=>{try{const R=await yc.getScanStatus();T({scanned:R.scanned,total:R.total});const $=await yc.getDiscoveredPrinters();d($),R.running||(clearInterval(A),l(!1),f(!0))}catch(R){console.error("Failed to get scan status:",R)}},500)}else{await yc.startDiscovery(10);const A=setInterval(async()=>{try{const R=await yc.getDiscoveredPrinters();d(R)}catch(R){console.error("Failed to get discovered printers:",R)}},1e3);setTimeout(async()=>{clearInterval(A);try{await yc.stopDiscovery()}catch{}l(!1),f(!0);try{const R=await yc.getDiscoveredPrinters();d(R)}catch(R){console.error("Failed to get final discovered printers:",R)}},1e4)}}catch(A){console.error("Failed to start discovery:",A),m(A instanceof Error?A.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},D=A=>{const R=A.serial.startsWith("unknown-")?"":A.serial;s({...a,name:A.name||"",serial_number:R,ip_address:A.ip_address,model:pv(A.model)}),d([])};return w.useEffect(()=>()=>{yc.stopDiscovery().catch(()=>{}),yc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const A=R=>{R.key==="Escape"&&t()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:i.jsx(Tt,{className:"w-full max-w-md",onClick:A=>A.stopPropagation(),children:i.jsxs(Pt,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),i.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),g.length>0?i.jsx("select",{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 text-sm",value:_,onChange:A=>N(A.target.value),disabled:o,children:g.map(A=>i.jsx("option",{value:A,children:A},A))}):i.jsx("input",{type:"text",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 text-sm",value:_,onChange:A=>N(A.target.value),placeholder:"192.168.1.0/24",disabled:o}),i.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),i.jsx(Oe,{type:"button",variant:"secondary",onClick:k,disabled:o,className:"w-full",children:o?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),x&&C.total>0?r("printers.discovery.scanProgress",{scanned:C.scanned,total:C.total}):r("printers.discovery.scanning")]}):i.jsxs(i.Fragment,{children:[i.jsx(jr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&i.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),P.length>0&&i.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:P.map(A=>i.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>D(A),children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium text-white text-sm truncate",children:A.name||A.serial}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[pv(A.model)||r("printers.discovery.unknown")," • ",A.ip_address,A.serial.startsWith("unknown-")&&i.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),i.jsx(jn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},A.serial))}),o&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&P.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),i.jsxs("form",{onSubmit:A=>{A.preventDefault(),e(a)},className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),i.jsx("input",{type:"text",required:!0,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",value:a.name,onChange:A=>s({...a,name:A.target.value}),placeholder:r("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),i.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",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",value:a.ip_address,onChange:A=>s({...a,ip_address:A.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),i.jsx("input",{type:"text",required:!0,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",value:a.serial_number,onChange:A=>s({...a,serial_number:A.target.value}),placeholder:"01P00A000000000"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),i.jsx("input",{type:"password",required:!0,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",value:a.access_code,onChange:A=>s({...a,access_code:A.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),i.jsxs("select",{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",value:a.model||"",onChange:A=>s({...a,model:A.target.value}),children:[i.jsx("option",{value:"",children:r("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),i.jsx("input",{type:"text",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",value:a.location||"",onChange:A=>s({...a,location:A.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"auto_archive",checked:a.auto_archive,onChange:A=>s({...a,auto_archive:A.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsx(Oe,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function bqe({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Mt(),a=Zt(),{showToast:s}=hn(),{hasPermission:o}=Dr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),{data:x,isLoading:v}=Ze({queryKey:["firmwarePrepare",t.id],queryFn:()=>l1.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=dt({mutationFn:()=>l1.startUpload(t.id),onSuccess:()=>{m(!0);const _=setInterval(async()=>{try{const N=await l1.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),a.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const y=()=>{d(null),g.mutate()};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsx(Tt,{className:"w-full max-w-md mx-4",children:i.jsxs(Pt,{children:[i.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[i.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?i.jsx(hi,{className:"w-5 h-5 text-orange-400"}):i.jsx(pr,{className:"w-5 h-5 text-status-ok"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),i.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&i.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),i.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&i.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[i.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),i.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?v?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!u&&!c?i.jsx("div",{className:"mb-4",children:x.can_proceed?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[i.jsx(ia,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):i.jsx("div",{className:"space-y-1",children:x.errors.map((_,N)=>i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(zi,{className:"w-4 h-4 flex-shrink-0"}),_]},N))})}):null:null,(u||c)&&c&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),i.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),i.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&i.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),i.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),i.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(Oe,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!u&&c?.status!=="complete"&&l&&i.jsx(Oe,{onClick:y,disabled:g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):i.jsxs(i.Fragment,{children:[i.jsx(hi,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function xqe({printer:t,onClose:e}){const{t:n}=Mt(),r=Zt(),{showToast:a}=hn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=dt({mutationFn:d=>fe.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>a(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsx(Tt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:i.jsxs(Pt,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),i.jsx("input",{type:"text",required:!0,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",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),i.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",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",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),i.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),i.jsx("input",{type:"password",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",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),i.jsxs("select",{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",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[i.jsx("option",{value:"",children:n("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),i.jsx("input",{type:"text",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",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),i.jsx(Oe,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function yqe(t){const{data:e}=Ze({queryKey:["printerStatus",t],queryFn:()=>fe.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function vqe({printer:t,plug:e,onPowerOn:n,isPowering:r}){const a=yqe(t.id),{data:s}=Ze({queryKey:["smartPlugStatus",e.id],queryFn:()=>fe.getSmartPlugStatus(e.id),refetchInterval:1e4});return a?i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),i.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[i.jsx(Su,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function wqe(){const{t}=Mt(),[e,n]=w.useState(!1),[r,a]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,x]=w.useState(()=>{const L=localStorage.getItem("printerCardSize");return L?parseInt(L,10):2}),v=f===1?"compact":"expanded",g=Zt(),{showToast:y}=hn(),{hasPermission:_}=Dr(),[N,C]=w.useState(()=>{const L=localStorage.getItem("openEmbeddedCameras");if(L)try{const G=JSON.parse(L);return new Map(G.map(B=>[B.id,B]))}catch{return new Map}return new Map});w.useEffect(()=>{const L=Array.from(N.values());L.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(L)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:T,isLoading:P}=Ze({queryKey:["printers"],queryFn:fe.getPrinters}),{data:k}=Ze({queryKey:["settings"],queryFn:fe.getSettings});w.useEffect(()=>{k?.camera_view_mode==="window"&&N.size>0&&C(new Map)},[k?.camera_view_mode,N.size]);const{data:D}=Ze({queryKey:["smart-plugs"],queryFn:fe.getSmartPlugs}),{data:A}=Ze({queryKey:["maintenanceOverview"],queryFn:fe.getMaintenanceOverview,staleTime:60*1e3}),{data:R}=Ze({queryKey:["spoolman-status"],queryFn:fe.getSpoolmanStatus,staleTime:60*1e3}),$=R?.enabled&&R?.connected,{data:U}=Ze({queryKey:["unlinked-spools"],queryFn:fe.getUnlinkedSpools,enabled:!!$,staleTime:30*1e3}),W=U&&U.length>0,{data:O}=Ze({queryKey:["linked-spools"],queryFn:fe.getLinkedSpools,enabled:!!$,staleTime:30*1e3}),te=O?.linked,{data:re}=Ze({queryKey:["spool-assignments"],queryFn:()=>fe.getAssignments(),staleTime:30*1e3}),J=dt({mutationFn:({printerId:L,amsId:G,trayId:B})=>fe.unassignSpool(L,G,B),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),le=(L,G,B)=>re?.find(ie=>ie.printer_id===L&&ie.ams_id===Number(G)&&ie.tray_id===Number(B)),me=A?.reduce((L,G)=>(L[G.printer_id]={due_count:G.due_count,warning_count:G.warning_count,total_print_hours:G.total_print_hours},L),{})||{},he=D?.reduce((L,G)=>(G.printer_id&&(L[G.printer_id]=G),L),{})||{},X=dt({mutationFn:fe.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:L=>y(L.message||t("printers.toast.failedToAdd"),"error")}),ae=dt({mutationFn:L=>fe.controlSmartPlug(L,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),oe=()=>{const L=!r;a(L),localStorage.setItem("hideDisconnectedPrinters",String(L))},ye=L=>{u(L),localStorage.setItem("printerSortBy",L)},Ee=()=>{const L=!m;p(L),localStorage.setItem("printerSortAsc",String(L))},q=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},K=["S","M","L","XL"],E=w.useMemo(()=>{if(!T)return[];const L=[...T];switch(d){case"name":L.sort((G,B)=>G.name.localeCompare(B.name));break;case"model":L.sort((G,B)=>(G.model||"").localeCompare(B.model||""));break;case"location":L.sort((G,B)=>{const ie=G.location||"",z=B.location||"";return!ie&&z?1:ie&&!z?-1:ie.localeCompare(z)||G.name.localeCompare(B.name)});break;case"status":L.sort((G,B)=>{const ie=g.getQueryData(["printerStatus",G.id]),z=g.getQueryData(["printerStatus",B.id]),V=ee=>ee?.connected?ee.state==="RUNNING"?0:1:2;return V(ie)-V(z)});break}return m||L.reverse(),L},[T,d,m,g]),j=w.useMemo(()=>{if(d!=="location")return null;const L={};return E.forEach(G=>{const B=G.location||"Ungrouped";L[B]||(L[B]=[]),L[B].push(G)}),L},[d,E]);return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),i.jsx(fqe,{printers:T})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("select",{value:d,onChange:L=>ye(L.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"name",children:t("printers.sort.name")}),i.jsx("option",{value:"status",children:t("printers.sort.status")}),i.jsx("option",{value:"model",children:t("printers.sort.model")}),i.jsx("option",{value:"location",children:t("printers.sort.location")})]}),i.jsx("button",{onClick:Ee,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?i.jsx($p,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(Pb,{className:"w-4 h-4 text-bambu-gray"})})]}),i.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:K.map((L,G)=>{const B=G+1,ie=f===B;return i.jsx("button",{onClick:()=>{x(B),localStorage.setItem("printerCardSize",String(B))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${G===0?"rounded-l-lg":""} ${G===K.length-1?"rounded-r-lg":""} ${ie?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(L==="S"?"printers.cardSize.small":L==="M"?"printers.cardSize.medium":L==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:L},L)})}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:oe,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(he).length>0&&i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(Su,{className:"w-4 h-4"}),t("printers.powerOn"),i.jsx(jn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),i.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[i.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),T?.filter(L=>he[L.id]).map(L=>i.jsx(vqe,{printer:L,plug:he[L.id],onPowerOn:G=>{c(G),ae.mutate(G)},isPowering:l===he[L.id]?.id},L.id)),T?.filter(L=>he[L.id]).length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),i.jsxs(Oe,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),P?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):T?.length===0?i.jsx(Tt,{children:i.jsxs(Pt,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),i.jsxs(Oe,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):j?i.jsx("div",{className:"space-y-6",children:Object.entries(j).map(([L,G])=>i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),L,i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",G.length,")"]})]}),i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${q()}`,children:G.map(B=>i.jsx(RG,{printer:B,hideIfDisconnected:r,maintenanceInfo:me[B.id],viewMode:v,cardSize:f,amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,spoolmanEnabled:$,hasUnlinkedSpools:W,linkedSpools:te,spoolmanUrl:R?.url,onGetAssignment:le,onUnassignSpool:(ie,z,V)=>J.mutate({printerId:ie,amsId:z,trayId:V}),timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(ie,z)=>C(V=>new Map(V).set(ie,{id:ie,name:z})),checkPrinterFirmware:k?.check_printer_firmware!==!1},B.id))})]},L))}):i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${q()}`,children:E.map(L=>i.jsx(RG,{printer:L,hideIfDisconnected:r,maintenanceInfo:me[L.id],viewMode:v,cardSize:f,spoolmanEnabled:$,hasUnlinkedSpools:W,linkedSpools:te,spoolmanUrl:R?.url,onGetAssignment:le,onUnassignSpool:(G,B,ie)=>J.mutate({printerId:G,amsId:B,trayId:ie}),amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(G,B)=>C(ie=>new Map(ie).set(G,{id:G,name:B})),checkPrinterFirmware:k?.check_printer_firmware!==!1},L.id))}),e&&i.jsx(gqe,{onClose:()=>n(!1),onAdd:L=>X.mutate(L),existingSerials:T?.map(L=>L.serial_number)||[]}),Array.from(N.values()).map((L,G)=>i.jsx(wAe,{printerId:L.id,printerName:L.name,viewerIndex:G,onClose:()=>C(B=>{const ie=new Map(B);return ie.delete(L.id),ie})},L.id))]})}function Sqe(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function wp(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:Sqe()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const FG=768;function ire(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${FG-1}px)`),r=a=>{e(a.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function O4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:a}){const{t:s}=Mt(),{data:o}=Ze({queryKey:["settings"],queryFn:fe.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[m,p]=w.useState(null),[f,x]=w.useState(!0),[v,g]=w.useState(null),[y,_]=w.useState(!1),[N,C]=w.useState(null),[T,P]=w.useState(0),[k,D]=w.useState(!1),[A,R]=w.useState(null),[$,U]=w.useState(!1),[W,O]=w.useState(!1),te=w.useRef(null),re=w.useRef(null),J=10,le=160,me=240,he=.35;w.useEffect(()=>{const ge=ce=>{ce.key==="Escape"&&a()};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[a]),w.useEffect(()=>{if(x(!0),c){const ge=(r||"").toLowerCase(),ce=ge==="3mf"||ge==="stl",I=ge==="gcode"||ge==="3mf";p({has_model:ce,has_gcode:I,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(ce?"3d":I?"gcode":null),x(!1);return}if(!t){p(null),u(null),x(!1);return}fe.getArchiveCapabilities(t).then(ge=>{p(ge),ge.has_model?u("3d"):ge.has_gcode&&u("gcode"),x(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),C(null),P(0),c){const ge=(r||"").toLowerCase();if(!e||ge!=="3mf"){g(null),_(!1);return}fe.getLibraryFilePlates(e).then(ce=>g(ce)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}fe.getArchivePlates(t).then(ge=>g(ge)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const X=w.useMemo(()=>v?.plates??[],[v]),ae=(v?.is_multi_plate??!1)&&X.length>1,oe=k&&ae,ye=N==null?null:X.find(ge=>ge.index===N)??null,Ee=ge=>ge.object_count??ge.objects?.length??0,q=X.reduce((ge,ce)=>ge+Ee(ce),0),K=ye?Ee(ye):q,E=ye?s("modelViewer.plateNumber",{number:ye.index}):s("modelViewer.allPlates"),j=X.length>0,L=w.useRef(null),G=w.useRef(null),[B,ie]=w.useState(10),[z,V]=w.useState(3),ee=X.length>B,Z=Math.max(1,Math.ceil(X.length/B)),ne=ee?X.slice(T*B,(T+1)*B):X;w.useEffect(()=>{if(!oe){ie(10),V(3);return}const ge=L.current,ce=G.current;if(!ge||!ce)return;let I=0;const F=()=>{const pe=ce.clientWidth,Ae=Math.floor(pe/210),_e=Math.max(3,Math.min(5,Ae||3));V(be=>be===_e?be:_e);const Ue=window.getComputedStyle(ge),$e=Number.parseFloat(Ue.rowGap||"0"),ke=ge.querySelector("button")?.getBoundingClientRect().height??44,Me=ce.clientHeight,Pe=Math.max(1,Math.floor((Me+$e)/(ke+$e)))*_e,We=Math.max(1,Pe-1);ie(be=>be===We?be:We)},Q=()=>{I&&cancelAnimationFrame(I),I=requestAnimationFrame(F)};Q();const xe=new ResizeObserver(Q);return xe.observe(ce),xe.observe(ge),()=>{I&&cancelAnimationFrame(I),xe.disconnect()}},[oe,X.length]),w.useEffect(()=>{if(!ee){P(0);return}P(ge=>Math.min(ge,Z-1))},[X.length,ee,Z]),w.useEffect(()=>{if(!ee||N==null)return;const ge=X.findIndex(I=>I.index===N);if(ge<0)return;const ce=Math.floor(ge/B);P(I=>I===ce?I:ce)},[X,B,N,ee]),w.useEffect(()=>{if(!oe){R(null),O(!1);return}if(W)return;const ge=te.current,ce=re.current;if(!ge||!ce)return;const I=ge.clientHeight;if(!I)return;const F=Math.max(me,I*he),Q=Math.max(le,I-J-F),xe=Math.min(ce.scrollHeight,Q);R(Math.max(le,xe))},[oe,W,X.length,T,J,le,me,he]),w.useEffect(()=>{if(!$)return;const ge=I=>{const F=te.current;if(!F)return;const Q=F.getBoundingClientRect(),xe=Q.height;if(!xe)return;const pe=Math.max(me,xe*he),de=Math.max(le,xe-J-pe),Ae=Math.min(de,Math.max(le,I.clientY-Q.top));R(Ae)},ce=()=>{U(!1),O(!0)};return document.addEventListener("mousemove",ge),document.addEventListener("mouseup",ce),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",ge),document.removeEventListener("mouseup",ce),document.body.style.cursor="",document.body.style.userSelect=""}},[$,J,le,me,he]);const se=c?(r||"").toLowerCase()==="3mf":!0,ue=async()=>{if(!se)return;const ge=n||"model";try{if(c){const{token:ce}=await fe.createLibrarySlicerToken(e),I=fe.getLibrarySlicerDownloadUrl(e,ce,ge);wp(`${window.location.origin}${I}`,l)}else{const{token:ce}=await fe.createArchiveSlicerToken(t),I=fe.getArchiveSlicerDownloadUrl(t,ce,ge);wp(`${window.location.origin}${I}`,l)}}catch{if(c){const ce=`${window.location.origin}${fe.getLibraryFileDownloadUrl(e)}`;wp(ce,l)}else{const ce=`${window.location.origin}${fe.getArchiveForSlicer(t,ge)}`;wp(ce,l)}}};return i.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${k?"p-0":"p-8"}`,onClick:a,children:i.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${k?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:ge=>ge.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[E,": ",s("modelViewer.objectCount",{count:K})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Oe,{variant:"secondary",size:"sm",onClick:ue,disabled:!se,children:[i.jsx(ei,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),i.jsx(Oe,{variant:"secondary",size:"sm",onClick:()=>D(ge=>!ge),title:k?"Exit fullscreen":"Enter fullscreen",children:k?i.jsx(KF,{className:"w-4 h-4"}):i.jsx(uC,{className:"w-4 h-4"})}),i.jsx(Oe,{variant:"ghost",size:"sm",onClick:a,children:i.jsx(zt,{className:"w-5 h-5"})})]})]}),m&&i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(ia,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),i.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(xhe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),i.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?i.jsxs("div",{ref:te,className:`w-full h-full flex flex-col ${oe?"gap-0 min-h-0":"gap-3"}`,children:[ae&&i.jsxs("div",{ref:re,style:oe&&A!=null?{height:A}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${oe?"flex flex-col shrink-0":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[i.jsx(Gi,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&i.jsx(lt,{className:"w-3 h-3 animate-spin"})]}),i.jsxs("div",{className:oe?"flex flex-col min-h-0 flex-1":void 0,children:[i.jsx("div",{ref:G,className:oe?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:i.jsxs("div",{ref:L,className:oe?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:oe?{gridTemplateColumns:`repeat(${z}, minmax(0, 1fr))`}:void 0,children:[i.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${oe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${oe?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${oe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${oe?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),i.jsx("p",{className:`${oe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:X.length})})]}),N==null&&i.jsx(Vr,{className:`${oe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ne.map(ge=>i.jsxs("button",{type:"button",onClick:()=>C(ge.index),className:`flex items-center rounded-lg border text-left transition-colors ${oe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===ge.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[ge.has_thumbnail&&ge.thumbnail_url?i.jsx("img",{src:ge.thumbnail_url,alt:`Plate ${ge.index}`,className:`${oe?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${oe?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${oe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${oe?"text-xs":"text-sm"} text-white font-medium truncate`,children:ge.name||s("modelViewer.plateNumber",{number:ge.index})}),i.jsx("p",{className:`${oe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:ge.object_count??ge.objects?.length??0})})]}),N===ge.index&&i.jsx(Vr,{className:`${oe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},ge.index))]})}),(ye||ee)&&i.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ye&&i.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[i.jsx("span",{children:s("modelViewer.plateNumber",{number:ye.index})}),ye.print_time_seconds!=null&&i.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ye.print_time_seconds/60)})}),ye.filament_used_grams!=null&&i.jsxs("span",{children:[ye.filament_used_grams.toFixed(1)," g"]}),ye.filaments.length>0&&i.jsx("span",{children:s("modelViewer.filamentCount",{count:ye.filaments.length})})]}),ee&&i.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ye?"ml-auto":""}`,children:[i.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:T+1,total:Z})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>P(ge=>Math.max(ge-1,0)),disabled:T===0,className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let ce=Math.max(0,T-Math.floor(2.5));const I=Math.min(Z,ce+5);I-ce<5&&(ce=Math.max(0,I-5));const F=Array.from({length:I-ce},(Q,xe)=>ce+xe);return i.jsxs(i.Fragment,{children:[ce>0&&i.jsx("button",{type:"button",onClick:()=>P(0),className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),ce>1&&i.jsx("span",{className:"px-1",children:"…"}),F.map(Q=>i.jsx("button",{type:"button",onClick:()=>P(Q),className:`px-2 py-1 rounded border text-xs ${T===Q?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Q+1},Q)),IP(Z-1),className:`px-2 py-1 rounded border text-xs ${T===Z-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Z})]})})(),i.jsx("button",{type:"button",onClick:()=>P(ge=>Math.min(ge+1,Z-1)),disabled:T>=Z-1,className:`px-2 py-1 rounded border text-xs ${T>=Z-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),oe&&i.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:ge=>{ge.preventDefault(),U(!0),O(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${$?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),i.jsx("div",{className:`flex-1 ${oe?"min-h-0":""}`,children:i.jsx(QX,{url:c?fe.getLibraryFileDownloadUrl(e):m.has_source?fe.getSource3mfDownloadUrl(t):fe.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&m?i.jsx(DQ,{gcodeUrl:c?fe.getLibraryFileGcodeUrl(e):fe.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function _qe({onClose:t,initialFiles:e}){const{t:n}=Mt(),r=Zt(),{showToast:a}=hn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(T=>T.name.endsWith(".3mf")).map(T=>({file:T,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const T=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[t]);const p=dt({mutationFn:T=>fe.uploadArchivesBulk(T),onSuccess:T=>{m(T),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(P=>P.map(k=>{const D=T.results.find(R=>R.filename===k.file.name),A=T.errors.find(R=>R.filename===k.file.name);return D?{...k,status:"success",archiveId:D.id}:A?{...k,status:"error",error:A.error}:k})),T.failed===0?a(`${T.uploaded} file${T.uploaded!==1?"s":""} uploaded`):T.uploaded===0?a(`Failed to upload ${T.failed} file${T.failed!==1?"s":""}`,"error"):a(`${T.uploaded} uploaded, ${T.failed} failed`,"warning")},onError:()=>{l(T=>T.map(P=>({...P,status:"error",error:"Upload failed"}))),a("Upload failed","error")}}),f=w.useCallback(T=>{T.preventDefault(),d(!0)},[]),x=w.useCallback(T=>{T.preventDefault(),d(!1)},[]),v=w.useCallback(T=>{T.preventDefault(),d(!1);const P=Array.from(T.dataTransfer.files).filter(k=>k.name.endsWith(".3mf"));P.length>0&&l(k=>[...k,...P.map(D=>({file:D,status:"pending"}))])},[]),g=w.useCallback(T=>{const P=Array.from(T.target.files||[]).filter(k=>k.name.endsWith(".3mf"));P.length>0&&l(k=>[...k,...P.map(D=>({file:D,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(T=>{l(P=>P.filter((k,D)=>D!==T))},[]),_=()=>{if(o.length===0)return;const T=o.filter(P=>P.status==="pending");T.length!==0&&(l(P=>P.map(k=>k.status==="pending"?{...k,status:"uploading"}:k)),p.mutate(T.map(P=>P.file)))},N=o.filter(T=>T.status==="pending").length,C=p.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:i.jsxs(Pt,{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.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"p-4",children:i.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:x,onDrop:v,children:[i.jsx(Si,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),i.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),i.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),i.jsx(Oe,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:n("uploadModal.browseFiles")}),i.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),i.jsx("div",{className:"px-4 pb-4",children:i.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&i.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:i.jsx("div",{className:"space-y-2",children:o.map((T,P)=>i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx(oC,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"flex-1 text-white text-sm truncate",children:T.file.name}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[(T.file.size/(1024*1024)).toFixed(1)," MB"]}),T.status==="pending"&&i.jsx("button",{onClick:()=>y(P),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:i.jsx(zt,{className:"w-4 h-4"})}),T.status==="uploading"&&i.jsx(lt,{className:"w-4 h-4 text-bambu-green animate-spin"}),T.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-bambu-green"}),T.status==="error"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-red-400",children:T.error}),i.jsx(zi,{className:"w-4 h-4 text-red-400"})]})]},`${T.file.name}-${P}`))})}),u&&i.jsx("div",{className:"px-4 pb-4",children:i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&i.jsxs(i.Fragment,{children:[", ",i.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Oe,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&i.jsx(Oe,{onClick:_,disabled:N===0||C,className:"flex-1",children:C?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Si,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const Nqe=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],kqe=["completed","failed","aborted","printing"];function are({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Mt();w.useEffect(()=>{const j=L=>{L.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const a=Zt(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,x]=w.useState(t.tags||""),[v,g]=w.useState(t.failure_reason||""),[y,_]=w.useState(t.status),[N,C]=w.useState(t.quantity??1),[T,P]=w.useState(t.photos||[]),[k,D]=w.useState(t.external_url||""),[A,R]=w.useState(!1),[$,U]=w.useState(!1),W=w.useRef(null),O=w.useRef(null),te=w.useRef(null),{data:re}=Ze({queryKey:["printers"],queryFn:fe.getPrinters}),{data:J}=Ze({queryKey:["projects"],queryFn:()=>fe.getProjects()}),{data:le}=Ze({queryKey:["tags"],queryFn:fe.getTags,enabled:n.length===0}),me=n.length>0?n:le?.map(j=>j.name)||[],he=f.split(",").map(j=>j.trim()).filter(Boolean),X=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ae=me.filter(j=>!he.includes(j)&&(X===""||j.toLowerCase().includes(X))),oe=j=>{let L;if(X&&!me.includes(X)?L=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(G=>G.trim()).filter(Boolean):[]:L=he,!L.includes(j)){const G=[...L,j].join(", ");x(G)}te.current!==null&&clearTimeout(te.current),W.current?.focus()},ye=j=>{const L=he.filter(G=>G!==j).join(", ");x(L)},Ee=dt({mutationFn:j=>fe.updateArchive(t.id,j),onSuccess:()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),e()}}),q=async j=>{const L=j.target.files?.[0];if(L){R(!0);try{const G=await fe.uploadArchivePhoto(t.id,L);P(G.photos),a.invalidateQueries({queryKey:["archives"]})}catch(G){console.error("Failed to upload photo:",G)}finally{R(!1),O.current&&(O.current.value="")}}},K=async j=>{try{const L=await fe.deleteArchivePhoto(t.id,j);P(L.photos||[]),a.invalidateQueries({queryKey:["archives"]})}catch(L){console.error("Failed to delete photo:",L)}},E=j=>{j.preventDefault();const L={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:N,external_url:k||null};y!==t.status&&(L.status=y),y==="failed"||y==="aborted"?L.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(L.failure_reason=null),Ee.mutate(L)};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:j=>j.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:E,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),i.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),i.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.noPrinter")}),re?.map(j=>i.jsx("option",{value:j.id,children:j.name},j.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(bs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),i.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.noProject")}),J?.map(j=>i.jsx("option",{value:j.id,children:j.name},j.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(kpe,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),i.jsx("input",{type:"number",min:1,value:N,onChange:j=>C(Math.max(1,parseInt(j.target.value)||1)),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:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),i.jsx("textarea",{value:m,onChange:j=>p(j.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(dx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),i.jsx("input",{type:"url",value:k,onChange:j=>D(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),he.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:he.map(j=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[i.jsx(du,{className:"w-3 h-3"}),j,i.jsx("button",{type:"button",onClick:()=>ye(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:i.jsx(zt,{className:"w-3 h-3"})})]},j))}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{ref:W,type:"text",value:f,onChange:j=>x(j.target.value),onFocus:()=>{te.current!==null&&clearTimeout(te.current),U(!0)},onBlur:()=>{te.current=window.setTimeout(()=>U(!1),200)},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:he.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),$&&ae.length>0&&i.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[i.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[X?r("editArchive.matchingTags",{query:X}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),i.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ae.map(j=>i.jsx("button",{type:"button",onClick:()=>oe(j),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:j},j))})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),i.jsx("select",{value:y,onChange:j=>{_(j.target.value),j.target.value==="completed"&&g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:kqe.map(j=>i.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(y==="failed"||y==="aborted")&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),i.jsxs("select",{value:v,onChange:j=>g(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.selectReason")}),Nqe.map(j=>i.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(Mb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[T.map(j=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:fe.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:()=>K(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx(Qt,{className:"w-3 h-3 text-white"})})]},j)),i.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[i.jsx("input",{ref:O,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:q,className:"hidden",disabled:A}),A?i.jsx(lt,{className:"w-6 h-6 text-bambu-gray animate-spin"}):i.jsx(rr,{className:"w-6 h-6 text-bambu-gray"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),i.jsxs(Oe,{type:"submit",disabled:Ee.isPending,className:"flex-1",children:[i.jsx(gs,{className:"w-4 h-4"}),Ee.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function sre({x:t,y:e,items:n,onClose:r}){const a=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const g=N=>{a.current&&!a.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(a.current){a.current.style.visibility="hidden",a.current.style.display="block";const g=a.current.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,N=8;let C=t,T=e;t+g.width>y-N&&(C=Math.max(N,y-g.width-N)),C_-N&&(T=Math.max(N,_-g.height-N)),TP),d({x:C,y:T,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,C=300,k=N-_.top-8C;f(D=>({...D,[g]:k?"bottom":"top"})),o(g)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return i.jsx("div",{ref:a,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((g,y)=>{if(g.divider)return i.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const _=g.submenu&&g.submenu.length>0;return i.jsxs("div",{className:"relative",onMouseEnter:N=>_&&x(y,N.currentTarget),onMouseLeave:()=>_&&v(),children:[i.jsxs("button",{onMouseEnter:N=>_&&x(y,N.currentTarget.parentElement),onClick:()=>{_?o(s===y?null:y):g.disabled||(g.onClick(),r())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===y?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),i.jsx("span",{className:"flex-1",children:g.label}),_&&i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===y&&i.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:g.submenu.map((N,C)=>i.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},C))})]},y)})})}function Cqe({selectedIds:t,existingTags:e,onClose:n}){const r=Zt(),{showToast:a}=hn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=dt({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await fe.getArchive(y),N=_.tags?_.tags.split(",").map(T=>T.trim()).filter(Boolean):[];let C;d==="add"?C=[...new Set([...N,...v])]:C=N.filter(T=>!l.has(T)),await fe.updateArchive(y,{tags:C.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${y}:`,_),new Error(`Failed on archive ${y}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:v}},onSuccess:({count:v,mode:g,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),a(`${g==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${g==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{a(v.message||"Failed to update tags","error")}}),p=v=>{c(g=>{const y=new Set(g);return y.has(v)?y.delete(v):y.add(v),y})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Tt,{className:"w-full max-w-md",children:i.jsxs(Pt,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(du,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Oe,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),i.jsx(Oe,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",placeholder:"Enter new tag...",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",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),i.jsx(Oe,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:i.jsx(rr,{className:"w-4 h-4"})})]}),e.length>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>i.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&i.jsxs("div",{children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>i.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,i.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:i.jsx(zt,{className:"w-3 h-3"})})]},v))})]})]}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Oe,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),i.jsx(Oe,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(du,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function Tqe({selectedIds:t,onClose:e}){const n=Zt(),{showToast:r}=hn(),{data:a,isLoading:s}=Ze({queryKey:["projects"],queryFn:()=>fe.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=dt({mutationFn:async u=>(await fe.addArchivesToProject(u,t),u),onSuccess:u=>{const m=a?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=dt({mutationFn:async()=>{for(const u of t)await fe.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:i.jsxs(Pt,{className:"p-0 flex flex-col min-h-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(bs,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[i.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:i.jsx(Vi,{className:"w-4 h-4 text-red-400"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),i.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&i.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),a&&a.length>0&&i.jsxs("div",{className:"flex items-center gap-2 py-2",children:[i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),a?.map(u=>i.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[i.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:i.jsx(bs,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium truncate",children:u.name}),i.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&i.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!a||a.length===0)&&i.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),i.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:i.jsx(Oe,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function Pqe(t,e){return new Date(t,e+1,0).getDate()}function Aqe(t,e){return new Date(t,e,1).getDay()}const Mqe=["January","February","March","April","May","June","July","August","September","October","November","December"],Eqe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function jqe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[a,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const T=new Map;return t.forEach(P=>{const k=er(P.completed_at||P.created_at)||new Date,D=`${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}-${String(k.getDate()).padStart(2,"0")}`,A=T.get(D)||[];A.push(P),T.set(D,A)}),T},[t]),f=Pqe(o,a),x=Aqe(o,a),v=()=>{a===0?(s(11),l(o-1)):s(a-1)},g=()=>{a===11?(s(0),l(o+1)):s(a+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let T=0;T{T!==c&&m(null),d(T)};return i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(nc,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:[Mqe[a]," ",o]}),i.jsx("button",{onClick:y,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),i.jsx("button",{onClick:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(fa,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:Eqe.map(T=>i.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:T},T))}),i.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((T,P)=>{if(T===null)return i.jsx("div",{className:"aspect-square"},`empty-${P}`);const k=`${o}-${String(a+1).padStart(2,"0")}-${String(T).padStart(2,"0")}`,D=p.get(k)||[],A=D.length>0,R=T===r.getDate()&&a===r.getMonth()&&o===r.getFullYear(),$=k===c,U=D.filter(O=>O.status==="completed").length,W=D.filter(O=>O.status==="failed").length;return i.jsxs("button",{onClick:()=>C($?null:k),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${$?"bg-bambu-green text-white":R?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":A?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[i.jsx("span",{className:`text-sm font-medium ${R&&!$?"text-bambu-green":""}`,children:T}),A&&i.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${W>0&&U===0?"bg-red-400":W>0?"bg-yellow-400":"bg-green-400"}`}),i.jsx("span",{className:"text-xs font-medium",children:D.length})]})]},T)})}),i.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(T=>{const P=er(T.completed_at||T.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(T=>{const P=er(T.completed_at||T.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&T.status==="completed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(T=>{const P=er(T.completed_at||T.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&T.status==="failed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),i.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?i.jsxs(i.Fragment,{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),N.length>0?i.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(T=>{const P=T.id===u||T.id===n;return i.jsxs("button",{onClick:()=>{m(T.id),e?.(T)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${P?"":"hover:bg-bambu-dark-tertiary"}`,style:P?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[T.thumbnail_path?i.jsx("img",{src:fe.getArchiveThumbnail(T.id),alt:"",className:"w-12 h-12 rounded object-cover"}):i.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:T.print_name||T.filename}),i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:T.status==="failed"?"text-red-400":"text-green-400",children:T.status==="failed"?"Failed":"Completed"}),T.filament_color&&i.jsx("div",{className:"flex gap-0.5",children:T.filament_color.split(",").map((k,D)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:k}},D))})]})]})]},T.id)})}):i.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):i.jsx("div",{className:"text-center py-8",children:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function ore({archiveId:t,archiveName:e,onClose:n}){const r=fe.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const a=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 flex flex-col items-center",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),i.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:i.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),i.jsxs(Oe,{onClick:a,className:"w-full",children:[i.jsx(hi,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function lre({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:a}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const d=n[s],u=fe.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{a&&c(!0)};return i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[i.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Oe,{variant:"secondary",size:"sm",onClick:m,children:[i.jsx(hi,{className:"w-4 h-4"}),"Download"]}),a&&i.jsx(Oe,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:i.jsx(Qt,{className:"w-4 h-4"})}),i.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-6 h-6"})})]})]}),i.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&i.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(nc,{className:"w-8 h-8 text-white"})}),i.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(fa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&i.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,x)=>i.jsx("button",{onClick:()=>o(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:i.jsx("img",{src:fe.getArchivePhotoUrl(t,f),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&i.jsx(_n,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{a?.(d),c(!1)},onCancel:()=>c(!1)})]})}function Xa(t){this.content=t}Xa.prototype={constructor:Xa,find:function(t){for(var e=0;e>1}};Xa.from=function(t){if(t instanceof Xa)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Xa(e)};function cre(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let a=t.child(r),s=e.child(r);if(a==s){n+=a.nodeSize;continue}if(!a.sameMarkup(s))return n;if(a.isText&&a.text!=s.text){for(let o=0;a.text[o]==s.text[o];o++)n++;return n}if(a.content.size||s.content.size){let o=cre(a.content,s.content,n+1);if(o!=null)return o}n+=a.nodeSize}}function dre(t,e,n,r){for(let a=t.childCount,s=e.childCount;;){if(a==0||s==0)return a==s?null:{a:n,b:r};let o=t.child(--a),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;de&&r(c,a+l,s||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,n-u),r,a+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,a){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let d=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?a?typeof a=="function"?a(l):a:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,a=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),s=1);se)for(let s=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),a+=l.nodeSize),o=c}return new Ot(r,a)}cutByIndex(e,n){return e==n?Ot.empty:e==0&&n==this.content.length?this:new Ot(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let a=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return a[e]=n,new Ot(a,s)}addToStart(e){return new Ot([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Ot(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let a=this.child(n),s=r+a.nodeSize;if(s>=e)return s==e?B_(n+1,s):B_(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return Ot.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Ot(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Ot.empty;let n,r=0;for(let a=0;athis.type.rank&&(n||(n=e.slice(0,a)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-a.type.rank),n}};Yr.none=[];class lk extends Error{}class Gt{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=mre(this.content,e+this.openStart,n);return r&&new Gt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Gt(ure(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return Gt.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Gt(Ot.fromJSON(e,n.content),r,a)}static maxOpen(e,n=!0){let r=0,a=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)a++;return new Gt(e,r,a)}}Gt.empty=new Gt(Ot.empty,0,0);function ure(t,e,n){let{index:r,offset:a}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(a==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(ure(s.content,e-a-1,n-a-1)))}function mre(t,e,n,r){let{index:a,offset:s}=t.findIndex(e),o=t.maybeChild(a);if(s==e||o.isText)return r&&!r.canReplace(a,a,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=mre(o.content,e-s-1,n,o);return l&&t.replaceChild(a,o.copy(l))}function Dqe(t,e,n){if(n.openStart>t.depth)throw new lk("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new lk("Inconsistent open depths");return hre(t,e,n,0)}function hre(t,e,n,r){let a=t.index(r),s=t.node(r);if(a==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function fv(t,e,n,r){let a=(e||t).node(n),s=0,o=e?e.index(n):a.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(Fp(t.nodeAfter,r),s++));for(let l=s;la&&BR(t,e,a+1),o=r.depth>a&&BR(n,r,a+1),l=[];return fv(null,t,a,l),s&&o&&e.index(a)==n.index(a)?(pre(s,o),Fp(Lp(s,fre(t,e,n,r,a+1)),l)):(s&&Fp(Lp(s,ck(t,e,a+1)),l),fv(e,n,a,l),o&&Fp(Lp(o,ck(n,r,a+1)),l)),fv(r,null,a,l),new Ot(l)}function ck(t,e,n){let r=[];if(fv(null,t,n,r),t.depth>n){let a=BR(t,e,n+1);Fp(Lp(a,ck(t,e,n+1)),r)}return fv(e,null,n,r),new Ot(r)}function Rqe(t,e){let n=e.depth-t.openStart,a=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)a=e.node(s).copy(Ot.from(a));return{start:a.resolveNoCache(t.openStart+n),end:a.resolveNoCache(a.content.size-t.openEnd-n)}}class m0{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],a=e.child(n);return r?e.child(n).cut(r):a}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],a=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new dk(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],a=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(r.push(o,l,a+c),!d||(o=o.child(l),o.isText))break;s=d-1,a+=c+1}return new m0(n,r,s)}static resolveCached(e,n){let r=LG.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(a=!0),!a)),a}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),gre(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=Ot.empty,a=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,a,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=a;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let a=Ot.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,a,r);return s.type.checkAttrs(s.attrs),s}};Jm.prototype.text=void 0;class uk extends Jm{constructor(e,n,r,a){if(super(e,n,null,a),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):gre(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new uk(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new uk(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function gre(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class df{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new Iqe(e,n);if(r.next==null)return df.empty;let a=bre(r);r.next&&r.err("Unexpected trailing text");let s=Vqe(qqe(a));return Gqe(s,r),s}matchType(e){for(let n=0;nd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let a=0;a{let s=a+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` + `,title:C("printers:control")?g(It?"printers.resume":"printers.pause"):g("printers.permission.noControl"),children:[It?i.jsx(uo,{className:"w-3 h-3"}):i.jsx(hC,{className:"w-3 h-3"}),g(It?"printers.resume":"printers.pause")]})]})]})]})})(),(Fn?.length>0||we.vt_tray.length>0)&&r==="expanded"&&(()=>{const bt=Fn.filter(Nt=>Nt.tray.length>1),It=Fn.filter(Nt=>Nt.tray.length===1),nn=t.nozzle_count===2||we?.temperatures?.nozzle_2!==void 0;return i.jsxs("div",{className:"mt-3",children:[i.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[i.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:g("printers.filaments")}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),i.jsxs("div",{className:"space-y-3",children:[bt.length>0&&i.jsx("div",{className:"grid grid-cols-2 gap-3",children:bt.map(Nt=>{const wn=Rn[String(Nt.id)],Nr=Nt.id>=128?Nt.id-128:Nt.id,$t=wn!==void 0?wn:Nr,vr=$t===1,xi=$t===0;return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(DG,{ams:Nt,printerId:t.id,label:Cc(Nt.id,Nt.tray.length),amsLabels:ht,canEdit:C("printers:update"),onSaved:ft,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:ht?.[Nt.id]||Cc(Nt.id,Nt.tray.length)})}),nn&&(vr||xi)&&i.jsx(AG,{side:vr?"L":"R"})]}),(Nt.humidity!=null||Nt.temp!=null)&&i.jsxs("div",{className:"flex items-center gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[Nt.humidity!=null&&i.jsx(EG,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0}),Nt.temp!=null&&i.jsx(jG,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0})]})]}),i.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(rn=>{const Ln=Nt.tray[rn]||Nt.tray.find(Fr=>Fr.id===rn),Ho=Ln?.tray_type&&Ln.remain>=0,Gs=!Ln?.tray_type,bo=Nt.id*4+rn,Se=Je===bo,Dt=Ln?.tray_info_idx?kt?.[Ln.tray_info_idx]:null,sr=qe?.[bo],hr=Ln?.tray_uuid?.toUpperCase(),Ti=hr?c?.[hr]:void 0,Ua=uj(Ti),Xi=u?.(t.id,Nt.id,rn),Wn=(()=>{const Fr=Xi?.spool;return Fr&&Fr.label_weight>0&&Fr.weight_used!=null?Math.round(Math.max(0,Fr.label_weight-Fr.weight_used)/Fr.label_weight*100):null})(),Cs=Ua??Wn??(Ho?Ln.remain:null),Pf=Ua!==null?"spoolman":Wn!==null?"inventory":Ho?"ams":void 0,yi=Ln?.tray_type?{vendor:mj(Ln)?"Bambu Lab":"Generic",profile:Dt?.name||sr?.preset_name||Ln.tray_sub_brands||Ln.tray_type,colorName:oj(Ln.tray_id_name)||N1(Ln.tray_color),colorHex:Ln.tray_color||null,kFactor:lj(Ln.k),fillLevel:Cs,trayUuid:Ln.tray_uuid||null,tagUid:Ln.tag_uid||null,fillSource:Pf}:null,Ba=yr?.amsId===Nt.id&&yr?.slotId===rn,sd=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Gs?"opacity-50":""} ${Se?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(sj,{trayColor:Ln?.tray_color,trayType:Ln?.tray_type,isEmpty:Gs,slotNumber:rn+1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Ln?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Cs!==null&&Cs>=0&&Ln&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Cs}%`,backgroundColor:dj(Cs)}})})]});return i.jsxs("div",{className:"relative group",children:[Ba&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),we?.state!=="RUNNING"&&i.jsx("button",{onClick:Fr=>{Fr.stopPropagation(),Vs(ks?.amsId===Nt.id&&ks?.slotId===rn?null:{amsId:Nt.id,slotId:rn})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Bm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),we?.state!=="RUNNING"&&ks?.amsId===Nt.id&&ks?.slotId===rn&&i.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 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-xs flex items-center gap-2 ${C("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Fr=>{Fr.stopPropagation(),C("printers:ams_rfid")&&(fi.mutate({amsId:Nt.id,slotId:rn}),Vs(null))},disabled:Ba||!C("printers:ams_rfid"),title:C("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${Ba?"animate-spin":""}`}),g("printers.rfid.reread")]})}),yi?i.jsx(ij,{data:yi,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:yi.trayUuid?c?.[yi.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&yi.trayUuid?Fr=>{xe({tagUid:yi.tagUid||"",trayUuid:Fr,printerId:t.id,amsId:Nt.id,trayId:rn})}:void 0},inventory:o?void 0:(()=>{const Fr=u?.(t.id,Nt.id,rn);return{assignedSpool:Fr?.spool?{id:Fr.spool.id,material:Fr.spool.material,brand:Fr.spool.brand,color_name:Fr.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Fr.spool.label_weight-Fr.spool.weight_used))}:null,onAssignSpool:yi.vendor!=="Bambu Lab"?()=>de({printerId:t.id,amsId:Nt.id,trayId:rn,trayInfo:{type:yi.profile,color:yi.colorHex||"",location:`${Cc(Nt.id,Nt.tray.length)} Slot ${rn+1}`}}):void 0,onUnassignSpool:Fr&&yi.vendor!=="Bambu Lab"?()=>m?.(t.id,Nt.id,rn):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:rn,trayCount:Nt.tray.length,trayType:Ln?.tray_type||void 0,trayColor:Ln?.tray_color||void 0,traySubBrands:Ln?.tray_sub_brands||void 0,trayInfoIdx:Ln?.tray_info_idx||void 0,extruderId:wn,caliIdx:Ln?.cali_idx,savedPresetId:sr?.preset_id})},children:sd}):i.jsx(aj,{configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:rn,trayCount:Nt.tray.length,extruderId:wn})},children:sd})]},rn)})})]},Nt.id)})}),(It.length>0||we.vt_tray.length>0)&&i.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[It.map(Nt=>{const wn=Rn[String(Nt.id)],Nr=Nt.id>=128?Nt.id-128:Nt.id,$t=wn!==void 0?wn:Nr,vr=$t===1,xi=$t===0,rn=Nt.tray[0],Ln=rn?.tray_type&&rn.remain>=0,Ho=!rn?.tray_type,Gs=sk(Nt.id,rn?.id??0,!1),bo=Je===Gs,Se=rn?.tray_info_idx?kt?.[rn.tray_info_idx]:null,Dt=qe?.[Gs],sr=rn?.tray_uuid?.toUpperCase(),hr=sr?c?.[sr]:void 0,Ti=uj(hr),Ua=rn?.id??0,Xi=u?.(t.id,Nt.id,Ua),Wn=(()=>{const vi=Xi?.spool;return vi&&vi.label_weight>0&&vi.weight_used!=null?Math.round(Math.max(0,vi.label_weight-vi.weight_used)/vi.label_weight*100):null})(),Cs=Ti??Wn??(Ln?rn.remain:null),Pf=Ti!==null?"spoolman":Wn!==null?"inventory":Ln?"ams":void 0,yi=rn?.tray_type?{vendor:mj(rn)?"Bambu Lab":"Generic",profile:Se?.name||Dt?.preset_name||rn.tray_sub_brands||rn.tray_type,colorName:oj(rn.tray_id_name)||N1(rn.tray_color),colorHex:rn.tray_color||null,kFactor:lj(rn.k),fillLevel:Cs,trayUuid:rn.tray_uuid||null,tagUid:rn.tag_uid||null,fillSource:Pf}:null,Ba=rn?.id??0,sd=yr?.amsId===Nt.id&&yr?.slotId===Ba,Fr=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ho?"opacity-50":""} ${bo?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(sj,{trayColor:rn?.tray_color,trayType:rn?.tray_type,isEmpty:Ho,slotNumber:1}),i.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:rn?.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Cs!==null&&Cs>=0&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Cs}%`,backgroundColor:dj(Cs)}})})]});return i.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[i.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[i.jsx(DG,{ams:Nt,printerId:t.id,label:Cc(Nt.id,Nt.tray.length),amsLabels:ht,canEdit:C("printers:update"),onSaved:ft,children:i.jsx("span",{className:"text-[10px] text-white font-medium cursor-default select-none",children:ht?.[Nt.id]||Cc(Nt.id,Nt.tray.length)})}),nn&&(vr||xi)&&i.jsx(AG,{side:vr?"L":"R"})]}),i.jsxs("div",{className:"flex gap-1.5 max-[550px]:flex-col max-[550px]:items-start",children:[i.jsxs("div",{className:"relative group flex-1 max-[550px]:w-full",children:[sd&&i.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:i.jsx(Sr,{className:"w-4 h-4 text-bambu-green animate-spin"})}),we?.state!=="RUNNING"&&i.jsx("button",{onClick:vi=>{vi.stopPropagation(),Vs(ks?.amsId===Nt.id&&ks?.slotId===Ba?null:{amsId:Nt.id,slotId:Ba})},className:"absolute -top-1 -right-1 w-4 h-4 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:bg-bambu-dark-tertiary",title:g("printers.slotOptions"),children:i.jsx(Bm,{className:"w-2.5 h-2.5 text-bambu-gray"})}),we?.state!=="RUNNING"&&ks?.amsId===Nt.id&&ks?.slotId===Ba&&i.jsx("div",{className:"absolute top-full left-0 mt-1 z-50 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-xs flex items-center gap-2 ${C("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:vi=>{vi.stopPropagation(),C("printers:ams_rfid")&&(fi.mutate({amsId:Nt.id,slotId:Ba}),Vs(null))},disabled:sd||!C("printers:ams_rfid"),title:C("printers:ams_rfid")?void 0:g("printers.permission.noAmsRfid"),children:[i.jsx(Sr,{className:`w-3 h-3 ${sd?"animate-spin":""}`}),g("printers.rfid.reread")]})}),yi?i.jsx(ij,{data:yi,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:yi.trayUuid?c?.[yi.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&yi.trayUuid?vi=>{xe({tagUid:yi.tagUid||"",trayUuid:vi,printerId:t.id,amsId:Nt.id,trayId:Ba})}:void 0},inventory:o?void 0:(()=>{const vi=u?.(t.id,Nt.id,Ba);return{assignedSpool:vi?.spool?{id:vi.spool.id,material:vi.spool.material,brand:vi.spool.brand,color_name:vi.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(vi.spool.label_weight-vi.spool.weight_used))}:null,onAssignSpool:yi.vendor!=="Bambu Lab"?()=>de({printerId:t.id,amsId:Nt.id,trayId:Ba,trayInfo:{type:yi.profile,color:yi.colorHex||"",location:Cc(Nt.id,Nt.tray.length)}}):void 0,onUnassignSpool:vi&&yi.vendor!=="Bambu Lab"?()=>m?.(t.id,Nt.id,Ba):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:Ba,trayCount:Nt.tray.length,trayType:rn?.tray_type||void 0,trayColor:rn?.tray_color||void 0,traySubBrands:rn?.tray_sub_brands||void 0,trayInfoIdx:rn?.tray_info_idx||void 0,extruderId:wn,caliIdx:rn?.cali_idx,savedPresetId:Dt?.preset_id})},children:Fr}):i.jsx(aj,{configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:Nt.id,trayId:Ba,trayCount:Nt.tray.length,extruderId:wn})},children:Fr})]}),(Nt.humidity!=null||Nt.temp!=null)&&i.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0 max-[550px]:w-full",children:[Nt.temp!=null&&i.jsx(jG,{temp:Nt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"temperature"}),compact:!0}),Nt.humidity!=null&&i.jsx(EG,{humidity:Nt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>F({amsId:Nt.id,amsLabel:Cc(Nt.id,Nt.tray.length),mode:"humidity"}),compact:!0})]})]})]},Nt.id)}),we.vt_tray.length>0&&i.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${we.vt_tray.length===1?"max-w-[50%]":""}`,children:[i.jsx("div",{className:"flex items-center gap-1 mb-2",children:i.jsx("span",{className:"text-[10px] text-white font-medium",children:g("printers.external")})}),i.jsx("div",{className:`grid ${we.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...we.vt_tray].sort((Nt,wn)=>(Nt.id??254)-(wn.id??254)).map(Nt=>{const wn=Nt.id??254,Nr=nn&&Je===254?wn===254&&we.active_extruder===1||wn===255&&we.active_extruder===0:Je===wn,$t=wn-254,vr=nn?g(wn===254?"printers.extL":"printers.extR"):"",xi=Nt.tray_info_idx?kt?.[Nt.tray_info_idx]:null,rn=qe?.[1020+$t],Ln=Nt.tray_uuid?.toUpperCase(),Ho=Ln?c?.[Ln]:void 0,Gs=uj(Ho),bo=u?.(t.id,255,$t),Se=(()=>{const Wn=bo?.spool;return Wn&&Wn.label_weight>0&&Wn.weight_used!=null?Math.round(Math.max(0,Wn.label_weight-Wn.weight_used)/Wn.label_weight*100):null})(),Dt=Nt.tray_type&&Nt.remain>=0,sr=Gs??Se??(Dt?Nt.remain:null),hr=Gs!==null?"spoolman":Se!==null?"inventory":Dt?"ams":void 0,Ti={vendor:mj(Nt)?"Bambu Lab":"Generic",profile:xi?.name||rn?.preset_name||Nt.tray_sub_brands||Nt.tray_type||"Unknown",colorName:oj(Nt.tray_id_name)||N1(Nt.tray_color),colorHex:Nt.tray_color||null,kFactor:lj(Nt.k),fillLevel:sr,trayUuid:Nt.tray_uuid||null,tagUid:Nt.tag_uid||null,fillSource:hr},Ua=!Nt.tray_type,Xi=i.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Ua?"opacity-50":""} ${Nr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[i.jsx(sj,{trayColor:Nt.tray_color,trayType:Nt.tray_type,isEmpty:Ua,slotNumber:$t+1}),i.jsx("div",{className:`text-[9px] font-bold truncate ${Ua?"text-white/40":"text-white"}`,children:Nt.tray_type||"—"}),i.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:sr!==null&&sr>=0&&!Ua&&i.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${sr}%`,backgroundColor:dj(sr)}})}),vr&&i.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:vr})]});return i.jsx("div",{className:"relative group",children:Ua?i.jsx(aj,{configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:255,trayId:$t,trayCount:1,extruderId:nn?wn===254?1:0:void 0})},children:Xi}):i.jsx(ij,{data:Ti,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Ti.trayUuid?c?.[Ti.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:d,onLinkSpool:o&&Ti.trayUuid?Wn=>{xe({tagUid:Ti.tagUid||"",trayUuid:Wn,printerId:t.id,amsId:255,trayId:$t})}:void 0},inventory:o?void 0:(()=>{const Wn=u?.(t.id,255,$t);return{assignedSpool:Wn?.spool?{id:Wn.spool.id,material:Wn.spool.material,brand:Wn.spool.brand,color_name:Wn.spool.color_name,remainingWeightGrams:Math.max(0,Math.round(Wn.spool.label_weight-Wn.spool.weight_used))}:null,onAssignSpool:()=>de({printerId:t.id,amsId:255,trayId:$t,trayInfo:{type:Ti.profile,color:Ti.colorHex||"",location:vr||g("printers.external")}}),onUnassignSpool:Wn?()=>m?.(t.id,255,$t):void 0}})(),configureSlot:{enabled:C("printers:control"),onConfigure:()=>_e({amsId:255,trayId:$t,trayCount:1,trayType:Nt.tray_type||void 0,trayColor:Nt.tray_color||void 0,traySubBrands:Nt.tray_sub_brands||void 0,trayInfoIdx:Nt.tray_info_idx||void 0,extruderId:nn?wn===254?1:0:void 0,caliIdx:Nt.cali_idx,savedPresetId:rn?.preset_id})},children:Xi})},wn)})})]})]})]})]})})()]}),tt&&r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx(ac,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"text-sm text-white truncate",children:tt.name}),Rt&&i.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${Rt.state==="ON"?"bg-bambu-green/20 text-bambu-green":Rt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[Rt.state||"?",Rt.state==="ON"&&Rt.energy?.power!=null&&i.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",Rt.energy.power,"W"]})]})]}),i.jsx("div",{className:"flex-1"}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{onClick:()=>le(!0),disabled:jt.isPending||Rt?.state==="ON"||!C("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${C("smart_plugs:control")?Rt?.state==="ON"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:C("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(Su,{className:"w-3 h-3"}),"On"]}),i.jsxs("button",{onClick:()=>he(!0),disabled:jt.isPending||Rt?.state==="OFF"||!C("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${C("smart_plugs:control")?Rt?.state==="OFF"?"bg-red-500/30 text-red-400":"bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary":"bg-bambu-dark text-bambu-gray/50 cursor-not-allowed"}`,title:C("smart_plugs:control")?void 0:g("printers.permission.noSmartPlugControl"),children:[i.jsx(pC,{className:"w-3 h-3"}),"Off"]})]}),i.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[i.jsx("span",{className:`text-xs hidden sm:inline ${tt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:tt.auto_off_executed?"Auto-off done":"Auto-off"}),i.jsx("button",{onClick:()=>Ft.mutate(!tt.auto_off),disabled:Ft.isPending||tt.auto_off_executed||!C("smart_plugs:control"),title:C("smart_plugs:control")?tt.auto_off_executed?g("printers.autoOffExecuted"):g("printers.autoOffAfterPrint"):g("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${C("smart_plugs:control")?tt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":tt.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:i.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${tt.auto_off||tt.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Ye&&Ye.length>0&&i.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[i.jsx(j0,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),i.jsx("div",{className:"flex flex-wrap gap-1",children:Ye.map(bt=>i.jsxs("button",{onClick:()=>cn.mutate(bt.id),disabled:cn.isPending,title:`Run ${bt.ha_entity_id}`,className:"px-2 py-0.5 text-xs bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded transition-colors flex items-center gap-1",children:[i.jsx(uo,{className:"w-2.5 h-2.5"}),bt.name]},bt.id))})]})]}),r==="expanded"&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex items-center justify-end gap-2 flex-wrap",children:[i.jsx(Oe,{variant:"secondary",size:"sm",onClick:()=>In.mutate(!we?.chamber_light),disabled:!we?.connected||In.isPending||!C("printers:control"),title:C("printers:control")?we?.chamber_light?g("printers.chamberLightOff"):g("printers.chamberLightOn"):g("printers.permission.noControl"),className:we?.chamber_light?"!border-yellow-500 !text-yellow-400 hover:!bg-yellow-500/20":"",children:i.jsx(ML,{on:we?.chamber_light??!1,className:`w-4 h-4 ${we?.chamber_light?"text-yellow-400":""}`})}),i.jsx(Oe,{variant:"secondary",size:"sm",onClick:()=>{if(f==="embedded"&&x)x(t.id,t.name);else{const bt=localStorage.getItem("cameraWindowState"),It=bt?JSON.parse(bt):{width:640,height:400},nn=[`width=${It.width}`,`height=${It.height}`,It.left!==void 0?`left=${It.left}`:"",It.top!==void 0?`top=${It.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,nn)}},disabled:!we?.connected||!C("camera:view"),title:C("camera:view")?g(f==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"):g("printers.permission.noCamera"),children:i.jsx(ZF,{className:"w-4 h-4"})}),i.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[i.jsx(Oe,{variant:"secondary",size:"sm",onClick:_h,disabled:!we?.connected||Xt.isPending||!C("printers:update"),title:C("printers:update")?t.plate_detection_enabled?g("printers.plateDetection.enabledClick"):g("printers.plateDetection.disabledClick"):g("printers.plateDetection.noPermission"),className:`!rounded-r-none !border-r-0 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Xt.isPending?i.jsx(lt,{className:"w-4 h-4 animate-spin"}):i.jsx(V1,{className:"w-4 h-4"})}),i.jsx(Oe,{variant:"secondary",size:"sm",onClick:kf,disabled:!we?.connected||Me||!C("printers:update"),title:C("printers:update")?g("printers.plateDetection.manageCalibration"):g("printers.plateDetection.noPermission"),className:`!rounded-l-none !px-1.5 ${t.plate_detection_enabled?"!border-green-500 !text-green-400 hover:!bg-green-500/20":""}`,children:Me?i.jsx(lt,{className:"w-3 h-3 animate-spin"}):i.jsx(jn,{className:"w-3 h-3"})})]}),i.jsxs(Oe,{variant:"secondary",size:"sm",onClick:()=>O(!0),disabled:!on||!C("printers:files"),title:C("printers:files")?g("printers.browseFiles"):g("printers.permission.noFiles"),children:[i.jsx(cx,{className:"w-4 h-4"}),g("printers.files")]}),on&&we?.state!=="RUNNING"&&we?.state!=="PAUSE"&&i.jsxs(Oe,{size:"sm",onClick:()=>B(!0),disabled:!C("printers:control"),title:C("printers:control")?g("common.print"):g("printers.permission.noControl"),className:"!bg-bambu-green hover:!bg-bambu-green/80 !text-white",children:[i.jsx(_r,{className:"w-4 h-4"}),g("common.print")]})]})]}),W&&i.jsx(gAe,{printerId:t.id,printerName:t.name,onClose:()=>O(!1)}),G&&i.jsx(Yne,{folderId:null,onClose:()=>B(!1),onUploadComplete:()=>{},autoUpload:!0,accept:".gcode,.3mf",validateFile:bt=>{const It=bt.name.toLowerCase();if(!It.endsWith(".gcode")&&!It.includes(".gcode."))return g("printers.dropNotPrintable","Only .gcode and .gcode.3mf files can be printed")},onFileUploaded:bt=>{const It=bt.metadata?.sliced_for_model,nn=pv(t.model);if(It&&nn&&It.toLowerCase()!==nn.toLowerCase())return fe.deleteLibraryFile(bt.id).catch(()=>{}),g("printers.incompatibleFile","This file was sliced for {{slicedFor}}, but this printer is a {{printerModel}}",{slicedFor:It,printerModel:nn});Z({id:bt.id,filename:bt.filename})}}),ee&&i.jsx(Vc,{mode:"reprint",libraryFileId:ee.id,archiveName:ee.filename,initialSelectedPrinterIds:[t.id],onClose:()=>Z(null),onSuccess:()=>Z(null)}),te&&i.jsx(SAe,{printerId:t.id,printerName:t.name,onClose:()=>re(!1)}),ie&&i.jsx(iqe,{printer:t,status:we,totalPrintHours:n?.total_print_hours,onClose:V}),Fe&&i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>za(),children:i.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl shadow-2xl max-w-lg w-full",onClick:bt=>bt.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[Fe.needs_calibration?i.jsx(V1,{className:"w-5 h-5 text-blue-500"}):Fe.is_empty?i.jsx(pr,{className:"w-5 h-5 text-green-500"}):i.jsx(Vi,{className:"w-5 h-5 text-yellow-500"}),i.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),Fe.reference_count!==void 0&&Fe.max_references&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[Fe.reference_count,"/",Fe.max_references," refs"]})]}),i.jsx("button",{onClick:()=>za(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[Fe.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[i.jsx("p",{className:"font-medium text-blue-400",children:g("printers.plateDetection.calibrationRequired")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationInstructions")}})]}),i.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[i.jsx("p",{children:g("printers.plateDetection.calibrationDescription")}),i.jsx("p",{dangerouslySetInnerHTML:{__html:g("printers.plateDetection.calibrationTip")}})]})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:`p-3 rounded-lg ${Fe.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[i.jsx("p",{className:`font-medium ${Fe.is_empty?"text-green-400":"text-yellow-400"}`,children:Fe.is_empty?g("printers.plateDetection.plateEmpty"):g("printers.plateDetection.objectsDetected")}),i.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[g("printers.plateDetection.confidence"),": ",Math.round(Fe.confidence*100),"% | ",g("printers.plateDetection.difference"),": ",Fe.difference_percent.toFixed(1),"%"]})]}),Fe.debug_image_url&&i.jsxs("div",{children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:g("printers.plateDetection.analysisPreview")}),i.jsx("img",{src:Fe.debug_image_url,alt:g("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:g("printers.plateDetection.analysisLegend")})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:Fe.message})]}),Zn&&Zn.references.length>0&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsx("p",{className:"text-sm font-medium text-white mb-2",children:g("printers.plateDetection.savedReferences",{count:Zn.references.length,max:Zn.max_references})}),i.jsx("div",{className:"grid grid-cols-5 gap-2",children:Zn.references.map(bt=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:fe.getPlateReferenceThumbnailUrl(t.id,bt.index),alt:bt.label||`Reference ${bt.index+1}`,className:"w-full aspect-video object-cover rounded border border-bambu-dark-tertiary"}),i.jsx("button",{onClick:()=>hc(bt.index),className:"absolute top-1 right-1 p-0.5 bg-red-500/80 rounded opacity-0 group-hover:opacity-100 transition-opacity",title:g("printers.plateDetection.deleteReference"),children:i.jsx(zt,{className:"w-3 h-3 text-white"})}),ni?.index===bt.index?i.jsx("input",{type:"text",value:ni.label,onChange:It=>Rr({...ni,label:It.target.value}),onBlur:()=>mc(bt.index,ni.label),onKeyDown:It=>{It.key==="Enter"&&mc(bt.index,ni.label),It.key==="Escape"&&Rr(null)},className:"w-full mt-1 px-1 py-0.5 text-xs bg-bambu-dark-tertiary border border-bambu-green rounded text-white",autoFocus:!0,placeholder:g("printers.plateDetection.labelPlaceholder")}):i.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Rr({index:bt.index,label:bt.label}),title:bt.label?g("printers.plateDetection.clickToEdit",{label:bt.label}):g("printers.plateDetection.clickToAddLabel"),children:bt.label||i.jsx("span",{className:"italic opacity-50",children:g("printers.noLabel")})}),i.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:bt.timestamp?er(bt.timestamp)?.toLocaleDateString()??"":""})]},bt.index))})]}),!Fe.needs_calibration&&i.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center justify-between mb-2",children:[i.jsx("p",{className:"text-sm font-medium text-white",children:g("printers.roi.title")}),be?i.jsxs("div",{className:"flex gap-1",children:[i.jsx(Oe,{variant:"ghost",size:"sm",onClick:()=>He(null),disabled:Ce,children:g("common.cancel")}),i.jsx(Oe,{size:"sm",onClick:Yi,disabled:Ce,children:Ce?i.jsx(lt,{className:"w-3 h-3 animate-spin"}):g("common.save")})]}):i.jsxs(Oe,{variant:"ghost",size:"sm",onClick:()=>He(Fe.roi||{x:.15,y:.35,w:.7,h:.55}),children:[i.jsx(Ki,{className:"w-3 h-3 mr-1"}),g("common.edit")]})]}),be?i.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.xStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:be.x,onChange:bt=>He({...be,x:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.x*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.roi.yStart")}),i.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:be.y,onChange:bt=>He({...be,y:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.y*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.width")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:be.w,onChange:bt=>He({...be,w:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.w*100),"%"]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"text-xs text-bambu-gray",children:g("printers.height")}),i.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:be.h,onChange:bt=>He({...be,h:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(be.h*100),"%"]})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:g("printers.roi.instruction")})]}):i.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((Fe.roi?.x||.15)*100),"%, Y=",Math.round((Fe.roi?.y||.35)*100),"%, W=",Math.round((Fe.roi?.w||.7)*100),"%, H=",Math.round((Fe.roi?.h||.55)*100),"%"]})]})]}),i.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:Fe.needs_calibration?i.jsxs(i.Fragment,{children:[i.jsx(Oe,{variant:"ghost",onClick:()=>za(),children:g("common.cancel")}),i.jsx(Oe,{onClick:()=>Cf(),disabled:Pe,children:Pe?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):i.jsxs(i.Fragment,{children:[i.jsx(Oe,{variant:"ghost",onClick:()=>Cf(),disabled:Pe,children:Pe?"Adding...":`Add Reference (${Zn?.references.length||0}/${Zn?.max_references||5})`}),i.jsx(Oe,{onClick:()=>za(),children:"Close"})]})})]})}),J&&tt&&i.jsx(_n,{title:g("printers.confirm.powerOnTitle"),message:g("printers.confirm.powerOnMessage",{name:t.name}),confirmText:g("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{jt.mutate("on"),le(!1)},onCancel:()=>le(!1)}),me&&tt&&i.jsx(_n,{title:g("printers.confirm.powerOffTitle"),message:we?.state==="RUNNING"?g("printers.confirm.powerOffWarning",{name:t.name}):g("printers.confirm.powerOffMessage",{name:t.name}),confirmText:g("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{jt.mutate("off"),he(!1)},onCancel:()=>he(!1)}),oe&&i.jsx(_n,{title:g("printers.confirm.stopTitle"),message:g("printers.confirm.stopMessage",{name:t.name}),confirmText:g("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{Jt.mutate(),ye(!1)},onCancel:()=>ye(!1)}),Ee&&i.jsx(_n,{title:g("printers.confirm.pauseTitle"),message:g("printers.confirm.pauseMessage",{name:t.name}),confirmText:g("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{fn.mutate(),q(!1)},onCancel:()=>q(!1)}),K&&i.jsx(_n,{title:g("printers.confirm.resumeTitle"),message:g("printers.confirm.resumeMessage",{name:t.name}),confirmText:g("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Pn.mutate(),E(!1)},onCancel:()=>E(!1)}),i.jsx(EL,{printerId:t.id,isOpen:j,onClose:()=>L(!1)}),X&&i.jsx(CAe,{printerName:t.name,errors:we?.hms_errors||[],onClose:()=>ae(!1),printerId:t.id,hasPermission:C}),I&&i.jsx(L$e,{isOpen:!!I,onClose:()=>F(null),printerId:t.id,printerName:t.name,amsId:I.amsId,amsLabel:I.amsLabel,initialMode:I.mode,thresholds:s}),Q&&i.jsx(O$e,{isOpen:!!Q,onClose:()=>xe(null),tagUid:Q.tagUid,trayUuid:Q.trayUuid,printerId:Q.printerId,amsId:Q.amsId,trayId:Q.trayId}),pe&&i.jsx(I$e,{isOpen:!!pe,onClose:()=>de(null),printerId:pe.printerId,amsId:pe.amsId,trayId:pe.trayId,trayInfo:pe.trayInfo}),Ae&&i.jsx(Kne,{isOpen:!!Ae,onClose:()=>_e(null),printerId:t.id,slotInfo:Ae,printerModel:pv(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),$&&i.jsx(xqe,{printer:t,onClose:()=>U(!1)}),Ue&&Ge&&i.jsx(bqe,{printer:t,firmwareInfo:Ge,onClose:()=>$e(!1)}),ks&&i.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Vs(null)})]})}function gqe({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Mt(),[a,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,d]=w.useState([]),[u,m]=w.useState(""),[p,f]=w.useState(!1),[x,v]=w.useState(!1),[g,y]=w.useState([]),[_,N]=w.useState(""),[C,T]=w.useState({scanned:0,total:0});w.useEffect(()=>{yc.getInfo().then(A=>{v(A.is_docker),A.subnets.length>0&&(y(A.subnets),N(A.subnets[0]))}).catch(()=>{})},[]);const P=c.filter(A=>!n.includes(A.serial)),k=async()=>{m(""),d([]),l(!0),f(!1),T({scanned:0,total:0});try{if(x){await yc.startSubnetScan(_);const A=setInterval(async()=>{try{const R=await yc.getScanStatus();T({scanned:R.scanned,total:R.total});const $=await yc.getDiscoveredPrinters();d($),R.running||(clearInterval(A),l(!1),f(!0))}catch(R){console.error("Failed to get scan status:",R)}},500)}else{await yc.startDiscovery(10);const A=setInterval(async()=>{try{const R=await yc.getDiscoveredPrinters();d(R)}catch(R){console.error("Failed to get discovered printers:",R)}},1e3);setTimeout(async()=>{clearInterval(A);try{await yc.stopDiscovery()}catch{}l(!1),f(!0);try{const R=await yc.getDiscoveredPrinters();d(R)}catch(R){console.error("Failed to get final discovered printers:",R)}},1e4)}}catch(A){console.error("Failed to start discovery:",A),m(A instanceof Error?A.message:r("printers.discovery.failedToStart")),l(!1),f(!0)}},D=A=>{const R=A.serial.startsWith("unknown-")?"":A.serial;s({...a,name:A.name||"",serial_number:R,ip_address:A.ip_address,model:pv(A.model)}),d([])};return w.useEffect(()=>()=>{yc.stopDiscovery().catch(()=>{}),yc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const A=R=>{R.key==="Escape"&&t()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t]),i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:i.jsx(Tt,{className:"w-full max-w-md",onClick:A=>A.stopPropagation(),children:i.jsxs(Pt,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),i.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&i.jsxs("div",{className:"mb-3",children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),g.length>0?i.jsx("select",{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 text-sm",value:_,onChange:A=>N(A.target.value),disabled:o,children:g.map(A=>i.jsx("option",{value:A,children:A},A))}):i.jsx("input",{type:"text",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 text-sm",value:_,onChange:A=>N(A.target.value),placeholder:"192.168.1.0/24",disabled:o}),i.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),i.jsx(Oe,{type:"button",variant:"secondary",onClick:k,disabled:o,className:"w-full",children:o?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),x&&C.total>0?r("printers.discovery.scanProgress",{scanned:C.scanned,total:C.total}):r("printers.discovery.scanning")]}):i.jsxs(i.Fragment,{children:[i.jsx(jr,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),u&&i.jsx("div",{className:"mt-2 text-sm text-red-400",children:u}),P.length>0&&i.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:P.map(A=>i.jsxs("div",{className:"flex items-center justify-between p-2 bg-bambu-dark rounded-lg hover:bg-bambu-dark-secondary cursor-pointer transition-colors",onClick:()=>D(A),children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium text-white text-sm truncate",children:A.name||A.serial}),i.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[pv(A.model)||r("printers.discovery.unknown")," • ",A.ip_address,A.serial.startsWith("unknown-")&&i.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),i.jsx(jn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},A.serial))}),o&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),p&&!o&&c.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),p&&!o&&c.length>0&&P.length===0&&i.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),i.jsxs("form",{onSubmit:A=>{A.preventDefault(),e(a)},className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),i.jsx("input",{type:"text",required:!0,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",value:a.name,onChange:A=>s({...a,name:A.target.value}),placeholder:r("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),i.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",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",value:a.ip_address,onChange:A=>s({...a,ip_address:A.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),i.jsx("input",{type:"text",required:!0,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",value:a.serial_number,onChange:A=>s({...a,serial_number:A.target.value}),placeholder:"01P00A000000000"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),i.jsx("input",{type:"password",required:!0,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",value:a.access_code,onChange:A=>s({...a,access_code:A.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),i.jsxs("select",{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",value:a.model||"",onChange:A=>s({...a,model:A.target.value}),children:[i.jsx("option",{value:"",children:r("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),i.jsx("input",{type:"text",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",value:a.location||"",onChange:A=>s({...a,location:A.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"auto_archive",checked:a.auto_archive,onChange:A=>s({...a,auto_archive:A.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),i.jsx(Oe,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function bqe({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Mt(),a=Zt(),{showToast:s}=hn(),{hasPermission:o}=Dr(),l=o("firmware:update"),[c,d]=w.useState(null),[u,m]=w.useState(!1),[p,f]=w.useState(null),{data:x,isLoading:v}=Ze({queryKey:["firmwarePrepare",t.id],queryFn:()=>l1.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),g=dt({mutationFn:()=>l1.startUpload(t.id),onSuccess:()=>{m(!0);const _=setInterval(async()=>{try{const N=await l1.getUploadStatus(t.id);d(N),(N.status==="complete"||N.status==="error")&&(clearInterval(_),f(null),m(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),a.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);f(_)},onError:_=>{s(r("printers.firmwareModal.uploadFailed",{error:_.message}),"error"),m(!1)}});w.useEffect(()=>()=>{p&&clearInterval(p)},[p]);const y=()=>{d(null),g.mutate()};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:i.jsx(Tt,{className:"w-full max-w-md mx-4",children:i.jsxs(Pt,{children:[i.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[i.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?i.jsx(hi,{className:"w-5 h-5 text-orange-400"}):i.jsx(pr,{className:"w-5 h-5 text-status-ok"})}),i.jsxs("div",{className:"flex-1",children:[i.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),i.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),i.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[i.jsxs("div",{className:"flex justify-between items-center text-sm",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),i.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&i.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[i.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),i.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&i.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[i.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),i.jsx("div",{className:"mt-2 text-bambu-gray text-xs max-h-40 overflow-y-auto whitespace-pre-wrap",children:e.release_notes})]})]}),e.update_available?v?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!u&&!c?i.jsx("div",{className:"mb-4",children:x.can_proceed?i.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[i.jsx(ia,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):i.jsx("div",{className:"space-y-1",children:x.errors.map((_,N)=>i.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[i.jsx(zi,{className:"w-4 h-4 flex-shrink-0"}),_]},N))})}):null:null,(u||c)&&c&&i.jsxs("div",{className:"mb-4",children:[i.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[i.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),i.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),i.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:i.jsx("div",{className:`h-2 rounded-full transition-all ${c.status==="error"?"bg-status-error":c.status==="complete"?"bg-status-ok":"bg-orange-500"} ${c.status==="uploading"?"animate-pulse":""}`,style:{width:`${c.progress}%`}})}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&i.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&i.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[i.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),i.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),i.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),i.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),i.jsxs("div",{className:"flex gap-2 justify-end",children:[i.jsx(Oe,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!u&&c?.status!=="complete"&&l&&i.jsx(Oe,{onClick:y,disabled:g.isPending,children:g.isPending?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):i.jsxs(i.Fragment,{children:[i.jsx(hi,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function xqe({printer:t,onClose:e}){const{t:n}=Mt(),r=Zt(),{showToast:a}=hn(),[s,o]=w.useState({name:t.name,ip_address:t.ip_address,access_code:"",model:t.model||"",location:t.location||"",auto_archive:t.auto_archive}),l=dt({mutationFn:d=>fe.updatePrinter(t.id,d),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:d=>a(d.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const d=u=>{u.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const c=d=>{d.preventDefault();const u={name:s.name,ip_address:s.ip_address,model:s.model||void 0,location:s.location||void 0,auto_archive:s.auto_archive};s.access_code&&(u.access_code=s.access_code),l.mutate(u)};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:i.jsx(Tt,{className:"w-full max-w-md",onClick:d=>d.stopPropagation(),children:i.jsxs(Pt,{children:[i.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),i.jsxs("form",{onSubmit:c,className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),i.jsx("input",{type:"text",required:!0,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",value:s.name,onChange:d=>o({...s,name:d.target.value}),placeholder:n("printers.modal.myPrinter")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),i.jsx("input",{type:"text",required:!0,pattern:"(\\d{1,3}(\\.\\d{1,3}){3}|[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?)*)",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",value:s.ip_address,onChange:d=>o({...s,ip_address:d.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),i.jsx("input",{type:"text",disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed",value:t.serial_number}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),i.jsx("input",{type:"password",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",value:s.access_code,onChange:d=>o({...s,access_code:d.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),i.jsxs("select",{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",value:s.model,onChange:d=>o({...s,model:d.target.value}),children:[i.jsx("option",{value:"",children:n("printers.modal.selectModel")}),i.jsxs("optgroup",{label:"H2 Series",children:[i.jsx("option",{value:"H2C",children:"H2C"}),i.jsx("option",{value:"H2D",children:"H2D"}),i.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),i.jsx("option",{value:"H2S",children:"H2S"})]}),i.jsxs("optgroup",{label:"X1 Series",children:[i.jsx("option",{value:"X1E",children:"X1E"}),i.jsx("option",{value:"X1C",children:"X1 Carbon"}),i.jsx("option",{value:"X1",children:"X1"})]}),i.jsxs("optgroup",{label:"P Series",children:[i.jsx("option",{value:"P2S",children:"P2S"}),i.jsx("option",{value:"P1S",children:"P1S"}),i.jsx("option",{value:"P1P",children:"P1P"})]}),i.jsxs("optgroup",{label:"A1 Series",children:[i.jsx("option",{value:"A1",children:"A1"}),i.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),i.jsx("input",{type:"text",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",value:s.location,onChange:d=>o({...s,location:d.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:d=>o({...s,auto_archive:d.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),i.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),i.jsxs("div",{className:"flex gap-3 pt-4",children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),i.jsx(Oe,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function yqe(t){const{data:e}=Ze({queryKey:["printerStatus",t],queryFn:()=>fe.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function vqe({printer:t,plug:e,onPowerOn:n,isPowering:r}){const a=yqe(t.id),{data:s}=Ze({queryKey:["smartPlugStatus",e.id],queryFn:()=>fe.getSmartPlugStatus(e.id),refetchInterval:1e4});return a?i.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&i.jsx("span",{className:`text-xs px-1.5 py-0.5 rounded ${s.state==="ON"?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:s.state||"?"})]}),i.jsxs("button",{onClick:()=>n(e.id),disabled:r||s?.state==="ON",className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${s?.state==="ON"?"bg-bambu-green/20 text-bambu-green cursor-default":"bg-bambu-green/20 text-bambu-green hover:bg-bambu-green hover:text-white"}`,children:[i.jsx(Su,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function wqe(){const{t}=Mt(),[e,n]=w.useState(!1),[r,a]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[d,u]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[m,p]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[f,x]=w.useState(()=>{const L=localStorage.getItem("printerCardSize");return L?parseInt(L,10):2}),v=f===1?"compact":"expanded",g=Zt(),{showToast:y}=hn(),{hasPermission:_}=Dr(),[N,C]=w.useState(()=>{const L=localStorage.getItem("openEmbeddedCameras");if(L)try{const G=JSON.parse(L);return new Map(G.map(B=>[B.id,B]))}catch{return new Map}return new Map});w.useEffect(()=>{const L=Array.from(N.values());L.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(L)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:T,isLoading:P}=Ze({queryKey:["printers"],queryFn:fe.getPrinters}),{data:k}=Ze({queryKey:["settings"],queryFn:fe.getSettings});w.useEffect(()=>{k?.camera_view_mode==="window"&&N.size>0&&C(new Map)},[k?.camera_view_mode,N.size]);const{data:D}=Ze({queryKey:["smart-plugs"],queryFn:fe.getSmartPlugs}),{data:A}=Ze({queryKey:["maintenanceOverview"],queryFn:fe.getMaintenanceOverview,staleTime:60*1e3}),{data:R}=Ze({queryKey:["spoolman-status"],queryFn:fe.getSpoolmanStatus,staleTime:60*1e3}),$=R?.enabled&&R?.connected,{data:U}=Ze({queryKey:["unlinked-spools"],queryFn:fe.getUnlinkedSpools,enabled:!!$,staleTime:30*1e3}),W=U&&U.length>0,{data:O}=Ze({queryKey:["linked-spools"],queryFn:fe.getLinkedSpools,enabled:!!$,staleTime:30*1e3}),te=O?.linked,{data:re}=Ze({queryKey:["spool-assignments"],queryFn:()=>fe.getAssignments(),enabled:_("inventory:view_assignments"),staleTime:30*1e3}),J=dt({mutationFn:({printerId:L,amsId:G,trayId:B})=>fe.unassignSpool(L,G,B),onSuccess:()=>{g.invalidateQueries({queryKey:["spool-assignments"]})}}),le=(L,G,B)=>re?.find(ie=>ie.printer_id===L&&ie.ams_id===Number(G)&&ie.tray_id===Number(B)),me=A?.reduce((L,G)=>(L[G.printer_id]={due_count:G.due_count,warning_count:G.warning_count,total_print_hours:G.total_print_hours},L),{})||{},he=D?.reduce((L,G)=>(G.printer_id&&(L[G.printer_id]=G),L),{})||{},X=dt({mutationFn:fe.createPrinter,onSuccess:()=>{g.invalidateQueries({queryKey:["printers"]}),g.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:L=>y(L.message||t("printers.toast.failedToAdd"),"error")}),ae=dt({mutationFn:L=>fe.controlSmartPlug(L,"on"),onSuccess:()=>{g.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),oe=()=>{const L=!r;a(L),localStorage.setItem("hideDisconnectedPrinters",String(L))},ye=L=>{u(L),localStorage.setItem("printerSortBy",L)},Ee=()=>{const L=!m;p(L),localStorage.setItem("printerSortAsc",String(L))},q=()=>{switch(f){case 1:return"grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5";case 2:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3";case 3:return"grid-cols-1 lg:grid-cols-2";case 4:return"grid-cols-1";default:return"grid-cols-1 md:grid-cols-2 xl:grid-cols-3"}},K=["S","M","L","XL"],E=w.useMemo(()=>{if(!T)return[];const L=[...T];switch(d){case"name":L.sort((G,B)=>G.name.localeCompare(B.name));break;case"model":L.sort((G,B)=>(G.model||"").localeCompare(B.model||""));break;case"location":L.sort((G,B)=>{const ie=G.location||"",z=B.location||"";return!ie&&z?1:ie&&!z?-1:ie.localeCompare(z)||G.name.localeCompare(B.name)});break;case"status":L.sort((G,B)=>{const ie=g.getQueryData(["printerStatus",G.id]),z=g.getQueryData(["printerStatus",B.id]),V=ee=>ee?.connected?ee.state==="RUNNING"?0:1:2;return V(ie)-V(z)});break}return m||L.reverse(),L},[T,d,m,g]),j=w.useMemo(()=>{if(d!=="location")return null;const L={};return E.forEach(G=>{const B=G.location||"Ungrouped";L[B]||(L[B]=[]),L[B].push(G)}),L},[d,E]);return i.jsxs("div",{className:"p-4 md:p-8",children:[i.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[i.jsxs("div",{children:[i.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),i.jsx(fqe,{printers:T})]}),i.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("select",{value:d,onChange:L=>ye(L.target.value),className:"text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg px-2 py-1.5 text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"name",children:t("printers.sort.name")}),i.jsx("option",{value:"status",children:t("printers.sort.status")}),i.jsx("option",{value:"model",children:t("printers.sort.model")}),i.jsx("option",{value:"location",children:t("printers.sort.location")})]}),i.jsx("button",{onClick:Ee,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(m?"printers.sort.descending":"printers.sort.ascending"),children:m?i.jsx($p,{className:"w-4 h-4 text-bambu-gray"}):i.jsx(Pb,{className:"w-4 h-4 text-bambu-gray"})})]}),i.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:K.map((L,G)=>{const B=G+1,ie=f===B;return i.jsx("button",{onClick:()=>{x(B),localStorage.setItem("printerCardSize",String(B))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${G===0?"rounded-l-lg":""} ${G===K.length-1?"rounded-r-lg":""} ${ie?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(L==="S"?"printers.cardSize.small":L==="M"?"printers.cardSize.medium":L==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:L},L)})}),i.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),i.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[i.jsx("input",{type:"checkbox",checked:r,onChange:oe,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(he).length>0&&i.jsxs("div",{className:"relative",children:[i.jsxs("button",{onClick:()=>o(!s),className:"flex items-center gap-1.5 px-3 py-1.5 text-sm bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg text-gray-600 dark:text-bambu-gray hover:text-gray-900 dark:hover:text-white hover:border-bambu-green transition-colors",children:[i.jsx(Su,{className:"w-4 h-4"}),t("printers.powerOn"),i.jsx(jn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),i.jsxs("div",{className:"absolute right-0 mt-2 w-56 bg-white dark:bg-bambu-dark-secondary border border-gray-200 dark:border-bambu-dark-tertiary rounded-lg shadow-lg z-20 py-1",children:[i.jsx("div",{className:"px-3 py-2 text-xs text-gray-500 dark:text-bambu-gray border-b border-gray-200 dark:border-bambu-dark-tertiary",children:t("printers.offlinePrintersWithPlugs")}),T?.filter(L=>he[L.id]).map(L=>i.jsx(vqe,{printer:L,plug:he[L.id],onPowerOn:G=>{c(G),ae.mutate(G)},isPowering:l===he[L.id]?.id},L.id)),T?.filter(L=>he[L.id]).length===0&&i.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),i.jsxs(Oe,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),P?i.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):T?.length===0?i.jsx(Tt,{children:i.jsxs(Pt,{className:"text-center py-12",children:[i.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),i.jsxs(Oe,{onClick:()=>n(!0),disabled:!_("printers:create"),title:_("printers:create")?void 0:t("printers.permission.noAdd"),children:[i.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):j?i.jsx("div",{className:"space-y-6",children:Object.entries(j).map(([L,G])=>i.jsxs("div",{children:[i.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[i.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),L,i.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",G.length,")"]})]}),i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${q()}`,children:G.map(B=>i.jsx(RG,{printer:B,hideIfDisconnected:r,maintenanceInfo:me[B.id],viewMode:v,cardSize:f,amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,spoolmanEnabled:$,hasUnlinkedSpools:W,linkedSpools:te,spoolmanUrl:R?.url,onGetAssignment:le,onUnassignSpool:(ie,z,V)=>J.mutate({printerId:ie,amsId:z,trayId:V}),timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(ie,z)=>C(V=>new Map(V).set(ie,{id:ie,name:z})),checkPrinterFirmware:k?.check_printer_firmware!==!1},B.id))})]},L))}):i.jsx("div",{className:`grid gap-4 ${f>=3?"gap-6":""} ${q()}`,children:E.map(L=>i.jsx(RG,{printer:L,hideIfDisconnected:r,maintenanceInfo:me[L.id],viewMode:v,cardSize:f,spoolmanEnabled:$,hasUnlinkedSpools:W,linkedSpools:te,spoolmanUrl:R?.url,onGetAssignment:le,onUnassignSpool:(G,B,ie)=>J.mutate({printerId:G,amsId:B,trayId:ie}),amsThresholds:k?{humidityGood:Number(k.ams_humidity_good)||40,humidityFair:Number(k.ams_humidity_fair)||60,tempGood:Number(k.ams_temp_good)||28,tempFair:Number(k.ams_temp_fair)||35}:void 0,timeFormat:k?.time_format||"system",cameraViewMode:k?.camera_view_mode||"window",onOpenEmbeddedCamera:(G,B)=>C(ie=>new Map(ie).set(G,{id:G,name:B})),checkPrinterFirmware:k?.check_printer_firmware!==!1},L.id))}),e&&i.jsx(gqe,{onClose:()=>n(!1),onAdd:L=>X.mutate(L),existingSerials:T?.map(L=>L.serial_number)||[]}),Array.from(N.values()).map((L,G)=>i.jsx(wAe,{printerId:L.id,printerName:L.name,viewerIndex:G,onClose:()=>C(B=>{const ie=new Map(B);return ie.delete(L.id),ie})},L.id))]})}function Sqe(){const t=navigator.userAgent.toLowerCase(),e=navigator.platform?.toLowerCase()||"";return t.includes("win")||e.includes("win")?"windows":t.includes("mac")||e.includes("mac")?"macos":t.includes("linux")||e.includes("linux")?"linux":"unknown"}function wp(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:Sqe()==="macos"?n=`bambustudioopen://${encodeURIComponent(t)}`:n=`bambustudio://open?file=${t}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}const FG=768;function ire(){const[t,e]=w.useState(()=>typeof window<"u"?window.innerWidth{const n=window.matchMedia(`(max-width: ${FG-1}px)`),r=a=>{e(a.matches)};return e(n.matches),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),t}function O4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:a}){const{t:s}=Mt(),{data:o}=Ze({queryKey:["settings"],queryFn:fe.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[d,u]=w.useState(null),[m,p]=w.useState(null),[f,x]=w.useState(!0),[v,g]=w.useState(null),[y,_]=w.useState(!1),[N,C]=w.useState(null),[T,P]=w.useState(0),[k,D]=w.useState(!1),[A,R]=w.useState(null),[$,U]=w.useState(!1),[W,O]=w.useState(!1),te=w.useRef(null),re=w.useRef(null),J=10,le=160,me=240,he=.35;w.useEffect(()=>{const ge=ce=>{ce.key==="Escape"&&a()};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[a]),w.useEffect(()=>{if(x(!0),c){const ge=(r||"").toLowerCase(),ce=ge==="3mf"||ge==="stl",I=ge==="gcode"||ge==="3mf";p({has_model:ce,has_gcode:I,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u(ce?"3d":I?"gcode":null),x(!1);return}if(!t){p(null),u(null),x(!1);return}fe.getArchiveCapabilities(t).then(ge=>{p(ge),ge.has_model?u("3d"):ge.has_gcode&&u("gcode"),x(!1)}).catch(()=>{p({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),u("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(_(!0),C(null),P(0),c){const ge=(r||"").toLowerCase();if(!e||ge!=="3mf"){g(null),_(!1);return}fe.getLibraryFilePlates(e).then(ce=>g(ce)).catch(()=>g(null)).finally(()=>_(!1));return}if(!t){g(null),_(!1);return}fe.getArchivePlates(t).then(ge=>g(ge)).catch(()=>g(null)).finally(()=>_(!1))},[t,r,c,e]);const X=w.useMemo(()=>v?.plates??[],[v]),ae=(v?.is_multi_plate??!1)&&X.length>1,oe=k&&ae,ye=N==null?null:X.find(ge=>ge.index===N)??null,Ee=ge=>ge.object_count??ge.objects?.length??0,q=X.reduce((ge,ce)=>ge+Ee(ce),0),K=ye?Ee(ye):q,E=ye?s("modelViewer.plateNumber",{number:ye.index}):s("modelViewer.allPlates"),j=X.length>0,L=w.useRef(null),G=w.useRef(null),[B,ie]=w.useState(10),[z,V]=w.useState(3),ee=X.length>B,Z=Math.max(1,Math.ceil(X.length/B)),ne=ee?X.slice(T*B,(T+1)*B):X;w.useEffect(()=>{if(!oe){ie(10),V(3);return}const ge=L.current,ce=G.current;if(!ge||!ce)return;let I=0;const F=()=>{const pe=ce.clientWidth,Ae=Math.floor(pe/210),_e=Math.max(3,Math.min(5,Ae||3));V(be=>be===_e?be:_e);const Ue=window.getComputedStyle(ge),$e=Number.parseFloat(Ue.rowGap||"0"),ke=ge.querySelector("button")?.getBoundingClientRect().height??44,Me=ce.clientHeight,Pe=Math.max(1,Math.floor((Me+$e)/(ke+$e)))*_e,We=Math.max(1,Pe-1);ie(be=>be===We?be:We)},Q=()=>{I&&cancelAnimationFrame(I),I=requestAnimationFrame(F)};Q();const xe=new ResizeObserver(Q);return xe.observe(ce),xe.observe(ge),()=>{I&&cancelAnimationFrame(I),xe.disconnect()}},[oe,X.length]),w.useEffect(()=>{if(!ee){P(0);return}P(ge=>Math.min(ge,Z-1))},[X.length,ee,Z]),w.useEffect(()=>{if(!ee||N==null)return;const ge=X.findIndex(I=>I.index===N);if(ge<0)return;const ce=Math.floor(ge/B);P(I=>I===ce?I:ce)},[X,B,N,ee]),w.useEffect(()=>{if(!oe){R(null),O(!1);return}if(W)return;const ge=te.current,ce=re.current;if(!ge||!ce)return;const I=ge.clientHeight;if(!I)return;const F=Math.max(me,I*he),Q=Math.max(le,I-J-F),xe=Math.min(ce.scrollHeight,Q);R(Math.max(le,xe))},[oe,W,X.length,T,J,le,me,he]),w.useEffect(()=>{if(!$)return;const ge=I=>{const F=te.current;if(!F)return;const Q=F.getBoundingClientRect(),xe=Q.height;if(!xe)return;const pe=Math.max(me,xe*he),de=Math.max(le,xe-J-pe),Ae=Math.min(de,Math.max(le,I.clientY-Q.top));R(Ae)},ce=()=>{U(!1),O(!0)};return document.addEventListener("mousemove",ge),document.addEventListener("mouseup",ce),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",ge),document.removeEventListener("mouseup",ce),document.body.style.cursor="",document.body.style.userSelect=""}},[$,J,le,me,he]);const se=c?(r||"").toLowerCase()==="3mf":!0,ue=async()=>{if(!se)return;const ge=n||"model";try{if(c){const{token:ce}=await fe.createLibrarySlicerToken(e),I=fe.getLibrarySlicerDownloadUrl(e,ce,ge);wp(`${window.location.origin}${I}`,l)}else{const{token:ce}=await fe.createArchiveSlicerToken(t),I=fe.getArchiveSlicerDownloadUrl(t,ce,ge);wp(`${window.location.origin}${I}`,l)}}catch{if(c){const ce=`${window.location.origin}${fe.getLibraryFileDownloadUrl(e)}`;wp(ce,l)}else{const ce=`${window.location.origin}${fe.getArchiveForSlicer(t,ge)}`;wp(ce,l)}}};return i.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${k?"p-0":"p-8"}`,onClick:a,children:i.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${k?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:ge=>ge.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[i.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),j&&i.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[E,": ",s("modelViewer.objectCount",{count:K})]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Oe,{variant:"secondary",size:"sm",onClick:ue,disabled:!se,children:[i.jsx(ei,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),i.jsx(Oe,{variant:"secondary",size:"sm",onClick:()=>D(ge=>!ge),title:k?"Exit fullscreen":"Enter fullscreen",children:k?i.jsx(KF,{className:"w-4 h-4"}):i.jsx(uC,{className:"w-4 h-4"})}),i.jsx(Oe,{variant:"ghost",size:"sm",onClick:a,children:i.jsx(zt,{className:"w-5 h-5"})})]})]}),m&&i.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[i.jsxs("button",{onClick:()=>m.has_model&&u("3d"),disabled:!m.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="3d"?"text-bambu-green border-b-2 border-bambu-green":m.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(ia,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!m.has_model&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),i.jsxs("button",{onClick:()=>m.has_gcode&&u("gcode"),disabled:!m.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${d==="gcode"?"text-bambu-green border-b-2 border-bambu-green":m.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[i.jsx(xhe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!m.has_gcode&&i.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),i.jsx("div",{className:"flex-1 overflow-hidden p-4",children:f?i.jsx("div",{className:"w-full h-full flex items-center justify-center",children:i.jsx(lt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):d==="3d"&&m?i.jsxs("div",{ref:te,className:`w-full h-full flex flex-col ${oe?"gap-0 min-h-0":"gap-3"}`,children:[ae&&i.jsxs("div",{ref:re,style:oe&&A!=null?{height:A}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${oe?"flex flex-col shrink-0":""}`,children:[i.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[i.jsx(Gi,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&i.jsx(lt,{className:"w-3 h-3 animate-spin"})]}),i.jsxs("div",{className:oe?"flex flex-col min-h-0 flex-1":void 0,children:[i.jsx("div",{ref:G,className:oe?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:i.jsxs("div",{ref:L,className:oe?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:oe?{gridTemplateColumns:`repeat(${z}, minmax(0, 1fr))`}:void 0,children:[i.jsxs("button",{type:"button",onClick:()=>C(null),className:`flex items-center rounded-lg border text-left transition-colors ${oe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N==null?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${oe?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${oe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${oe?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),i.jsx("p",{className:`${oe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:X.length})})]}),N==null&&i.jsx(Vr,{className:`${oe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ne.map(ge=>i.jsxs("button",{type:"button",onClick:()=>C(ge.index),className:`flex items-center rounded-lg border text-left transition-colors ${oe?"gap-1.5 p-1.5 w-full":"gap-2 p-2"} ${N===ge.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark-secondary hover:border-bambu-gray"}`,children:[ge.has_thumbnail&&ge.thumbnail_url?i.jsx("img",{src:ge.thumbnail_url,alt:`Plate ${ge.index}`,className:`${oe?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):i.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${oe?"w-8 h-8":"w-10 h-10"}`,children:i.jsx(Gi,{className:`${oe?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:`${oe?"text-xs":"text-sm"} text-white font-medium truncate`,children:ge.name||s("modelViewer.plateNumber",{number:ge.index})}),i.jsx("p",{className:`${oe?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:ge.object_count??ge.objects?.length??0})})]}),N===ge.index&&i.jsx(Vr,{className:`${oe?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},ge.index))]})}),(ye||ee)&&i.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ye&&i.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[i.jsx("span",{children:s("modelViewer.plateNumber",{number:ye.index})}),ye.print_time_seconds!=null&&i.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ye.print_time_seconds/60)})}),ye.filament_used_grams!=null&&i.jsxs("span",{children:[ye.filament_used_grams.toFixed(1)," g"]}),ye.filaments.length>0&&i.jsx("span",{children:s("modelViewer.filamentCount",{count:ye.filaments.length})})]}),ee&&i.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ye?"ml-auto":""}`,children:[i.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:T+1,total:Z})}),i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>P(ge=>Math.max(ge-1,0)),disabled:T===0,className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.prev")}),(()=>{let ce=Math.max(0,T-Math.floor(2.5));const I=Math.min(Z,ce+5);I-ce<5&&(ce=Math.max(0,I-5));const F=Array.from({length:I-ce},(Q,xe)=>ce+xe);return i.jsxs(i.Fragment,{children:[ce>0&&i.jsx("button",{type:"button",onClick:()=>P(0),className:`px-2 py-1 rounded border text-xs ${T===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),ce>1&&i.jsx("span",{className:"px-1",children:"…"}),F.map(Q=>i.jsx("button",{type:"button",onClick:()=>P(Q),className:`px-2 py-1 rounded border text-xs ${T===Q?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Q+1},Q)),IP(Z-1),className:`px-2 py-1 rounded border text-xs ${T===Z-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:Z})]})})(),i.jsx("button",{type:"button",onClick:()=>P(ge=>Math.min(ge+1,Z-1)),disabled:T>=Z-1,className:`px-2 py-1 rounded border text-xs ${T>=Z-1?"border-bambu-dark-tertiary text-bambu-gray/40 cursor-not-allowed":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:s("modelViewer.pagination.next")})]})]})]})]})]}),oe&&i.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:ge=>{ge.preventDefault(),U(!0),O(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${$?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:i.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),i.jsx("div",{className:`flex-1 ${oe?"min-h-0":""}`,children:i.jsx(QX,{url:c?fe.getLibraryFileDownloadUrl(e):m.has_source?fe.getSource3mfDownloadUrl(t):fe.getArchiveDownload(t),fileType:r,buildVolume:m.build_volume,filamentColors:m.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):d==="gcode"&&m?i.jsx(DQ,{gcodeUrl:c?fe.getLibraryFileGcodeUrl(e):fe.getArchiveGcode(t),filamentColors:m.filament_colors,className:"w-full h-full"}):i.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}function _qe({onClose:t,initialFiles:e}){const{t:n}=Mt(),r=Zt(),{showToast:a}=hn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(T=>T.name.endsWith(".3mf")).map(T=>({file:T,status:"pending"}))||[]),[c,d]=w.useState(!1),[u,m]=w.useState(null);w.useEffect(()=>{const T=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[t]);const p=dt({mutationFn:T=>fe.uploadArchivesBulk(T),onSuccess:T=>{m(T),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(P=>P.map(k=>{const D=T.results.find(R=>R.filename===k.file.name),A=T.errors.find(R=>R.filename===k.file.name);return D?{...k,status:"success",archiveId:D.id}:A?{...k,status:"error",error:A.error}:k})),T.failed===0?a(`${T.uploaded} file${T.uploaded!==1?"s":""} uploaded`):T.uploaded===0?a(`Failed to upload ${T.failed} file${T.failed!==1?"s":""}`,"error"):a(`${T.uploaded} uploaded, ${T.failed} failed`,"warning")},onError:()=>{l(T=>T.map(P=>({...P,status:"error",error:"Upload failed"}))),a("Upload failed","error")}}),f=w.useCallback(T=>{T.preventDefault(),d(!0)},[]),x=w.useCallback(T=>{T.preventDefault(),d(!1)},[]),v=w.useCallback(T=>{T.preventDefault(),d(!1);const P=Array.from(T.dataTransfer.files).filter(k=>k.name.endsWith(".3mf"));P.length>0&&l(k=>[...k,...P.map(D=>({file:D,status:"pending"}))])},[]),g=w.useCallback(T=>{const P=Array.from(T.target.files||[]).filter(k=>k.name.endsWith(".3mf"));P.length>0&&l(k=>[...k,...P.map(D=>({file:D,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(T=>{l(P=>P.filter((k,D)=>D!==T))},[]),_=()=>{if(o.length===0)return;const T=o.filter(P=>P.status==="pending");T.length!==0&&(l(P=>P.map(k=>k.status==="pending"?{...k,status:"uploading"}:k)),p.mutate(T.map(P=>P.file)))},N=o.filter(T=>T.status==="pending").length,C=p.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Tt,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:i.jsxs(Pt,{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.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),i.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsx("div",{className:"p-4",children:i.jsxs("div",{className:`border-2 border-dashed rounded-lg p-8 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,onDragOver:f,onDragLeave:x,onDrop:v,children:[i.jsx(Si,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),i.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),i.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),i.jsx(Oe,{variant:"secondary",onClick:()=>s.current?.click(),disabled:C,children:n("uploadModal.browseFiles")}),i.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:g})]})}),i.jsx("div",{className:"px-4 pb-4",children:i.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&i.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:i.jsx("div",{className:"space-y-2",children:o.map((T,P)=>i.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[i.jsx(oC,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),i.jsx("span",{className:"flex-1 text-white text-sm truncate",children:T.file.name}),i.jsxs("span",{className:"text-xs text-bambu-gray",children:[(T.file.size/(1024*1024)).toFixed(1)," MB"]}),T.status==="pending"&&i.jsx("button",{onClick:()=>y(P),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:C,children:i.jsx(zt,{className:"w-4 h-4"})}),T.status==="uploading"&&i.jsx(lt,{className:"w-4 h-4 text-bambu-green animate-spin"}),T.status==="success"&&i.jsx(pr,{className:"w-4 h-4 text-bambu-green"}),T.status==="error"&&i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"text-xs text-red-400",children:T.error}),i.jsx(zi,{className:"w-4 h-4 text-red-400"})]})]},`${T.file.name}-${P}`))})}),u&&i.jsx("div",{className:"px-4 pb-4",children:i.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:i.jsxs("p",{className:"text-sm text-white",children:[i.jsx("span",{className:"text-bambu-green",children:u.uploaded})," ",n("uploadModal.uploaded"),u.failed>0&&i.jsxs(i.Fragment,{children:[", ",i.jsx("span",{className:"text-red-400",children:u.failed})," ",n("uploadModal.failed")]})]})})}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Oe,{variant:"secondary",onClick:t,className:"flex-1",children:n(u?"common.close":"common.cancel")}),!u&&i.jsx(Oe,{onClick:_,disabled:N===0||C,className:"flex-1",children:C?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):i.jsxs(i.Fragment,{children:[i.jsx(Si,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const Nqe=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],kqe=["completed","failed","aborted","printing"];function are({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Mt();w.useEffect(()=>{const j=L=>{L.key==="Escape"&&e()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[e]);const a=Zt(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[d,u]=w.useState(t.project_id??null),[m,p]=w.useState(t.notes||""),[f,x]=w.useState(t.tags||""),[v,g]=w.useState(t.failure_reason||""),[y,_]=w.useState(t.status),[N,C]=w.useState(t.quantity??1),[T,P]=w.useState(t.photos||[]),[k,D]=w.useState(t.external_url||""),[A,R]=w.useState(!1),[$,U]=w.useState(!1),W=w.useRef(null),O=w.useRef(null),te=w.useRef(null),{data:re}=Ze({queryKey:["printers"],queryFn:fe.getPrinters}),{data:J}=Ze({queryKey:["projects"],queryFn:()=>fe.getProjects()}),{data:le}=Ze({queryKey:["tags"],queryFn:fe.getTags,enabled:n.length===0}),me=n.length>0?n:le?.map(j=>j.name)||[],he=f.split(",").map(j=>j.trim()).filter(Boolean),X=f.includes(",")?f.substring(f.lastIndexOf(",")+1).trim().toLowerCase():f.trim().toLowerCase(),ae=me.filter(j=>!he.includes(j)&&(X===""||j.toLowerCase().includes(X))),oe=j=>{let L;if(X&&!me.includes(X)?L=f.includes(",")?f.substring(0,f.lastIndexOf(",")).split(",").map(G=>G.trim()).filter(Boolean):[]:L=he,!L.includes(j)){const G=[...L,j].join(", ");x(G)}te.current!==null&&clearTimeout(te.current),W.current?.focus()},ye=j=>{const L=he.filter(G=>G!==j).join(", ");x(L)},Ee=dt({mutationFn:j=>fe.updateArchive(t.id,j),onSuccess:()=>{a.invalidateQueries({queryKey:["archives"]}),a.invalidateQueries({queryKey:["projects"]}),e()}}),q=async j=>{const L=j.target.files?.[0];if(L){R(!0);try{const G=await fe.uploadArchivePhoto(t.id,L);P(G.photos),a.invalidateQueries({queryKey:["archives"]})}catch(G){console.error("Failed to upload photo:",G)}finally{R(!1),O.current&&(O.current.value="")}}},K=async j=>{try{const L=await fe.deleteArchivePhoto(t.id,j);P(L.photos||[]),a.invalidateQueries({queryKey:["archives"]})}catch(L){console.error("Failed to delete photo:",L)}},E=j=>{j.preventDefault();const L={print_name:s||void 0,printer_id:l,project_id:d,notes:m||void 0,tags:f||void 0,quantity:N,external_url:k||null};y!==t.status&&(L.status=y),y==="failed"||y==="aborted"?L.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(L.failure_reason=null),Ee.mutate(L)};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:j=>j.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("form",{onSubmit:E,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),i.jsx("input",{type:"text",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:r("editArchive.namePlaceholder")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),i.jsxs("select",{value:l??"",onChange:j=>c(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.noPrinter")}),re?.map(j=>i.jsx("option",{value:j.id,children:j.name},j.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(bs,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),i.jsxs("select",{value:d??"",onChange:j=>u(j.target.value?Number(j.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.noProject")}),J?.map(j=>i.jsx("option",{value:j.id,children:j.name},j.id))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(kpe,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),i.jsx("input",{type:"number",min:1,value:N,onChange:j=>C(Math.max(1,parseInt(j.target.value)||1)),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:"1"}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),i.jsx("textarea",{value:m,onChange:j=>p(j.target.value),rows:3,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none resize-none",placeholder:r("editArchive.notesPlaceholder")})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(dx,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),i.jsx("input",{type:"url",value:k,onChange:j=>D(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",placeholder:"https://printables.com/model/..."}),i.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),he.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:he.map(j=>i.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[i.jsx(du,{className:"w-3 h-3"}),j,i.jsx("button",{type:"button",onClick:()=>ye(j),className:"ml-0.5 text-bambu-gray hover:text-white",children:i.jsx(zt,{className:"w-3 h-3"})})]},j))}),i.jsxs("div",{className:"relative",children:[i.jsx("input",{ref:W,type:"text",value:f,onChange:j=>x(j.target.value),onFocus:()=>{te.current!==null&&clearTimeout(te.current),U(!0)},onBlur:()=>{te.current=window.setTimeout(()=>U(!1),200)},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:he.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),$&&ae.length>0&&i.jsxs("div",{className:"absolute top-full left-0 right-0 mt-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-lg z-10 max-h-40 overflow-y-auto",children:[i.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[X?r("editArchive.matchingTags",{query:X}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),i.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:ae.map(j=>i.jsx("button",{type:"button",onClick:()=>oe(j),className:"px-2 py-0.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded text-sm text-bambu-gray hover:text-white transition-colors",children:j},j))})]})]})]}),i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),i.jsx("select",{value:y,onChange:j=>{_(j.target.value),j.target.value==="completed"&&g("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:kqe.map(j=>i.jsx("option",{value:j,children:r(`editArchive.statuses.${j}`)},j))})]}),(y==="failed"||y==="aborted")&&i.jsxs("div",{children:[i.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),i.jsxs("select",{value:v,onChange:j=>g(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[i.jsx("option",{value:"",children:r("editArchive.selectReason")}),Nqe.map(j=>i.jsx("option",{value:r(`editArchive.failureReasons.${j}`),children:r(`editArchive.failureReasons.${j}`)},j))]})]}),i.jsxs("div",{children:[i.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i.jsx(Mb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),i.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[T.map(j=>i.jsxs("div",{className:"relative group",children:[i.jsx("img",{src:fe.getArchivePhotoUrl(t.id,j),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),i.jsx("button",{type:"button",onClick:()=>K(j),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:i.jsx(Qt,{className:"w-3 h-3 text-white"})})]},j)),i.jsxs("label",{className:"w-20 h-20 flex items-center justify-center border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green transition-colors",children:[i.jsx("input",{ref:O,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:q,className:"hidden",disabled:A}),A?i.jsx(lt,{className:"w-6 h-6 text-bambu-gray animate-spin"}):i.jsx(rr,{className:"w-6 h-6 text-bambu-gray"})]})]}),i.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),i.jsxs("div",{className:"flex gap-3 pt-2",children:[i.jsx(Oe,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),i.jsxs(Oe,{type:"submit",disabled:Ee.isPending,className:"flex-1",children:[i.jsx(gs,{className:"w-4 h-4"}),Ee.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function sre({x:t,y:e,items:n,onClose:r}){const a=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,d]=w.useState({x:t,y:e,visible:!1}),[u,m]=w.useState(!1),[p,f]=w.useState({});w.useEffect(()=>{const g=N=>{a.current&&!a.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},_=()=>{r()};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),document.addEventListener("scroll",_,!0),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y),document.removeEventListener("scroll",_,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(a.current){a.current.style.visibility="hidden",a.current.style.display="block";const g=a.current.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,N=8;let C=t,T=e;t+g.width>y-N&&(C=Math.max(N,y-g.width-N)),C_-N&&(T=Math.max(N,_-g.height-N)),TP),d({x:C,y:T,visible:!0})}},[t,e]);const x=(g,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const _=y.getBoundingClientRect(),N=window.innerHeight,C=300,k=N-_.top-8C;f(D=>({...D,[g]:k?"bottom":"top"})),o(g)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return i.jsx("div",{ref:a,className:"fixed z-50 min-w-[180px] max-w-[280px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1",style:{left:c.x,top:c.y,visibility:c.visible?"visible":"hidden"},children:n.map((g,y)=>{if(g.divider)return i.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const _=g.submenu&&g.submenu.length>0;return i.jsxs("div",{className:"relative",onMouseEnter:N=>_&&x(y,N.currentTarget),onMouseLeave:()=>_&&v(),children:[i.jsxs("button",{onMouseEnter:N=>_&&x(y,N.currentTarget.parentElement),onClick:()=>{_?o(s===y?null:y):g.disabled||(g.onClick(),r())},disabled:g.disabled,title:g.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${g.disabled?"text-bambu-gray cursor-not-allowed":g.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${_&&s===y?"bg-bambu-dark-tertiary":""}`,children:[g.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:g.icon}),i.jsx("span",{className:"flex-1",children:g.label}),_&&i.jsx(fa,{className:"w-4 h-4 text-bambu-gray"})]}),_&&s===y&&i.jsx("div",{className:`absolute min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl py-1 overflow-hidden max-h-[300px] overflow-y-auto z-[60] ${u?"right-full mr-1":"left-full ml-1"} ${p[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:g.submenu.map((N,C)=>i.jsxs("button",{onClick:()=>{N.disabled||(N.onClick(),r())},disabled:N.disabled,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${N.disabled?"text-bambu-gray cursor-not-allowed":N.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"}`,children:[N.icon&&i.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},C))})]},y)})})}function Cqe({selectedIds:t,existingTags:e,onClose:n}){const r=Zt(),{showToast:a}=hn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[d,u]=w.useState("add");w.useEffect(()=>{const v=g=>{g.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const m=dt({mutationFn:async()=>{const v=Array.from(l);let g=0;for(const y of t)try{const _=await fe.getArchive(y),N=_.tags?_.tags.split(",").map(T=>T.trim()).filter(Boolean):[];let C;d==="add"?C=[...new Set([...N,...v])]:C=N.filter(T=>!l.has(T)),await fe.updateArchive(y,{tags:C.join(", ")}),g++}catch(_){throw console.error(`Failed to update archive ${y}:`,_),new Error(`Failed on archive ${y}: ${_ instanceof Error?_.message:"Unknown error"}`)}return{count:g,mode:d,tags:v}},onSuccess:({count:v,mode:g,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),a(`${g==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${g==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{a(v.message||"Failed to update tags","error")}}),p=v=>{c(g=>{const y=new Set(g);return y.has(v)?y.delete(v):y.add(v),y})},f=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),f())};return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Tt,{className:"w-full max-w-md",children:i.jsxs(Pt,{className:"p-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(du,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:d==="add"?"Add Tags":"Remove Tags"})]}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-4",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:[d==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(Oe,{size:"sm",variant:d==="add"?"primary":"secondary",onClick:()=>u("add"),children:"Add Tags"}),i.jsx(Oe,{size:"sm",variant:d==="remove"?"primary":"secondary",onClick:()=>u("remove"),children:"Remove Tags"})]}),d==="add"&&i.jsxs("div",{className:"flex gap-2",children:[i.jsx("input",{type:"text",placeholder:"Enter new tag...",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",value:s,onChange:v=>o(v.target.value),onKeyDown:x}),i.jsx(Oe,{size:"sm",variant:"secondary",onClick:f,disabled:!s.trim(),children:i.jsx(rr,{className:"w-4 h-4"})})]}),e.length>0&&i.jsxs("div",{children:[i.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),i.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>i.jsx("button",{onClick:()=>p(v),className:`px-2 py-1 rounded text-sm transition-colors ${l.has(v)?"bg-bambu-green text-white":"bg-bambu-dark-tertiary text-bambu-gray-light hover:bg-bambu-dark"}`,children:v},v))})]}),l.size>0&&i.jsxs("div",{children:[i.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",d==="add"?"add":"remove",":"]}),i.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>i.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${d==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,i.jsx("button",{onClick:()=>p(v),className:"hover:opacity-70",children:i.jsx(zt,{className:"w-3 h-3"})})]},v))})]})]}),i.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[i.jsx(Oe,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),i.jsx(Oe,{onClick:()=>m.mutate(),disabled:l.size===0||m.isPending,className:"flex-1",children:m.isPending?i.jsxs(i.Fragment,{children:[i.jsx(lt,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):i.jsxs(i.Fragment,{children:[i.jsx(du,{className:"w-4 h-4"}),d==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function Tqe({selectedIds:t,onClose:e}){const n=Zt(),{showToast:r}=hn(),{data:a,isLoading:s}=Ze({queryKey:["projects"],queryFn:()=>fe.getProjects()});w.useEffect(()=>{const u=m=>{m.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=dt({mutationFn:async u=>(await fe.addArchivesToProject(u,t),u),onSuccess:u=>{const m=a?.find(p=>p.id===u);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${m?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=dt({mutationFn:async()=>{for(const u of t)await fe.updateArchive(u,{project_id:null});return t.length},onSuccess:u=>{o(),r(`Removed ${u} archive${u!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),d=l.isPending||c.isPending;return i.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:i.jsx(Tt,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:i.jsxs(Pt,{className:"p-0 flex flex-col min-h-0",children:[i.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(bs,{className:"w-5 h-5 text-bambu-green"}),i.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),i.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:d,children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?i.jsx("div",{className:"flex items-center justify-center py-8",children:i.jsx(lt,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):i.jsxs("div",{className:"space-y-2",children:[i.jsxs("button",{onClick:()=>c.mutate(),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[i.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:i.jsx(Vi,{className:"w-4 h-4 text-red-400"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),i.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&i.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),a&&a.length>0&&i.jsxs("div",{className:"flex items-center gap-2 py-2",children:[i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),i.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),i.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),a?.map(u=>i.jsxs("button",{onClick:()=>l.mutate(u.id),disabled:d,className:"w-full flex items-center gap-3 p-3 rounded-lg bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary transition-colors text-left disabled:opacity-50",children:[i.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:u.color?`${u.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:i.jsx(bs,{className:"w-4 h-4",style:{color:u.color||"rgb(var(--bambu-green))"}})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-white font-medium truncate",children:u.name}),i.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[u.archive_count," archive",u.archive_count!==1?"s":"",u.status&&` • ${u.status}`]})]}),l.isPending&&l.variables===u.id&&i.jsx(lt,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},u.id)),(!a||a.length===0)&&i.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),i.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:i.jsx(Oe,{variant:"secondary",onClick:e,className:"flex-1",disabled:d,children:"Cancel"})})]})})})}function Pqe(t,e){return new Date(t,e+1,0).getDate()}function Aqe(t,e){return new Date(t,e,1).getDay()}const Mqe=["January","February","March","April","May","June","July","August","September","October","November","December"],Eqe=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function jqe({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[a,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,d]=w.useState(null),[u,m]=w.useState(null),p=w.useMemo(()=>{const T=new Map;return t.forEach(P=>{const k=er(P.completed_at||P.created_at)||new Date,D=`${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}-${String(k.getDate()).padStart(2,"0")}`,A=T.get(D)||[];A.push(P),T.set(D,A)}),T},[t]),f=Pqe(o,a),x=Aqe(o,a),v=()=>{a===0?(s(11),l(o-1)):s(a-1)},g=()=>{a===11?(s(0),l(o+1)):s(a+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},_=[];for(let T=0;T{T!==c&&m(null),d(T)};return i.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[i.jsxs("div",{className:"flex-1",children:[i.jsxs("div",{className:"flex items-center justify-between mb-4",children:[i.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(nc,{className:"w-5 h-5 text-bambu-gray"})}),i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsxs("h2",{className:"text-lg font-semibold text-white",children:[Mqe[a]," ",o]}),i.jsx("button",{onClick:y,className:"px-2 py-1 text-xs bg-bambu-dark-tertiary hover:bg-bambu-green/20 text-bambu-gray hover:text-white rounded transition-colors",children:"Today"})]}),i.jsx("button",{onClick:g,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:i.jsx(fa,{className:"w-5 h-5 text-bambu-gray"})})]}),i.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:Eqe.map(T=>i.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:T},T))}),i.jsx("div",{className:"grid grid-cols-7 gap-1",children:_.map((T,P)=>{if(T===null)return i.jsx("div",{className:"aspect-square"},`empty-${P}`);const k=`${o}-${String(a+1).padStart(2,"0")}-${String(T).padStart(2,"0")}`,D=p.get(k)||[],A=D.length>0,R=T===r.getDate()&&a===r.getMonth()&&o===r.getFullYear(),$=k===c,U=D.filter(O=>O.status==="completed").length,W=D.filter(O=>O.status==="failed").length;return i.jsxs("button",{onClick:()=>C($?null:k),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${$?"bg-bambu-green text-white":R?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":A?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[i.jsx("span",{className:`text-sm font-medium ${R&&!$?"text-bambu-green":""}`,children:T}),A&&i.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[i.jsx("div",{className:`w-2 h-2 rounded-full ${W>0&&U===0?"bg-red-400":W>0?"bg-yellow-400":"bg-green-400"}`}),i.jsx("span",{className:"text-xs font-medium",children:D.length})]})]},T)})}),i.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:i.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(T=>{const P=er(T.completed_at||T.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(T=>{const P=er(T.completed_at||T.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&T.status==="completed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),i.jsxs("div",{children:[i.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(T=>{const P=er(T.completed_at||T.created_at)||new Date;return P.getMonth()===a&&P.getFullYear()===o&&T.status==="failed"}).length}),i.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),i.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?i.jsxs(i.Fragment,{children:[i.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-3",children:new Date(c+"T12:00:00").toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric",year:"numeric"})}),N.length>0?i.jsx("div",{className:"calendar-scroll space-y-2 max-h-96 overflow-y-auto",children:N.map(T=>{const P=T.id===u||T.id===n;return i.jsxs("button",{onClick:()=>{m(T.id),e?.(T)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${P?"":"hover:bg-bambu-dark-tertiary"}`,style:P?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[T.thumbnail_path?i.jsx("img",{src:fe.getArchiveThumbnail(T.id),alt:"",className:"w-12 h-12 rounded object-cover"}):i.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:i.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),i.jsxs("div",{className:"flex-1 min-w-0",children:[i.jsx("p",{className:"text-sm text-white truncate",children:T.print_name||T.filename}),i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx("span",{className:T.status==="failed"?"text-red-400":"text-green-400",children:T.status==="failed"?"Failed":"Completed"}),T.filament_color&&i.jsx("div",{className:"flex gap-0.5",children:T.filament_color.split(",").map((k,D)=>i.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:k}},D))})]})]})]},T.id)})}):i.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):i.jsx("div",{className:"text-center py-8",children:i.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function ore({archiveId:t,archiveName:e,onClose:n}){const r=fe.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const a=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return i.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:i.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),i.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-5 h-5"})})]}),i.jsxs("div",{className:"p-6 flex flex-col items-center",children:[i.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),i.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:i.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),i.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),i.jsxs(Oe,{onClick:a,className:"w-full",children:[i.jsx(hi,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function lre({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:a}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const f=x=>{x.key==="Escape"&&r(),x.key==="ArrowLeft"&&o(v=>Math.max(0,v-1)),x.key==="ArrowRight"&&o(v=>Math.min(n.length-1,v+1))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r,n.length]),w.useEffect(()=>{s>=n.length&&o(Math.max(0,n.length-1))},[n.length,s]),n.length===0)return r(),null;const d=n[s],u=fe.getArchivePhotoUrl(t,d),m=()=>{const f=document.createElement("a");f.href=u,f.download=`${e}_photo_${s+1}.jpg`,f.click()},p=()=>{a&&c(!0)};return i.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[i.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:f=>f.stopPropagation(),children:[i.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[i.jsxs("div",{children:[i.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),i.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs(Oe,{variant:"secondary",size:"sm",onClick:m,children:[i.jsx(hi,{className:"w-4 h-4"}),"Download"]}),a&&i.jsx(Oe,{variant:"secondary",size:"sm",onClick:p,className:"text-red-400 hover:text-red-300",children:i.jsx(Qt,{className:"w-4 h-4"})}),i.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:i.jsx(zt,{className:"w-6 h-6"})})]})]}),i.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&i.jsx("button",{onClick:()=>o(f=>f-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(nc,{className:"w-8 h-8 text-white"})}),i.jsx("img",{src:u,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(f=>f+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:i.jsx(fa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&i.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((f,x)=>i.jsx("button",{onClick:()=>o(x),className:`w-16 h-16 rounded-lg overflow-hidden border-2 transition-colors ${x===s?"border-bambu-green":"border-transparent hover:border-bambu-gray"}`,children:i.jsx("img",{src:fe.getArchivePhotoUrl(t,f),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},f))})]}),l&&i.jsx(_n,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{a?.(d),c(!1)},onCancel:()=>c(!1)})]})}function Xa(t){this.content=t}Xa.prototype={constructor:Xa,find:function(t){for(var e=0;e>1}};Xa.from=function(t){if(t instanceof Xa)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Xa(e)};function cre(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let a=t.child(r),s=e.child(r);if(a==s){n+=a.nodeSize;continue}if(!a.sameMarkup(s))return n;if(a.isText&&a.text!=s.text){for(let o=0;a.text[o]==s.text[o];o++)n++;return n}if(a.content.size||s.content.size){let o=cre(a.content,s.content,n+1);if(o!=null)return o}n+=a.nodeSize}}function dre(t,e,n,r){for(let a=t.childCount,s=e.childCount;;){if(a==0||s==0)return a==s?null:{a:n,b:r};let o=t.child(--a),l=e.child(--s),c=o.nodeSize;if(o==l){n-=c,r-=c;continue}if(!o.sameMarkup(l))return{a:n,b:r};if(o.isText&&o.text!=l.text){let d=0,u=Math.min(o.text.length,l.text.length);for(;de&&r(c,a+l,s||null,o)!==!1&&c.content.size){let u=l+1;c.nodesBetween(Math.max(0,e-u),Math.min(c.content.size,n-u),r,a+u)}l=d}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,a){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let d=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?a?typeof a=="function"?a(l):a:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&d||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=d},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,a=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),s=1);se)for(let s=0,o=0;oe&&((on)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,n-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,n-o-1))),r.push(l),a+=l.nodeSize),o=c}return new Ot(r,a)}cutByIndex(e,n){return e==n?Ot.empty:e==0&&n==this.content.length?this:new Ot(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let a=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return a[e]=n,new Ot(a,s)}addToStart(e){return new Ot([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Ot(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let n=0;nthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let n=0,r=0;;n++){let a=this.child(n),s=r+a.nodeSize;if(s>=e)return s==e?B_(n+1,s):B_(n,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,n){if(!n)return Ot.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Ot(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Ot.empty;let n,r=0;for(let a=0;athis.type.rank&&(n||(n=e.slice(0,a)),n.push(this),r=!0),n&&n.push(s)}}return n||(n=e.slice()),r||n.push(this),n}removeFromSet(e){for(let n=0;nr.type.rank-a.type.rank),n}};Yr.none=[];class lk extends Error{}class Gt{constructor(e,n,r){this.content=e,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,n){let r=mre(this.content,e+this.openStart,n);return r&&new Gt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Gt(ure(this.content,e+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,n){if(!n)return Gt.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Gt(Ot.fromJSON(e,n.content),r,a)}static maxOpen(e,n=!0){let r=0,a=0;for(let s=e.firstChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(n||!s.type.spec.isolating);s=s.lastChild)a++;return new Gt(e,r,a)}}Gt.empty=new Gt(Ot.empty,0,0);function ure(t,e,n){let{index:r,offset:a}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(a==e||s.isText){if(l!=n&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(n))}if(r!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(r,s.copy(ure(s.content,e-a-1,n-a-1)))}function mre(t,e,n,r){let{index:a,offset:s}=t.findIndex(e),o=t.maybeChild(a);if(s==e||o.isText)return r&&!r.canReplace(a,a,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=mre(o.content,e-s-1,n,o);return l&&t.replaceChild(a,o.copy(l))}function Dqe(t,e,n){if(n.openStart>t.depth)throw new lk("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new lk("Inconsistent open depths");return hre(t,e,n,0)}function hre(t,e,n,r){let a=t.index(r),s=t.node(r);if(a==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function fv(t,e,n,r){let a=(e||t).node(n),s=0,o=e?e.index(n):a.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(Fp(t.nodeAfter,r),s++));for(let l=s;la&&BR(t,e,a+1),o=r.depth>a&&BR(n,r,a+1),l=[];return fv(null,t,a,l),s&&o&&e.index(a)==n.index(a)?(pre(s,o),Fp(Lp(s,fre(t,e,n,r,a+1)),l)):(s&&Fp(Lp(s,ck(t,e,a+1)),l),fv(e,n,a,l),o&&Fp(Lp(o,ck(n,r,a+1)),l)),fv(r,null,a,l),new Ot(l)}function ck(t,e,n){let r=[];if(fv(null,t,n,r),t.depth>n){let a=BR(t,e,n+1);Fp(Lp(a,ck(t,e,n+1)),r)}return fv(e,null,n,r),new Ot(r)}function Rqe(t,e){let n=e.depth-t.openStart,a=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)a=e.node(s).copy(Ot.from(a));return{start:a.resolveNoCache(t.openStart+n),end:a.resolveNoCache(a.content.size-t.openEnd-n)}}class m0{constructor(e,n,r){this.pos=e,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,n=this.index(this.depth);if(n==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],a=e.child(n);return r?e.child(n).cut(r):a}get nodeBefore(){let e=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(e).cut(0,n):e==0?null:this.parent.child(e-1)}posAtIndex(e,n){n=this.resolveDepth(n);let r=this.path[n*3],a=n==0?0:this.path[n*3-1]+1;for(let s=0;s0;n--)if(this.start(n)<=e&&this.end(n)>=e)return n;return 0}blockRange(e=this,n){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!n||n(this.node(r))))return new dk(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&n<=e.content.size))throw new RangeError("Position "+n+" out of range");let r=[],a=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),d=s-c;if(r.push(o,l,a+c),!d||(o=o.child(l),o.isText))break;s=d-1,a+=c+1}return new m0(n,r,s)}static resolveCached(e,n){let r=LG.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(a=!0),!a)),a}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),gre(this.marks,e)}contentMatchAt(e){let n=this.type.contentMatch.matchFragment(this.content,0,e);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(e,n,r=Ot.empty,a=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,a,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=a;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let e={type:this.type.name};for(let n in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(n=>n.toJSON())),e}static fromJSON(e,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(e.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(n.text,r)}let a=Ot.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,a,r);return s.type.checkAttrs(s.attrs),s}};Jm.prototype.text=void 0;class uk extends Jm{constructor(e,n,r,a){if(super(e,n,null,a),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):gre(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,n){return this.text.slice(e,n)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new uk(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new uk(this.type,this.attrs,e,this.marks)}cut(e=0,n=this.text.length){return e==0&&n==this.text.length?this:this.withText(this.text.slice(e,n))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function gre(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class df{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new Iqe(e,n);if(r.next==null)return df.empty;let a=bre(r);r.next&&r.err("Unexpected trailing text");let s=Vqe(qqe(a));return Gqe(s,r),s}matchType(e){for(let n=0;nd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function n(r){e.push(r);for(let a=0;a{let s=a+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` `)}}df.empty=new df(!0);class Iqe{constructor(e,n){this.string=e,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function bre(t){let e=[];do e.push(zqe(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function zqe(t){let e=[];do e.push(Uqe(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Uqe(t){let e=$qe(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else if(t.eat("{"))e=Bqe(t,e);else break;return e}function OG(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function Bqe(t,e){let n=OG(t),r=n;return t.eat(",")&&(t.next!="}"?r=OG(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function Hqe(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let a=[];for(let s in n){let o=n[s];o.isInGroup(e)&&a.push(o)}return a.length==0&&t.err("No node type or group '"+e+"' found"),a}function $qe(t){if(t.eat("(")){let e=bre(t);return t.eat(")")||t.err("Missing closing paren"),e}else if(/\W/.test(t.next))t.err("Unexpected token '"+t.next+"'");else{let e=Hqe(t,t.next).map(n=>(t.inline==null?t.inline=n.isInline:t.inline!=n.isInline&&t.err("Mixing inline and block content"),{type:"name",value:n}));return t.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function qqe(t){let e=[[]];return a(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let d={term:c,to:l};return e[o].push(d),d}function a(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,d)=>c.concat(s(d,l)),[]);if(o.type=="seq")for(let c=0;;c++){let d=s(o.exprs[c],l);if(c==o.exprs.length-1)return d;a(d,l=n())}else if(o.type=="star"){let c=n();return r(l,c),a(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return a(s(o.expr,l),c),a(s(o.expr,c),c),[r(c)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let c=l;for(let d=0;d{t[o].forEach(({term:l,to:c})=>{if(!l)return;let d;for(let u=0;u{d||a.push([l,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let s=e[r.join(",")]=new df(r.indexOf(t.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:vre(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Jm(this,this.computeAttrs(e),Ot.from(n),Yr.setFrom(r))}createChecked(e=null,n,r){return n=Ot.from(n),this.checkContent(n),new Jm(this,this.computeAttrs(e),n,Yr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Ot.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let a=this.contentMatch.matchFragment(n),s=a&&a.fillBefore(Ot.empty,!0);return s?new Jm(this,e,n.append(s),Yr.setFrom(r)):null}validContent(e){let n=this.contentMatch.matchFragment(e);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let n=0;nr[s]=new _re(s,n,o));let a=n.spec.topNode||"doc";if(!r[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Wqe(t,e,n){let r=n.split("|");return a=>{let s=a===null?"null":typeof a;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class Kqe{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Wqe(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class CT{constructor(e,n,r,a){this.name=e,this.rank=n,this.schema=r,this.spec=a,this.attrs=Sre(e,a.attrs),this.excluded=null;let s=yre(this.attrs);this.instance=s?new Yr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Yr(this,vre(this.attrs,e))}static compile(e,n){let r=Object.create(null),a=0;return e.forEach((s,o)=>r[s]=new CT(s,a++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class Nre{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let a in e)n[a]=e[a];n.nodes=Xa.from(e.nodes),n.marks=Xa.from(e.marks||{}),this.nodes=zG.compile(this.spec.nodes,this),this.marks=CT.compile(this.spec.marks,this);let r=Object.create(null);for(let a in this.nodes){if(a in this.marks)throw new RangeError(a+" can not be both a node and a mark");let s=this.nodes[a],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=df.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?UG(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let a in this.marks){let s=this.marks[a],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:UG(this,o.split(" "))}this.nodeFromJSON=a=>Jm.fromJSON(this,a),this.markFromJSON=a=>Yr.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,a){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof zG){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(n,r,a)}text(e,n){let r=this.nodes.text;return new uk(r,r.defaultAttrs,e,Yr.setFrom(n))}mark(e,n){return typeof e=="string"&&(e=this.marks[e]),e.create(n)}nodeType(e){let n=this.nodes[e];if(!n)throw new RangeError("Unknown node type: "+e);return n}}function UG(t,e){let n=[];for(let r=0;r-1)&&n.push(o=c)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return n}function Yqe(t){return t.tag!=null}function Xqe(t){return t.style!=null}let gv=class $R{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(Yqe(a))this.tags.push(a);else if(Xqe(a)){let s=/[^=]*/.exec(a.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(a)}}),this.normalizeLists=!this.tags.some(a=>{if(!/^(ul|ol)\b/.test(a.tag)||!a.node)return!1;let s=e.nodes[a.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new HG(this,n,!1);return r.addAll(e,Yr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new HG(this,n,!0);return r.addAll(e,Yr.none,n.from,n.to),Gt.maxOpen(r.finish())}matchTag(e,n,r){for(let a=r?this.tags.indexOf(r)+1:0;ae.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=n))){if(o.getAttrs){let c=o.getAttrs(n);if(c===!1)continue;o.attrs=c||void 0}return o}}}static schemaRules(e){let n=[];function r(a){let s=a.priority==null?50:a.priority,o=0;for(;o{r(o=$G(o)),o.mark||o.ignore||o.clearMark||(o.mark=a)})}for(let a in e.nodes){let s=e.nodes[a].spec.parseDOM;s&&s.forEach(o=>{r(o=$G(o)),o.node||o.ignore||o.mark||(o.node=a)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new $R(e,$R.schemaRules(e)))}};const kre={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Qqe={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Cre={ol:!0,ul:!0},h0=1,qR=2,bv=4;function BG(t,e,n){return e!=null?(e?h0:0)|(e==="full"?qR:0):t&&t.whitespace=="pre"?h0|qR:n&~bv}class H_{constructor(e,n,r,a,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=a,this.options=o,this.content=[],this.activeMarks=Yr.none,this.match=s||(o&bv?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Ot.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(e.type))?(this.match=r,a):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&h0)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-a[0].length))}}let n=Ot.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Ot.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!kre.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class HG{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let a=n.topNode,s,o=BG(null,n.preserveWhitespace,0)|(r?bv:0);a?s=new H_(a.type,a.attrs,Yr.none,!0,n.topMatch||a.type.contentMatch,o):r?s=new H_(null,null,Yr.none,!0,null,o):s=new H_(e.schema.topNodeType,null,Yr.none,!0,null,o),this.nodes=[s],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,n){e.nodeType==3?this.addTextNode(e,n):e.nodeType==1&&this.addElement(e,n)}addTextNode(e,n){let r=e.nodeValue,a=this.top,s=a.options&qR?"full":this.localPreserveWS||(a.options&h0)>0,{schema:o}=this.parser;if(s==="full"||a.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` `);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)l=c;else break}}return n}addElementByRule(e,n,r,a){let s,o;if(n.node)if(o=this.parser.schema.nodes[n.node],o.isLeaf)this.insertNode(o.create(n.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let c=this.enter(o,n.attrs||null,r,n.preserveWhitespace);c&&(s=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(a)this.addElement(e,r,a);else if(n.getContent)this.findInside(e),n.getContent(e,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=e;typeof n.contentElement=="string"?c=e.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(e):n.contentElement&&(c=n.contentElement),this.findAround(e,c,!0),this.addAll(c,r),this.findAround(e,c,!1)}s&&this.sync(l)&&this.open--}addAll(e,n,r,a){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=a==null?null:e.childNodes[a];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let a,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],d=c.findWrapping(e);if(d&&(!a||a.length>d.length+l)&&(a=d,s=c,!d.length))break;if(c.solid){if(r)break;l+=2}}if(!a)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(d.type):qG(d.type,e))?(c=d.addToSet(c),!1):!0),this.nodes.push(new H_(e,n,c,a,null,l)),this.open++,r}closeExtra(e=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let n=this.open;n>=0;n--){if(this.nodes[n]==e)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=h0)}return!1}get currentPos(){this.closeExtra();let e=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)e+=r[a].nodeSize;n&&e++}return e}findAtPoint(e,n){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let n=e.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(a?0:1),o=(l,c)=>{for(;l>=0;l--){let d=n[l];if(d==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let u=c>0||c==0&&a?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return o(n.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let n=e.depth;n>=0;n--){let r=e.node(n).contentMatchAt(e.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function Zqe(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Cre.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function Jqe(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function $G(t){let e={};for(let n in t)e[n]=t[n];return e}function qG(t,e){let n=e.schema.nodes;for(let r in n){let a=n[r];if(!a.allowsMarkType(t))continue;let s=[],o=l=>{s.push(l);for(let c=0;c{if(s.length||o.marks.length){let l=0,c=0;for(;l=0;a--){let s=this.serializeMark(e.marks[a],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let a=this.marks[e.type.name];return a&&k1(fj(r),a(e,n),null,e.attrs)}static renderSpec(e,n,r=null,a){return k1(e,n,r,a)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new _f(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=VG(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return VG(e.marks)}}function VG(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function fj(t){return t.document||window.document}const GG=new WeakMap;function eVe(t){let e=GG.get(t);return e===void 0&&GG.set(t,e=tVe(t)),e}function tVe(t){let e=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=a.indexOf(" ");o>0&&(n=a.slice(0,o),a=a.slice(o+1));let l,c=n?t.createElementNS(n,a):t.createElement(a),d=e[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let m in d)if(d[m]!=null){let p=m.indexOf(" ");p>0?c.setAttributeNS(m.slice(0,p),m.slice(p+1),d[m]):m=="style"&&c.style?c.style.cssText=d[m]:c.setAttribute(m,d[m])}}for(let m=u;mu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:x}=k1(t,p,n,r);if(c.appendChild(f),x){if(l)throw new RangeError("Multiple content holes");l=x}}}return{dom:c,contentDOM:l}}const Tre=65535,Pre=Math.pow(2,16);function nVe(t,e){return t+e*Pre}function WG(t){return t&Tre}function rVe(t){return(t-(t&Tre))/Pre}const Are=1,Mre=2,C1=4,Ere=8;class VR{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Ere)>0}get deletedBefore(){return(this.delInfo&(Are|C1))>0}get deletedAfter(){return(this.delInfo&(Mre|C1))>0}get deletedAcross(){return(this.delInfo&C1)>0}}class jo{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&jo.empty)return jo.empty}recover(e){let n=0,r=WG(e);if(!this.inverted)for(let a=0;ae)break;let d=this.ranges[l+s],u=this.ranges[l+o],m=c+d;if(e<=m){let p=d?e==c?-1:e==m?1:n:n,f=c+a+(p<0?0:u);if(r)return f;let x=e==(n<0?c:m)?null:nVe(l/3,e-c),v=e==c?Mre:e==m?Are:C1;return(n<0?e!=c:e!=m)&&(v|=Ere),new VR(f,v,x)}a+=u-d}return r?e+a:new VR(e+a,0,null)}touches(e,n){let r=0,a=WG(n),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let d=this.ranges[l+s],u=c+d;if(e<=u&&l==a*3)return!0;r+=this.ranges[l+o]-d}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,s=0;a=0;n--){let a=e.getMirror(n);this.appendMap(e._maps[n].invert(),a!=null&&a>n?r-a-1:void 0)}}invert(){let e=new p0;return e.appendMappingInverted(this),e}map(e,n=1){if(this.mirror)return this._map(e,n,!0);for(let r=this.from;rs&&c!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),a),n.openStart,n.openEnd);return sa.fromReplace(e,this.from,this.to,s)}invert(){return new ec(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Om(n.pos,r.pos,this.mark)}merge(e){return e instanceof Om&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Om(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Om(n.from,n.to,e.markFromJSON(n.mark))}}_s.jsonID("addMark",Om);class ec extends _s{constructor(e,n,r){super(),this.from=e,this.to=n,this.mark=r}apply(e){let n=e.slice(this.from,this.to),r=new Gt(I4(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),e),n.openStart,n.openEnd);return sa.fromReplace(e,this.from,this.to,r)}invert(){return new Om(this.from,this.to,this.mark)}map(e){let n=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new ec(n.pos,r.pos,this.mark)}merge(e){return e instanceof ec&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new ec(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ec(n.from,n.to,e.markFromJSON(n.mark))}}_s.jsonID("removeMark",ec);class Im extends _s{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return sa.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return sa.fromReplace(e,this.pos,this.pos+1,new Gt(Ot.from(r),0,n.isLeaf?0:1))}invert(e){let n=e.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;ar.pos?null:new Fa(n.pos,r.pos,a,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Fa(n.from,n.to,n.gapFrom,n.gapTo,Gt.fromJSON(e,n.slice),n.insert,!!n.structure)}}_s.jsonID("replaceAround",Fa);function GR(t,e,n){let r=t.resolve(e),a=n-e,s=r.depth;for(;a>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,a--;if(a>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;a>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,a--}}return!1}function iVe(t,e,n,r){let a=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,d,u)=>{if(!c.isInline)return;let m=c.marks;if(!r.isInSet(m)&&u.type.allowsMarkType(r.type)){let p=Math.max(d,e),f=Math.min(d+c.nodeSize,n),x=r.addToSet(m);for(let v=0;vt.step(c)),s.forEach(c=>t.step(c))}function aVe(t,e,n,r){let a=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof CT){let d=o.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let d=Math.min(l+o.nodeSize,n);for(let u=0;ut.step(new ec(o.from,o.to,o.style)))}function z4(t,e,n,r=n.contentMatch,a=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function sVe(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function Tx(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,a=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+a,c=t.$to.indexAfter(r)-s;if(rn;x--)v||r.index(x)>0?(v=!0,u=Ot.from(r.node(x).copy(u)),m++):c--;let p=Ot.empty,f=0;for(let x=s,v=!1;x>n;x--)v||a.after(x+1)=0;o--){if(r.size){let l=n[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Ot.from(n[o].type.create(n[o].attrs,r))}let a=e.start,s=e.end;t.step(new Fa(a,s,a,s,new Gt(r,0,0),n.length,!0))}function uVe(t,e,n,r,a){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,n,(o,l)=>{let c=typeof a=="function"?a(o):a;if(o.isTextblock&&!o.hasMarkup(r,c)&&mVe(t.doc,t.mapping.slice(s).map(l),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!x?d=!1:!f&&x&&(d=!0)}d===!1&&Dre(t,o,l,s),z4(t,t.mapping.slice(s).map(l,1),r,void 0,d===null);let u=t.mapping.slice(s),m=u.map(l,1),p=u.map(l+o.nodeSize,1);return t.step(new Fa(m,p,m+1,p-1,new Gt(Ot.from(r.create(c,null,o.marks)),0,0),1,!0)),d===!0&&jre(t,o,l,s),!1}})}function jre(t,e,n,r){e.forEach((a,s)=>{if(a.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(a.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function Dre(t,e,n,r){e.forEach((a,s)=>{if(a.type==a.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(` diff --git a/static/index.html b/static/index.html index 53cfbca5a..fc68ce64f 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +