diff --git a/CHANGELOG.md b/CHANGELOG.md index 52f5f54f4..bc61a7b49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ All notable changes to Bambuddy will be documented in this file. - **K-Profiles View — Accurate Filament Name Resolution** — K-profile filament names are now resolved from builtin filament tables and user cloud presets (via new `/cloud/filament-id-map` endpoint) instead of showing raw IDs like "GFU99" or "P4d64437". Falls back to extracting names from the profile name field. ### Fixed +- **Stale Inventory Assignments Persist After Switching to Spoolman Mode** — When switching from built-in inventory to Spoolman mode, existing spool-to-AMS-slot assignments were not cleaned up. The printer card hover cards continued showing "Assign Spool" buttons that opened the internal inventory modal, and any prior assignments remained visible. Now bulk-deletes all `SpoolAssignment` records when enabling Spoolman, invalidates the frontend cache so printer cards update immediately, and hides the inventory assign/unassign UI on printer cards while in Spoolman mode. - **Bulk Archive Delete Leaves Orphaned Database Records** — When bulk-deleting archives, the files were removed from disk before the database commit. If concurrent SQLite writes caused a lock timeout, the commit failed and rolled back — leaving database records pointing to deleted files (broken thumbnails, 404 errors). Fixed by deleting the database record first and only removing files after a successful commit. - **Model-Specific Maintenance Tasks for Carbon Rods vs Linear Rails** ([#351](https://github.com/maziggy/bambuddy/issues/351)) — Maintenance tasks "Clean Carbon Rods" and "Lubricate Linear Rails" were shown for all printers regardless of motion system. H2 and A1 series use linear rails (not carbon rods), and X1/P1/P2S series use carbon rods (not linear rails). Maintenance types are now classified by rod/rail type: "Lubricate Carbon Rods" and "Clean Carbon Rods" for X1/P1/P2S, "Lubricate Linear Rails" and "Clean Linear Rails" for A1/H2. Stale and duplicate system types are automatically cleaned up on startup. Includes model-specific wiki links and i18n keys for all 4 locales. - **AMS Slot Configuration Overwritten on Startup** — Bambuddy was resetting AMS slot filament presets on every startup and reconnection. The `on_ams_change` callback unconditionally unlinked Bambu Lab spool assignments on each MQTT push-all response, then re-assigned them by sending `ams_filament_setting` without a `setting_id`, which cleared the printer's filament preset. Now compares spool RFID identifiers (`tray_uuid` / `tag_uid`) before unlinking — if the same spool is still in the slot, the assignment is preserved and no `ams_filament_setting` command is sent. diff --git a/backend/app/api/routes/settings.py b/backend/app/api/routes/settings.py index 24092c270..9f4efb49d 100644 --- a/backend/app/api/routes/settings.py +++ b/backend/app/api/routes/settings.py @@ -6,7 +6,7 @@ from pathlib import Path from fastapi import APIRouter, Depends, File, UploadFile from fastapi.responses import JSONResponse, StreamingResponse -from sqlalchemy import select +from sqlalchemy import delete, select from sqlalchemy.ext.asyncio import AsyncSession from backend.app.core.auth import RequirePermissionIfAuthEnabled @@ -258,7 +258,16 @@ async def update_spoolman_settings( ): """Update Spoolman integration settings.""" if "spoolman_enabled" in settings: - await set_setting(db, "spoolman_enabled", settings["spoolman_enabled"]) + old_val = await get_setting(db, "spoolman_enabled") or "false" + new_val = settings["spoolman_enabled"] + await set_setting(db, "spoolman_enabled", new_val) + + # Switching to Spoolman: clear built-in inventory slot assignments + if old_val.lower() != "true" and new_val.lower() == "true": + from backend.app.models.spool_assignment import SpoolAssignment + + result = await db.execute(delete(SpoolAssignment)) + logger.info("Cleared %d spool assignments on switch to Spoolman mode", result.rowcount) if "spoolman_url" in settings: await set_setting(db, "spoolman_url", settings["spoolman_url"]) if "spoolman_sync_mode" in settings: diff --git a/frontend/src/components/SpoolmanSettings.tsx b/frontend/src/components/SpoolmanSettings.tsx index f7a1d4904..526c2f0d2 100644 --- a/frontend/src/components/SpoolmanSettings.tsx +++ b/frontend/src/components/SpoolmanSettings.tsx @@ -91,6 +91,7 @@ export function SpoolmanSettings() { queryClient.invalidateQueries({ queryKey: ['spoolman-settings'] }); queryClient.invalidateQueries({ queryKey: ['spoolman-status'] }); queryClient.invalidateQueries({ queryKey: ['settings'] }); + queryClient.invalidateQueries({ queryKey: ['spool-assignments'] }); showToast(t('settings.toast.settingsSaved')); }, }); diff --git a/frontend/src/pages/PrintersPage.tsx b/frontend/src/pages/PrintersPage.tsx index 0e39749e9..1165fdb09 100644 --- a/frontend/src/pages/PrintersPage.tsx +++ b/frontend/src/pages/PrintersPage.tsx @@ -2926,7 +2926,7 @@ function PrinterCard({ }); } : undefined, }} - inventory={(() => { + inventory={spoolmanEnabled ? undefined : (() => { const assignment = onGetAssignment?.(printer.id, ams.id, slotIdx); return { assignedSpool: assignment?.spool ? { @@ -3164,7 +3164,7 @@ function PrinterCard({ }); } : undefined, }} - inventory={(() => { + inventory={spoolmanEnabled ? undefined : (() => { const assignment = onGetAssignment?.(printer.id, ams.id, htSlotId); return { assignedSpool: assignment?.spool ? { @@ -3350,7 +3350,7 @@ function PrinterCard({ }); } : undefined, }} - inventory={(() => { + inventory={spoolmanEnabled ? undefined : (() => { const assignment = onGetAssignment?.(printer.id, 255, slotTrayId); return { assignedSpool: assignment?.spool ? { diff --git a/static/assets/index-CEmIWZ6o.js b/static/assets/index-8IRr_Byo.js similarity index 95% rename from static/assets/index-CEmIWZ6o.js rename to static/assets/index-8IRr_Byo.js index a40dc8d68..f62621660 100644 --- a/static/assets/index-CEmIWZ6o.js +++ b/static/assets/index-8IRr_Byo.js @@ -8508,7 +8508,7 @@ void main() { flex items-center justify-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${zn&&M("printers:control")?Ot?"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:M("printers:control")?b(Ot?"printers.resume":"printers.pause"):b("printers.permission.noControl"),children:[Ot?a.jsx(jo,{className:"w-3 h-3"}):a.jsx(tk,{className:"w-3 h-3"}),b(Ot?"printers.resume":"printers.pause")]})]})]})]})})(),(Je?.length>0||ye.vt_tray.length>0)&&r==="expanded"&&(()=>{const bt=Je.filter(vt=>vt.tray.length>1),Ot=Je.filter(vt=>vt.tray.length===1),zn=t.nozzle_count===2||ye?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:b("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[bt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:bt.map(vt=>{const Cn=Oe[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,fr=Cn!==void 0?Cn:Zr,mi=fr===1,_a=fr===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:ih(vt.id,vt.tray.length)}),zn&&(mi||_a)&&a.jsx(J7,{side:mi?"L":"R"})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[vt.humidity!=null&&a.jsx(t9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"humidity"}),compact:!0}),vt.temp!=null&&a.jsx(n9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(Gt=>{const gn=vt.tray[Gt]||vt.tray.find(vr=>vr.id===Gt),za=gn?.tray_type&&gn.remain>=0,Jr=!gn?.tray_type,Ua=vt.id*4+Gt,Nl=an===Ua,Sa=gn?.tray_info_idx?Ue?.[gn.tray_info_idx]:null,Vi=je?.[Ua],Gi=gn?.tray_uuid?.toUpperCase(),Li=Gi?c?.[Gi]:void 0,Or=ej(Li),Cl=d?.(t.id,vt.id,Gt),Ba=(()=>{const vr=Cl?.spool;return vr&&vr.label_weight>0&&vr.weight_used>0?Math.round(Math.max(0,vr.label_weight-vr.weight_used)/vr.label_weight*100):null})(),wi=za&&gn.remain>0?gn.remain:Or??Ba??(za?gn.remain:null),ic=za&&gn.remain===0&&(Or!==null||Ba!==null)?Or!==null?"spoolman":"inventory":"ams",Wr=gn?.tray_type?{vendor:tj(gn)?"Bambu Lab":"Generic",profile:Sa?.name||Vi?.preset_name||gn.tray_sub_brands||gn.tray_type,colorName:XP(gn.tray_id_name)||YP(gn.tray_color),colorHex:gn.tray_color||null,kFactor:QP(gn.k),fillLevel:wi,trayUuid:gn.tray_uuid||null,tagUid:gn.tag_uid||null,fillSource:ic}:null,_i=xe?.amsId===vt.id&&xe?.slotId===Gt,co=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Jr?"opacity-50":""} ${Nl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:gn?.tray_color?`#${gn.tray_color}`:gn?.tray_type?"#333":"transparent",borderColor:Jr?"#666":"rgba(255,255,255,0.1)",borderStyle:Jr?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:gn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:wi!==null&&wi>=0&&gn?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${wi}%`,backgroundColor:JP(wi)}}):gn?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"relative group",children:[_i&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Ur,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ye?.state!=="RUNNING"&&a.jsx("button",{onClick:vr=>{vr.stopPropagation(),Gn(_n?.amsId===vt.id&&_n?.slotId===Gt?null:{amsId:vt.id,slotId:Gt})},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:b("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ye?.state!=="RUNNING"&&_n?.amsId===vt.id&&_n?.slotId===Gt&&a.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:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${M("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:vr=>{vr.stopPropagation(),M("printers:ams_rfid")&&($t.mutate({amsId:vt.id,slotId:Gt}),Gn(null))},disabled:_i||!M("printers:ams_rfid"),title:M("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Ur,{className:`w-3 h-3 ${_i?"animate-spin":""}`}),b("printers.rfid.reread")]})}),Wr?a.jsx(WP,{data:Wr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Wr.trayUuid?c?.[Wr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Wr.trayUuid?vr=>{$({tagUid:Wr.tagUid||"",trayUuid:vr,printerId:t.id,amsId:vt.id,trayId:Gt})}:void 0},inventory:(()=>{const vr=d?.(t.id,vt.id,Gt);return{assignedSpool:vr?.spool?{id:vr.spool.id,material:vr.spool.material,brand:vr.spool.brand,color_name:vr.spool.color_name}:null,onAssignSpool:Wr.vendor!=="Bambu Lab"?()=>ce({printerId:t.id,amsId:vt.id,trayId:Gt,trayInfo:{type:Wr.profile,color:Wr.colorHex||"",location:`${ih(vt.id,vt.tray.length)} Slot ${Gt+1}`}}):void 0,onUnassignSpool:vr&&Wr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,Gt):void 0}})(),configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:Gt,trayCount:vt.tray.length,trayType:gn?.tray_type||void 0,trayColor:gn?.tray_color||void 0,traySubBrands:gn?.tray_sub_brands||void 0,trayInfoIdx:gn?.tray_info_idx||void 0,extruderId:Cn,caliIdx:gn?.cali_idx,savedPresetId:Vi?.preset_id})},children:co}):a.jsx(KP,{configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:Gt,trayCount:vt.tray.length,extruderId:Cn})},children:co})]},Gt)})})]},vt.id)})}),(Ot.length>0||ye.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ot.map(vt=>{const Cn=Oe[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,fr=Cn!==void 0?Cn:Zr,mi=fr===1,_a=fr===0,Gt=vt.tray[0],gn=Gt?.tray_type&&Gt.remain>=0,za=!Gt?.tray_type,Jr=vt.id*4+(Gt?.id??0),Ua=an===Jr,Nl=Gt?.tray_info_idx?Ue?.[Gt.tray_info_idx]:null,Sa=je?.[Jr],Vi=Gt?.tray_uuid?.toUpperCase(),Gi=Vi?c?.[Vi]:void 0,Li=ej(Gi),Or=Gt?.id??0,Cl=d?.(t.id,vt.id,Or),Ba=(()=>{const Yn=Cl?.spool;return Yn&&Yn.label_weight>0&&Yn.weight_used>0?Math.round(Math.max(0,Yn.label_weight-Yn.weight_used)/Yn.label_weight*100):null})(),wi=gn&&Gt.remain>0?Gt.remain:Li??Ba??(gn?Gt.remain:null),ic=gn&&Gt.remain===0&&(Li!==null||Ba!==null)?Li!==null?"spoolman":"inventory":"ams",Wr=Gt?.tray_type?{vendor:tj(Gt)?"Bambu Lab":"Generic",profile:Nl?.name||Sa?.preset_name||Gt.tray_sub_brands||Gt.tray_type,colorName:XP(Gt.tray_id_name)||YP(Gt.tray_color),colorHex:Gt.tray_color||null,kFactor:QP(Gt.k),fillLevel:wi,trayUuid:Gt.tray_uuid||null,tagUid:Gt.tag_uid||null,fillSource:ic}:null,_i=Gt?.id??0,co=xe?.amsId===vt.id&&xe?.slotId===_i,vr=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${za?"opacity-50":""} ${Ua?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Gt?.tray_color?`#${Gt.tray_color}`:Gt?.tray_type?"#333":"transparent",borderColor:za?"#666":"rgba(255,255,255,0.1)",borderStyle:za?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Gt?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:wi!==null&&wi>=0?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${wi}%`,backgroundColor:JP(wi)}}):Gt?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:ih(vt.id,vt.tray.length)}),zn&&(mi||_a)&&a.jsx(J7,{side:mi?"L":"R"})]}),a.jsxs("div",{className:"flex gap-1.5",children:[a.jsxs("div",{className:"relative group flex-1",children:[co&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Ur,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ye?.state!=="RUNNING"&&a.jsx("button",{onClick:Yn=>{Yn.stopPropagation(),Gn(_n?.amsId===vt.id&&_n?.slotId===_i?null:{amsId:vt.id,slotId:_i})},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:b("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ye?.state!=="RUNNING"&&_n?.amsId===vt.id&&_n?.slotId===_i&&a.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:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${M("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Yn=>{Yn.stopPropagation(),M("printers:ams_rfid")&&($t.mutate({amsId:vt.id,slotId:_i}),Gn(null))},disabled:co||!M("printers:ams_rfid"),title:M("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Ur,{className:`w-3 h-3 ${co?"animate-spin":""}`}),b("printers.rfid.reread")]})}),Wr?a.jsx(WP,{data:Wr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Wr.trayUuid?c?.[Wr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Wr.trayUuid?Yn=>{$({tagUid:Wr.tagUid||"",trayUuid:Yn,printerId:t.id,amsId:vt.id,trayId:_i})}:void 0},inventory:(()=>{const Yn=d?.(t.id,vt.id,_i);return{assignedSpool:Yn?.spool?{id:Yn.spool.id,material:Yn.spool.material,brand:Yn.spool.brand,color_name:Yn.spool.color_name}:null,onAssignSpool:Wr.vendor!=="Bambu Lab"?()=>ce({printerId:t.id,amsId:vt.id,trayId:_i,trayInfo:{type:Wr.profile,color:Wr.colorHex||"",location:ih(vt.id,vt.tray.length)}}):void 0,onUnassignSpool:Yn&&Wr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,_i):void 0}})(),configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:_i,trayCount:vt.tray.length,trayType:Gt?.tray_type||void 0,trayColor:Gt?.tray_color||void 0,traySubBrands:Gt?.tray_sub_brands||void 0,trayInfoIdx:Gt?.tray_info_idx||void 0,extruderId:Cn,caliIdx:Gt?.cali_idx,savedPresetId:Sa?.preset_id})},children:vr}):a.jsx(KP,{configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:_i,trayCount:vt.tray.length,extruderId:Cn})},children:vr})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0",children:[vt.temp!=null&&a.jsx(n9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"temperature"}),compact:!0}),vt.humidity!=null&&a.jsx(t9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"humidity"}),compact:!0})]})]})]},vt.id)}),ye.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${ye.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:b("printers.external")})}),a.jsx("div",{className:`grid ${ye.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...ye.vt_tray].sort((vt,Cn)=>(vt.id??254)-(Cn.id??254)).map(vt=>{const Cn=vt.id??254,Zr=an===Cn,fr=Cn-254,mi=zn?b(Cn===254?"printers.extL":"printers.extR"):"",_a=vt.tray_info_idx?Ue?.[vt.tray_info_idx]:null,Gt=je?.[1020+fr],gn=vt.tray_uuid?.toUpperCase(),za=gn?c?.[gn]:void 0,Jr=ej(za),Ua=d?.(t.id,255,fr),Nl=(()=>{const Or=Ua?.spool;return Or&&Or.label_weight>0&&Or.weight_used>0?Math.round(Math.max(0,Or.label_weight-Or.weight_used)/Or.label_weight*100):null})(),Sa=Jr??Nl??null,Vi={vendor:tj(vt)?"Bambu Lab":"Generic",profile:_a?.name||Gt?.preset_name||vt.tray_sub_brands||vt.tray_type||"Unknown",colorName:XP(vt.tray_id_name)||YP(vt.tray_color),colorHex:vt.tray_color||null,kFactor:QP(vt.k),fillLevel:Sa,trayUuid:vt.tray_uuid||null,tagUid:vt.tag_uid||null,fillSource:Jr!==null?"spoolman":Nl!==null?"inventory":void 0},Gi=!vt.tray_type,Li=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Gi?"opacity-50":""} ${Zr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:vt.tray_color?`#${vt.tray_color}`:vt.tray_type?"#333":"transparent",borderColor:Gi?"#666":"rgba(255,255,255,0.1)",borderStyle:Gi?"dashed":"solid"}}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Gi?"text-white/40":"text-white"}`,children:vt.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Sa!==null&&Sa>=0&&!Gi?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Sa}%`,backgroundColor:JP(Sa)}}):Gi?null:a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"})}),mi&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:mi})]});return a.jsx("div",{className:"relative group",children:Gi?a.jsx(KP,{configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:255,trayId:fr,trayCount:1,extruderId:zn?Cn===254?1:0:void 0})},children:Li}):a.jsx(WP,{data:Vi,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Vi.trayUuid?c?.[Vi.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Vi.trayUuid?Or=>{$({tagUid:Vi.tagUid||"",trayUuid:Or,printerId:t.id,amsId:255,trayId:fr})}:void 0},inventory:(()=>{const Or=d?.(t.id,255,fr);return{assignedSpool:Or?.spool?{id:Or.spool.id,material:Or.spool.material,brand:Or.spool.brand,color_name:Or.spool.color_name}:null,onAssignSpool:()=>ce({printerId:t.id,amsId:255,trayId:fr,trayInfo:{type:Vi.profile,color:Vi.colorHex||"",location:mi||b("printers.external")}}),onUnassignSpool:Or?()=>h?.(t.id,255,fr):void 0}})(),configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:255,trayId:fr,trayCount:1,trayType:vt.tray_type||void 0,trayColor:vt.tray_color||void 0,traySubBrands:vt.tray_sub_brands||void 0,trayInfoIdx:vt.tray_info_idx||void 0,extruderId:zn?Cn===254?1:0:void 0,caliIdx:vt.cali_idx,savedPresetId:Gt?.preset_id})},children:Li})},Cn)})})]})]})]})]})})()]}),Pt&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(qh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Pt.name}),gt&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${gt.state==="ON"?"bg-bambu-green/20 text-bambu-green":gt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[gt.state||"?",gt.state==="ON"&>.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",gt.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>K(!0),disabled:De.isPending||gt?.state==="ON"||!M("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${M("smart_plugs:control")?gt?.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:M("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(fd,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>ae(!0),disabled:De.isPending||gt?.state==="OFF"||!M("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${M("smart_plugs:control")?gt?.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:M("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(nk,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${Pt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Pt.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>nt.mutate(!Pt.auto_off),disabled:nt.isPending||Pt.auto_off_executed||!M("smart_plugs:control"),title:M("smart_plugs:control")?Pt.auto_off_executed?b("printers.autoOffExecuted"):b("printers.autoOffAfterPrint"):b("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${M("smart_plugs:control")?Pt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Pt.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${Pt.auto_off||Pt.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Ie&&Ie.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(dv,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Ie.map(bt=>a.jsxs("button",{onClick:()=>dt.mutate(bt.id),disabled:dt.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:[a.jsx(jo,{className:"w-2.5 h-2.5"}),bt.name]},bt.id))})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{children:t.ip_address}),a.jsx("p",{className:"truncate",children:t.serial_number})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>pe.mutate(!ye?.chamber_light),disabled:!ye?.connected||pe.isPending||!M("printers:control"),title:M("printers:control")?ye?.chamber_light?b("printers.chamberLightOff"):b("printers.chamberLightOn"):b("printers.permission.noControl"),className:ye?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(hL,{on:ye?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>{if(p==="embedded"&&x)x(t.id,t.name);else{const bt=localStorage.getItem("cameraWindowState"),Ot=bt?JSON.parse(bt):{width:640,height:400},zn=[`width=${Ot.width}`,`height=${Ot.height}`,Ot.left!==void 0?`left=${Ot.left}`:"",Ot.top!==void 0?`top=${Ot.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,zn)}},disabled:!ye?.connected,title:b(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:a.jsx(RF,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(Te,{variant:"secondary",size:"sm",onClick:Tn,disabled:!ye?.connected||ze.isPending||!M("printers:update"),title:M("printers:update")?t.plate_detection_enabled?b("printers.plateDetection.enabledClick"):b("printers.plateDetection.disabledClick"):b("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:ze.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(T1,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:bn,disabled:!ye?.connected||z||!M("printers:update"),title:M("printers:update")?b("printers.plateDetection.manageCalibration"):b("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:z?a.jsx(it,{className:"w-3 h-3 animate-spin"}):a.jsx(Jn,{className:"w-3 h-3"})})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!M("printers:files"),title:M("printers:files")?b("printers.browseFiles"):b("printers.permission.noFiles"),children:[a.jsx($b,{className:"w-4 h-4"}),"Files"]})]})]})]}),B&&a.jsx(qMe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),H&&a.jsx(ZMe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),ge&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Vt(),children:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[ge.needs_calibration?a.jsx(T1,{className:"w-5 h-5 text-blue-500"}):ge.is_empty?a.jsx(gr,{className:"w-5 h-5 text-green-500"}):a.jsx(ha,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),ge.reference_count!==void 0&&ge.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[ge.reference_count,"/",ge.max_references," refs"]})]}),a.jsx("button",{onClick:()=>Vt(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[ge.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:b("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:b("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${ge.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${ge.is_empty?"text-green-400":"text-yellow-400"}`,children:ge.is_empty?b("printers.plateDetection.plateEmpty"):b("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[b("printers.plateDetection.confidence"),": ",Math.round(ge.confidence*100),"% | ",b("printers.plateDetection.difference"),": ",ge.difference_percent.toFixed(1),"%"]})]}),ge.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:b("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:ge.debug_image_url,alt:b("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:b("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:ge.message})]}),Dt&&Dt.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:b("printers.plateDetection.savedReferences",{count:Dt.references.length,max:Dt.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:Dt.references.map(bt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:se.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"}),a.jsx("button",{onClick:()=>Gr(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:b("printers.plateDetection.deleteReference"),children:a.jsx(Rt,{className:"w-3 h-3 text-white"})}),Jt?.index===bt.index?a.jsx("input",{type:"text",value:Jt.label,onChange:Ot=>Kt({...Jt,label:Ot.target.value}),onBlur:()=>pn(bt.index,Jt.label),onKeyDown:Ot=>{Ot.key==="Enter"&&pn(bt.index,Jt.label),Ot.key==="Escape"&&Kt(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:b("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Kt({index:bt.index,label:bt.label}),title:bt.label?b("printers.plateDetection.clickToEdit",{label:bt.label}):b("printers.plateDetection.clickToAddLabel"),children:bt.label||a.jsx("span",{className:"italic opacity-50",children:b("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:bt.timestamp?new Date(bt.timestamp).toLocaleDateString():""})]},bt.index))})]}),!ge.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:b("printers.roi.title")}),_e?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>be(null),disabled:He,children:b("common.cancel")}),a.jsx(Te,{size:"sm",onClick:qr,disabled:He,children:He?a.jsx(it,{className:"w-3 h-3 animate-spin"}):b("common.save")})]}):a.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>be(ge.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx($i,{className:"w-3 h-3 mr-1"}),b("common.edit")]})]}),_e?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_e.x,onChange:bt=>be({..._e,x:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_e.y,onChange:bt=>be({..._e,y:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_e.w,onChange:bt=>be({..._e,w:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_e.h,onChange:bt=>be({..._e,h:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:b("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((ge.roi?.x||.15)*100),"%, Y=",Math.round((ge.roi?.y||.35)*100),"%, W=",Math.round((ge.roi?.w||.7)*100),"%, H=",Math.round((ge.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:ge.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Te,{variant:"ghost",onClick:()=>Vt(),children:b("common.cancel")}),a.jsx(Te,{onClick:()=>fn(),disabled:W,children:W?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Te,{variant:"ghost",onClick:()=>fn(),disabled:W,children:W?"Adding...":`Add Reference (${Dt?.references.length||0}/${Dt?.max_references||5})`}),a.jsx(Te,{onClick:()=>Vt(),children:"Close"})]})})]})}),I&&Pt&&a.jsx(Pn,{title:b("printers.confirm.powerOnTitle"),message:b("printers.confirm.powerOnMessage",{name:t.name}),confirmText:b("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{De.mutate("on"),K(!1)},onCancel:()=>K(!1)}),Q&&Pt&&a.jsx(Pn,{title:b("printers.confirm.powerOffTitle"),message:ye?.state==="RUNNING"?b("printers.confirm.powerOffWarning",{name:t.name}):b("printers.confirm.powerOffMessage",{name:t.name}),confirmText:b("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{De.mutate("off"),ae(!1)},onCancel:()=>ae(!1)}),ne&&a.jsx(Pn,{title:b("printers.confirm.stopTitle"),message:b("printers.confirm.stopMessage",{name:t.name}),confirmText:b("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{pt.mutate(),ee(!1)},onCancel:()=>ee(!1)}),ve&&a.jsx(Pn,{title:b("printers.confirm.pauseTitle"),message:b("printers.confirm.pauseMessage",{name:t.name}),confirmText:b("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{lt.mutate(),fe(!1)},onCancel:()=>fe(!1)}),de&&a.jsx(Pn,{title:b("printers.confirm.resumeTitle"),message:b("printers.confirm.resumeMessage",{name:t.name}),confirmText:b("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Ft.mutate(),Re(!1)},onCancel:()=>Re(!1)}),a.jsx(mL,{printerId:t.id,isOpen:ue,onClose:()=>le(!1)}),V&&a.jsx(nAe,{printerName:t.name,errors:ye?.hms_errors||[],onClose:()=>Y(!1)}),Ne&&a.jsx(pHe,{isOpen:!!Ne,onClose:()=>J(null),printerId:t.id,printerName:t.name,amsId:Ne.amsId,amsLabel:Ne.amsLabel,initialMode:Ne.mode,thresholds:s}),Le&&a.jsx(gHe,{isOpen:!!Le,onClose:()=>$(null),tagUid:Le.tagUid,trayUuid:Le.trayUuid,printerId:Le.printerId,amsId:Le.amsId,trayId:Le.trayId}),X&&a.jsx(bHe,{isOpen:!!X,onClose:()=>ce(null),printerId:X.printerId,amsId:X.amsId,trayId:X.trayId,trayInfo:X.trayInfo}),q&&a.jsx(kHe,{isOpen:!!q,onClose:()=>ie(null),printerId:t.id,slotInfo:q,printerModel:_R(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),U&&a.jsx($He,{printer:t,onClose:()=>L(!1)}),te&&we&&a.jsx(HHe,{printer:t,firmwareInfo:we,onClose:()=>he(!1)}),_n&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Gn(null)})]})}function BHe({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Ut(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,u]=w.useState([]),[d,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[b,y]=w.useState([]),[S,N]=w.useState(""),[M,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{uc.getInfo().then(E=>{v(E.is_docker),E.subnets.length>0&&(y(E.subnets),N(E.subnets[0]))}).catch(()=>{})},[]);const T=c.filter(E=>!n.includes(E.serial)),C=async()=>{h(""),u([]),l(!0),p(!1),k({scanned:0,total:0});try{if(x){await uc.startSubnetScan(S);const E=setInterval(async()=>{try{const P=await uc.getScanStatus();k({scanned:P.scanned,total:P.total});const U=await uc.getDiscoveredPrinters();u(U),P.running||(clearInterval(E),l(!1),p(!0))}catch(P){console.error("Failed to get scan status:",P)}},500)}else{await uc.startDiscovery(10);const E=setInterval(async()=>{try{const P=await uc.getDiscoveredPrinters();u(P)}catch(P){console.error("Failed to get discovered printers:",P)}},1e3);setTimeout(async()=>{clearInterval(E);try{await uc.stopDiscovery()}catch{}l(!1),p(!0);try{const P=await uc.getDiscoveredPrinters();u(P)}catch(P){console.error("Failed to get final discovered printers:",P)}},1e4)}}catch(E){console.error("Failed to start discovery:",E),h(E instanceof Error?E.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},j=E=>{const P=E.serial.startsWith("unknown-")?"":E.serial;s({...i,name:E.name||"",serial_number:P,ip_address:E.ip_address,model:_R(E.model)}),u([])};return w.useEffect(()=>()=>{uc.stopDiscovery().catch(()=>{}),uc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const E=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(_t,{className:"w-full max-w-md",onClick:E=>E.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?a.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:S,onChange:E=>N(E.target.value),disabled:o,children:b.map(E=>a.jsx("option",{value:E,children:E},E))}):a.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:S,onChange:E=>N(E.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(Te,{type:"button",variant:"secondary",onClick:C,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),x&&M.total>0?r("printers.discovery.scanProgress",{scanned:M.scanned,total:M.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Br,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),d&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:d}),T.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:T.map(E=>a.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:()=>j(E),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:E.name||E.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[_R(E.model)||r("printers.discovery.unknown")," • ",E.ip_address,E.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Jn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},E.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),f&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),f&&!o&&c.length>0&&T.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:E=>{E.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.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:i.name,onChange:E=>s({...i,name:E.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.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:i.ip_address,onChange:E=>s({...i,ip_address:E.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.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:i.serial_number,onChange:E=>s({...i,serial_number:E.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.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:i.access_code,onChange:E=>s({...i,access_code:E.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.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:i.model||"",onChange:E=>s({...i,model:E.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.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:i.location||"",onChange:E=>s({...i,location:E.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:E=>s({...i,auto_archive:E.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Te,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function HHe({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Ut(),i=Zt(),{showToast:s}=hn(),{hasPermission:o}=Fr(),l=o("firmware:update"),[c,u]=w.useState(null),[d,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=et({queryKey:["firmwarePrepare",t.id],queryFn:()=>XS.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),b=ot({mutationFn:()=>XS.startUpload(t.id),onSuccess:()=>{h(!0);const S=setInterval(async()=>{try{const N=await XS.getUploadStatus(t.id);u(N),(N.status==="complete"||N.status==="error")&&(clearInterval(S),p(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);p(S)},onError:S=>{s(r("printers.firmwareModal.uploadFailed",{error:S.message}),"error"),h(!1)}});w.useEffect(()=>()=>{f&&clearInterval(f)},[f]);const y=()=>{u(null),b.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(_t,{className:"w-full max-w-md mx-4",children:a.jsxs(Nt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ui,{className:"w-5 h-5 text-orange-400"}):a.jsx(gr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.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?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!d&&!c?a.jsx("div",{className:"mb-4",children:x.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(Zi,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:x.errors.map((S,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Bi,{className:"w-4 h-4 flex-shrink-0"}),S]},N))})}):null:null,(d||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.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}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Te,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!d&&c?.status!=="complete"&&l&&a.jsx(Te,{onClick:y,disabled:b.isPending,children:b.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ui,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function $He({printer:t,onClose:e}){const{t:n}=Ut(),r=Zt(),{showToast:i}=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=ot({mutationFn:u=>se.updatePrinter(t.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:u=>i(u.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const u=d=>{d.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const c=u=>{u.preventDefault();const d={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&&(d.access_code=s.access_code),l.mutate(d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsx(_t,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.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:u=>o({...s,name:u.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.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:u=>o({...s,ip_address:u.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.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}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.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:u=>o({...s,access_code:u.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.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:u=>o({...s,model:u.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.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:u=>o({...s,location:u.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:u=>o({...s,auto_archive:u.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Te,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function VHe(t){const{data:e}=et({queryKey:["printerStatus",t],queryFn:()=>se.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function GHe({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=VHe(t.id),{data:s}=et({queryKey:["smartPlugStatus",e.id],queryFn:()=>se.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.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||"?"})]}),a.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:[a.jsx(fd,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function qHe(){const{t}=Ut(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[u,d]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const le=localStorage.getItem("printerCardSize");return le?parseInt(le,10):2}),v=p===1?"compact":"expanded",b=Zt(),{showToast:y}=hn(),{hasPermission:S}=Fr(),[N,M]=w.useState(()=>{const le=localStorage.getItem("openEmbeddedCameras");if(le)try{const Ne=JSON.parse(le);return new Map(Ne.map(J=>[J.id,J]))}catch{return new Map}return new Map});w.useEffect(()=>{const le=Array.from(N.values());le.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(le)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:T}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:C}=et({queryKey:["settings"],queryFn:se.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&M(new Map)},[C?.camera_view_mode,N.size]);const{data:j}=et({queryKey:["smart-plugs"],queryFn:se.getSmartPlugs}),{data:E}=et({queryKey:["maintenanceOverview"],queryFn:se.getMaintenanceOverview,staleTime:60*1e3}),{data:P}=et({queryKey:["spoolman-status"],queryFn:se.getSpoolmanStatus,staleTime:60*1e3}),U=P?.enabled&&P?.connected,{data:L}=et({queryKey:["unlinked-spools"],queryFn:se.getUnlinkedSpools,enabled:!!U,staleTime:30*1e3}),B=L&&L.length>0,{data:D}=et({queryKey:["linked-spools"],queryFn:se.getLinkedSpools,enabled:!!U,staleTime:30*1e3}),H=D?.linked,{data:G}=et({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),staleTime:30*1e3}),I=ot({mutationFn:({printerId:le,amsId:Ne,trayId:J})=>se.unassignSpool(le,Ne,J),onSuccess:()=>{b.invalidateQueries({queryKey:["spool-assignments"]})}}),K=(le,Ne,J)=>G?.find(Le=>Le.printer_id===le&&Le.ams_id===Number(Ne)&&Le.tray_id===Number(J)),Q=E?.reduce((le,Ne)=>(le[Ne.printer_id]={due_count:Ne.due_count,warning_count:Ne.warning_count,total_print_hours:Ne.total_print_hours},le),{})||{},ae=j?.reduce((le,Ne)=>(Ne.printer_id&&(le[Ne.printer_id]=Ne),le),{})||{},V=ot({mutationFn:se.createPrinter,onSuccess:()=>{b.invalidateQueries({queryKey:["printers"]}),b.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:le=>y(le.message||t("printers.toast.failedToAdd"),"error")}),Y=ot({mutationFn:le=>se.controlSmartPlug(le,"on"),onSuccess:()=>{b.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),ne=()=>{const le=!r;i(le),localStorage.setItem("hideDisconnectedPrinters",String(le))},ee=le=>{d(le),localStorage.setItem("printerSortBy",le)},ve=()=>{const le=!h;f(le),localStorage.setItem("printerSortAsc",String(le))},fe=()=>{switch(p){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"}},de=["S","M","L","XL"],Re=w.useMemo(()=>{if(!k)return[];const le=[...k];switch(u){case"name":le.sort((Ne,J)=>Ne.name.localeCompare(J.name));break;case"model":le.sort((Ne,J)=>(Ne.model||"").localeCompare(J.model||""));break;case"location":le.sort((Ne,J)=>{const Le=Ne.location||"",$=J.location||"";return!Le&&$?1:Le&&!$?-1:Le.localeCompare($)||Ne.name.localeCompare(J.name)});break;case"status":le.sort((Ne,J)=>{const Le=b.getQueryData(["printerStatus",Ne.id]),$=b.getQueryData(["printerStatus",J.id]),X=ce=>ce?.connected?ce.state==="RUNNING"?0:1:2;return X(Le)-X($)});break}return h||le.reverse(),le},[k,u,h,b]),ue=w.useMemo(()=>{if(u!=="location")return null;const le={};return Re.forEach(Ne=>{const J=Ne.location||"Ungrouped";le[J]||(le[J]=[]),le[J].push(Ne)}),le},[u,Re]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(UHe,{printers:k})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:u,onChange:le=>ee(le.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:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:ve,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?a.jsx(jf,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(lb,{className:"w-4 h-4 text-bambu-gray"})})]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:de.map((le,Ne)=>{const J=Ne+1,Le=p===J;return a.jsx("button",{onClick:()=>{x(J),localStorage.setItem("printerCardSize",String(J))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Ne===0?"rounded-l-lg":""} ${Ne===de.length-1?"rounded-r-lg":""} ${Le?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(le==="S"?"printers.cardSize.small":le==="M"?"printers.cardSize.medium":le==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:le},le)})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:ne,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(ae).length>0&&a.jsxs("div",{className:"relative",children:[a.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:[a.jsx(fd,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Jn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.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:[a.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")}),k?.filter(le=>ae[le.id]).map(le=>a.jsx(GHe,{printer:le,plug:ae[le.id],onPowerOn:Ne=>{c(Ne),Y.mutate(Ne)},isPowering:l===ae[le.id]?.id},le.id)),k?.filter(le=>ae[le.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Te,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),T?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?a.jsx(_t,{children:a.jsxs(Nt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Te,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):ue?a.jsx("div",{className:"space-y-6",children:Object.entries(ue).map(([le,Ne])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),le,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ne.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${fe()}`,children:Ne.map(J=>a.jsx(i9,{printer:J,hideIfDisconnected:r,maintenanceInfo:Q[J.id],viewMode:v,cardSize:p,amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,spoolmanEnabled:U,hasUnlinkedSpools:B,linkedSpools:H,spoolmanUrl:P?.url,onGetAssignment:K,onUnassignSpool:(Le,$,X)=>I.mutate({printerId:Le,amsId:$,trayId:X}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Le,$)=>M(X=>new Map(X).set(Le,{id:Le,name:$})),checkPrinterFirmware:C?.check_printer_firmware!==!1},J.id))})]},le))}):a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${fe()}`,children:Re.map(le=>a.jsx(i9,{printer:le,hideIfDisconnected:r,maintenanceInfo:Q[le.id],viewMode:v,cardSize:p,spoolmanEnabled:U,hasUnlinkedSpools:B,linkedSpools:H,spoolmanUrl:P?.url,onGetAssignment:K,onUnassignSpool:(Ne,J,Le)=>I.mutate({printerId:Ne,amsId:J,trayId:Le}),amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ne,J)=>M(Le=>new Map(Le).set(Ne,{id:Ne,name:J})),checkPrinterFirmware:C?.check_printer_firmware!==!1},le.id))}),e&&a.jsx(BHe,{onClose:()=>n(!1),onAdd:le=>V.mutate(le),existingSerials:k?.map(le=>le.serial_number)||[]}),Array.from(N.values()).map((le,Ne)=>a.jsx(QMe,{printerId:le.id,printerName:le.name,viewerIndex:Ne,onClose:()=>M(J=>{const Le=new Map(J);return Le.delete(le.id),Le})},le.id))]})}function WHe(){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 Nc(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:n=`${WHe()==="windows"?"bambustudio":"bambustudioopen"}://${encodeURIComponent(t)}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}function x4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Ut(),{data:o}=et({queryKey:["settings"],queryFn:se.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[u,d]=w.useState(null),[h,f]=w.useState(null),[p,x]=w.useState(!0),[v,b]=w.useState(null),[y,S]=w.useState(!1),[N,M]=w.useState(null),[k,T]=w.useState(0),[C,j]=w.useState(!1),[E,P]=w.useState(null),[U,L]=w.useState(!1),[B,D]=w.useState(!1),H=w.useRef(null),G=w.useRef(null),I=10,K=160,Q=240,ae=.35;w.useEffect(()=>{const ge=Z=>{Z.key==="Escape"&&i()};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[i]),w.useEffect(()=>{if(x(!0),c){const ge=(r||"").toLowerCase(),Z=ge==="3mf"||ge==="stl",z=ge==="gcode"||ge==="3mf";f({has_model:Z,has_gcode:z,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d(Z?"3d":z?"gcode":null),x(!1);return}if(!t){f(null),d(null),x(!1);return}se.getArchiveCapabilities(t).then(ge=>{f(ge),ge.has_model?d("3d"):ge.has_gcode&&d("gcode"),x(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(S(!0),M(null),T(0),c){const ge=(r||"").toLowerCase();if(!e||ge!=="3mf"){b(null),S(!1);return}se.getLibraryFilePlates(e).then(Z=>b(Z)).catch(()=>b(null)).finally(()=>S(!1));return}if(!t){b(null),S(!1);return}se.getArchivePlates(t).then(ge=>b(ge)).catch(()=>b(null)).finally(()=>S(!1))},[t,r,c,e]);const V=w.useMemo(()=>v?.plates??[],[v]),Y=(v?.is_multi_plate??!1)&&V.length>1,ne=C&&Y,ee=N==null?null:V.find(ge=>ge.index===N)??null,ve=ge=>ge.object_count??ge.objects?.length??0,fe=V.reduce((ge,Z)=>ge+ve(Z),0),de=ee?ve(ee):fe,Re=ee?s("modelViewer.plateNumber",{number:ee.index}):s("modelViewer.allPlates"),ue=V.length>0,le=w.useRef(null),Ne=w.useRef(null),[J,Le]=w.useState(10),[$,X]=w.useState(3),ce=V.length>J,q=Math.max(1,Math.ceil(V.length/J)),ie=ce?V.slice(k*J,(k+1)*J):V;w.useEffect(()=>{if(!ne){Le(10),X(3);return}const ge=le.current,Z=Ne.current;if(!ge||!Z)return;let z=0;const F=()=>{const _e=Z.clientWidth,He=Math.floor(_e/210),Se=Math.max(3,Math.min(5,He||3));X(Ae=>Ae===Se?Ae:Se);const $e=window.getComputedStyle(ge),Qe=Number.parseFloat($e.rowGap||"0"),we=ge.querySelector("button")?.getBoundingClientRect().height??44,Ce=Z.clientHeight,je=Math.max(1,Math.floor((Ce+Qe)/(we+Qe)))*Se,Ve=Math.max(1,je-1);Le(Ae=>Ae===Ve?Ae:Ve)},W=()=>{z&&cancelAnimationFrame(z),z=requestAnimationFrame(F)};W();const me=new ResizeObserver(W);return me.observe(Z),me.observe(ge),()=>{z&&cancelAnimationFrame(z),me.disconnect()}},[ne,V.length]),w.useEffect(()=>{if(!ce){T(0);return}T(ge=>Math.min(ge,q-1))},[V.length,ce,q]),w.useEffect(()=>{if(!ce||N==null)return;const ge=V.findIndex(z=>z.index===N);if(ge<0)return;const Z=Math.floor(ge/J);T(z=>z===Z?z:Z)},[V,J,N,ce]),w.useEffect(()=>{if(!ne){P(null),D(!1);return}if(B)return;const ge=H.current,Z=G.current;if(!ge||!Z)return;const z=ge.clientHeight;if(!z)return;const F=Math.max(Q,z*ae),W=Math.max(K,z-I-F),me=Math.min(Z.scrollHeight,W);P(Math.max(K,me))},[ne,B,V.length,k,I,K,Q,ae]),w.useEffect(()=>{if(!U)return;const ge=z=>{const F=H.current;if(!F)return;const W=F.getBoundingClientRect(),me=W.height;if(!me)return;const _e=Math.max(Q,me*ae),be=Math.max(K,me-I-_e),He=Math.min(be,Math.max(K,z.clientY-W.top));P(He)},Z=()=>{L(!1),D(!0)};return document.addEventListener("mousemove",ge),document.addEventListener("mouseup",Z),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",ge),document.removeEventListener("mouseup",Z),document.body.style.cursor="",document.body.style.userSelect=""}},[U,I,K,Q,ae]);const te=c?(r||"").toLowerCase()==="3mf":!0,he=()=>{if(!te)return;const ge=n||"model";if(c){const z=`${window.location.origin}${se.getLibraryFileDownloadUrl(e)}`;Nc(z,l);return}const Z=`${window.location.origin}${se.getArchiveForSlicer(t,ge)}`;Nc(Z,l)};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${C?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${C?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:ge=>ge.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),ue&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[Re,": ",s("modelViewer.objectCount",{count:de})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Te,{variant:"secondary",size:"sm",onClick:he,disabled:!te,children:[a.jsx(Xr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>j(ge=>!ge),title:C?"Exit fullscreen":"Enter fullscreen",children:C?a.jsx(EF,{className:"w-4 h-4"}):a.jsx(TF,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Rt,{className:"w-5 h-5"})})]})]}),h&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>h.has_model&&d("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Zi,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>h.has_gcode&&d("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(lhe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:p?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&h?a.jsxs("div",{ref:H,className:`w-full h-full flex flex-col ${ne?"gap-0 min-h-0":"gap-3"}`,children:[Y&&a.jsxs("div",{ref:G,style:ne&&E!=null?{height:E}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${ne?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(is,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&a.jsx(it,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:ne?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:Ne,className:ne?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:le,className:ne?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:ne?{gridTemplateColumns:`repeat(${$}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>M(null),className:`flex items-center rounded-lg border text-left transition-colors ${ne?"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:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ne?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${ne?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ne?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${ne?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:V.length})})]}),N==null&&a.jsx(Yr,{className:`${ne?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ie.map(ge=>a.jsxs("button",{type:"button",onClick:()=>M(ge.index),className:`flex items-center rounded-lg border text-left transition-colors ${ne?"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?a.jsx("img",{src:ge.thumbnail_url,alt:`Plate ${ge.index}`,className:`${ne?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ne?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${ne?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ne?"text-xs":"text-sm"} text-white font-medium truncate`,children:ge.name||s("modelViewer.plateNumber",{number:ge.index})}),a.jsx("p",{className:`${ne?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:ge.object_count??ge.objects?.length??0})})]}),N===ge.index&&a.jsx(Yr,{className:`${ne?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},ge.index))]})}),(ee||ce)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ee&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:ee.index})}),ee.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ee.print_time_seconds/60)})}),ee.filament_used_grams!=null&&a.jsxs("span",{children:[ee.filament_used_grams.toFixed(1)," g"]}),ee.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:ee.filaments.length})})]}),ce&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ee?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:k+1,total:q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>T(ge=>Math.max(ge-1,0)),disabled:k===0,className:`px-2 py-1 rounded border text-xs ${k===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 Z=Math.max(0,k-Math.floor(2.5));const z=Math.min(q,Z+5);z-Z<5&&(Z=Math.max(0,z-5));const F=Array.from({length:z-Z},(W,me)=>Z+me);return a.jsxs(a.Fragment,{children:[Z>0&&a.jsx("button",{type:"button",onClick:()=>T(0),className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),Z>1&&a.jsx("span",{className:"px-1",children:"…"}),F.map(W=>a.jsx("button",{type:"button",onClick:()=>T(W),className:`px-2 py-1 rounded border text-xs ${k===W?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:W+1},W)),zT(q-1),className:`px-2 py-1 rounded border text-xs ${k===q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q})]})})(),a.jsx("button",{type:"button",onClick:()=>T(ge=>Math.min(ge+1,q-1)),disabled:k>=q-1,className:`px-2 py-1 rounded border text-xs ${k>=q-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")})]})]})]})]})]}),ne&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:ge=>{ge.preventDefault(),L(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${U?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${ne?"min-h-0":""}`,children:a.jsx(aY,{url:c?se.getLibraryFileDownloadUrl(e):h.has_source?se.getSource3mfDownloadUrl(t):se.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&h?a.jsx(BY,{gcodeUrl:c?se.getLibraryFileGcodeUrl(e):se.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const GN={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function KHe(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,u=0;if(s!==o){const d=s-o;u=l>.5?d/(2-s-o):d/(s+o);const h=n/255,f=r/255,p=i/255;s===h?c=((f-p)/d+(f.85?"White":u<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function qN(t){const e=t.replace("#","").toLowerCase().substring(0,6);return GN[e]?GN[e]:KHe(t)}function sne(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(GN[n])return GN[n]}return null}function a9(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function ji(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function Rc(t,e,n=40){const r=ji(t),i=ji(e);if(!r||!i||r.length<6||i.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(i.substring(0,2),16),u=parseInt(i.substring(2,4),16),d=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function XHe(t,e,n,r){const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`AMS-${i} Slot ${e+1}`}function YHe(t,e,n){return t>=128?t:t*4+e}function QHe(t){if(!t)return"";const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function s9(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}function mM(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=a9(o.tray_color);e.push({type:o.tray_type,color:l,colorName:qN(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:XHe(i.id,o.id,s),globalTrayId:YHe(i.id,o.id),trayInfoIdx:o.tray_info_idx||"",extruderId:n?.[String(i.id)]})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=a9(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:qN(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",extruderId:r?o-254:void 0})}return e}function o9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=mM(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=l.tray_info_idx||"";let u=n.filter(v=>!r.has(v.globalTrayId));if(l.nozzle_id!=null){const v=u.filter(b=>b.extruderId===l.nozzle_id);v.length>0&&(u=v)}let d,h,f,p;if(c){const v=u.filter(b=>b.trayInfoIdx===c);v.length===1?d=v[0]:v.length>1&&(h=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&ji(b.color)===ji(l.color)),h||(f=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(b.color,l.color))),!h&&!f&&(p=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase())))}!d&&!h&&!f&&!p&&(h=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&ji(v.color)===ji(l.color)),h||(f=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(v.color,l.color))),!h&&!f&&(p=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=d||h||f||p||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.globalTrayId??-1}}),s=Math.max(...i.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function ZHe(t){return w.useMemo(()=>mM(t),[t])}function one(t,e,n){const r=ZHe(e),i=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(u=>{const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const T=n[d],C=r.find(j=>j.globalTrayId===T);if(C){const j=C.type?.toUpperCase()===u.type?.toUpperCase(),E=ji(C.color)===ji(u.color)||Rc(C.color,u.color);let P;return j&&E?P="match":j?P="type_only":P="mismatch",{...u,loaded:C,hasFilament:!0,typeMatch:j,colorMatch:E,status:P,isManual:!0}}}const h=u.tray_info_idx||"";let f=r.filter(T=>!c.has(T.globalTrayId));if(u.nozzle_id!=null){const T=f.filter(C=>C.extruderId===u.nozzle_id);T.length>0&&(f=T)}let p,x,v,b;if(h){const T=f.filter(C=>C.trayInfoIdx===h);T.length===1?p=T[0]:T.length>1&&(x=T.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase()&&ji(C.color)===ji(u.color)),x||(v=T.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(C.color,u.color))),!x&&!v&&(b=T.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase())))}!p&&!x&&!v&&!b&&(x=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&ji(T.color)===ji(u.color)),x||(v=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(T.color,u.color))),!x&&!v&&(b=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase())));const y=p||x||v||b||void 0;y&&c.add(y.globalTrayId);const S=!!y,N=S,M=!!p||!!x||!!v;let k;return p||x||v?k="match":b?k="type_only":k="mismatch",{...u,loaded:y,hasFilament:S,typeMatch:N,colorMatch:M,status:k,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return i.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function JHe(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,s=0;const o=new Set(Object.values(n));for(const u of t){const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const b=n[d],y=e.find(S=>S.globalTrayId===b);if(y){const S=y.type?.toUpperCase()===u.type?.toUpperCase(),N=ji(y.color)===ji(u.color)||Rc(y.color,u.color);S&&N?r++:S?i++:s++;continue}}let h=e.filter(b=>!o.has(b.globalTrayId));if(u.nozzle_id!=null){const b=h.filter(y=>y.extruderId===u.nozzle_id);b.length>0&&(h=b)}const f=h.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&ji(b.color)===ji(u.color)),p=f?void 0:h.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(b.color,u.color)),x=f||p?void 0:h.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()),v=f??p??x;v&&o.add(v.globalTrayId),f||p?r++:x?i++:s++}const l=t.length;let c="full";return s>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:s,totalSlots:l,status:c}}function e$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=mM(e);if(r.length===0)return;const i=new Set(Object.values(n)),s=[];for(const c of t.filaments){const u=c.slot_id||0;if(u>0&&n[u]!==void 0){s.push({slot_id:u,globalTrayId:n[u]});continue}let d=r.filter(v=>!i.has(v.globalTrayId));if(c.nozzle_id!=null){const v=d.filter(b=>b.extruderId===c.nozzle_id);v.length>0&&(d=v)}const h=d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&ji(v.color)===ji(c.color)),f=h?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Rc(v.color,c.color)),p=h||f?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=h??f??p;x&&i.add(x.globalTrayId),s.push({slot_id:u,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const l9={useDefault:!0,manualMappings:{},autoConfigured:!1};function t$e(t,e,n,r,i,s){const o=kF({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>se.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const b=o[v],y=b?.data,N=e?.find(P=>P.id===x)?.name||`Printer ${x}`,M=mM(y),k=i[x]||l9,T=o9(n,y),C=k.useDefault?r:k.manualMappings,j=e$e(n,y,C),E=JHe(n?.filaments,M,C);return{printerId:x,printerName:N,status:y,isLoading:b?.isLoading??!1,loadedFilaments:M,autoMapping:T,finalMapping:j,matchStatus:E.status,exactMatches:E.exactMatches,typeOnlyMatches:E.typeOnlyMatches,missingTypes:E.missingTypes,totalSlots:E.totalSlots,config:k}}),[t,o,e,n,i,r]),c=o.some(x=>x.isLoading),u=(x,v)=>{s(b=>({...b,[x]:{...b[x]||l9,...v}}))},d=x=>{const v=l.find(S=>S.printerId===x);if(!v||!v.status||!n?.filaments)return;const b=o9(n,v.status);if(!b)return;const y={};b.forEach((S,N)=>{S!==-1&&(y[N+1]=S)}),u(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},h=()=>{for(const x of t)d(x)},f=x=>l.find(b=>b.printerId===x)?.finalMapping,p=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:h,autoConfigurePrinter:d,getFinalMapping:f,allPrintersReady:p}}function n$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Zt(),[i,s]=w.useState(!1),o=(u,d)=>{if(u<=0)return;const h={...t.config.manualMappings};d===""?delete h[u]:h[u]=parseInt(d,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await se.refreshPrinterStatus(t.printerId),await new Promise(u=>setTimeout(u,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(u=>{const d=u.slot_id||0,h=t.config.manualMappings[d];let f,p=!1;if(h!==void 0)f=t.loadedFilaments.find(v=>v.globalTrayId===h),p=!0;else{const v=new Set(Object.values(t.config.manualMappings)),b=t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&ji(N.color)===ji(u.color)),y=b?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(N.color,u.color)),S=b||y?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase());f=b??y??S}let x="mismatch";if(f){const v=f.type?.toUpperCase()===u.type?.toUpperCase(),b=ji(f.color)===ji(u.color)||Rc(f.color,u.color);v&&b?x="match":v&&(x="type_only")}return{req:u,loaded:f,status:x,isManual:p}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(Ur,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:h,isManual:f},p)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${u.type} - ${qN(u.color)}`,children:a.jsx(s3,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),a.jsxs("span",{className:"text-white truncate",children:[u.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:d?.globalTrayId??"",onChange:x=>o(u.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${f?"ring-1 ring-blue-400/50":""}`,title:f?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(x=>a.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.type," (",x.colorName,")"]},x.globalTrayId))]}),h==="match"?a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Mn,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Mn,{className:"w-3 h-3 text-orange-400"})})]},p))]})}function r$e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:u,assignmentMode:d="printer",onAssignmentModeChange:h,targetModel:f,onTargetModelChange:p,targetLocation:x,onTargetLocationChange:v,slicedForModel:b}){const[y,S]=w.useState(!1),N=s?t:t.filter(I=>I.is_active),M=w.useMemo(()=>{if(d!=="printer"||!b||y)return N;const I=N.filter(K=>K.model===b);return I.length>0?I:N},[N,d,b,y]),k=N.length-M.length,T=w.useMemo(()=>{const I=N.map(K=>K.model).filter(K=>!!K);return[...new Set(I)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const I=N.filter(K=>K.model===f&&K.location).map(K=>K.location).filter(K=>!!K);return[...new Set(I)].sort()},[N,f]),j=h&&p&&T.length>0,E=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&u;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(M.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Bi,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const P=I=>{i?e.includes(I)?n(e.filter(K=>K!==I)):n([...e,I]):n([I])},U=()=>{n(M.map(I=>I.id))},L=()=>{n([])},B=(I,K,Q)=>{Q.stopPropagation(),!(!c||!u)&&(K?c(I):u(I,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=I=>e.includes(I),H=e.length,G=I=>o?.find(K=>K.printerId===I);return a.jsxs("div",{className:"space-y-2 mb-6",children:[j&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{h("printer"),p(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(Cr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const I=b&&T.includes(b)?b:T[0];p(I)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(gh,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",b||"Model"]})]})]}),d==="model"&&j&&a.jsxs("div",{className:"space-y-3 mb-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:f||"",onChange:I=>{p(I.target.value||null),v&&v(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 text-sm",children:[a.jsx("option",{value:"",children:"Select a model..."}),T.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),f&&C.length>0&&v&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:x||"",onChange:I=>v(I.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 text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),C.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",x?` in ${x}`:""]})]}),d==="printer"&&i&&M.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:H===0?"Select printers":`${H} printer${H!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[H0&&a.jsx("button",{type:"button",onClick:L,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),d==="printer"&&M.map(I=>{const K=D(I.id),Q=G(I.id),ae=Q&&!Q.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>P(I.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${K?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${I.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${K?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Cr,{className:`w-5 h-5 ${K?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:"text-white font-medium",children:[I.name,!I.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[I.model||"Unknown model"," • ",I.ip_address]})]}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${K?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:K&&a.jsx(Yr,{className:"w-3 h-3 text-white"})})]}),K&&E&&Q&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:V=>V.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:ae,onChange:V=>B(I.id,V.target.checked,V),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${Q.matchStatus==="full"?"text-bambu-green":Q.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",Q.exactMatches,"/",Q.totalSlots," matched)"]}),Q.isLoading&&a.jsx(Ur,{className:"w-3 h-3 text-bambu-gray animate-spin"}),ae&&a.jsxs("button",{type:"button",onClick:V=>{V.stopPropagation(),c(I.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(Spe,{className:"w-3 h-3"}),"Auto"]})]}),ae&&a.jsx(n$e,{printerResult:Q,filamentReqs:l.filaments,onUpdateConfig:V=>u(I.id,V)})]})]},I.id)}),d==="printer"&&k>0&&!y&&a.jsxs("button",{type:"button",onClick:()=>S(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(Mn,{className:"w-3 h-3 text-yellow-400"}),k," other printer",k>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),d==="printer"&&y&&b&&a.jsx("button",{type:"button",onClick:()=>S(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",b," printers"]})}),d==="printer"&&H===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Bi,{className:"w-3 h-3"}),"Select at least one printer"]}),d==="model"&&!f&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Bi,{className:"w-3 h-3"}),"Select a target printer model"]})]})}function i$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(is,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(Mn,{className:"w-3 h-3"}),"Selection required"]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>a.jsxs("button",{type:"button",onClick:()=>r(i.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===i.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[i.has_thumbnail&&i.thumbnail_url!=null?a.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(is,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"...":""):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${QHe(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx(Yr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function a$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,defaultExpanded:i=!1}){const{t:s}=Ut(),o=Zt(),[l,c]=w.useState(!1),[u,d]=w.useState(i),{data:h}=et({queryKey:["printer-status",t],queryFn:()=>se.getPrinterStatus(t),enabled:!!t}),{loadedFilaments:f,filamentComparison:p,hasTypeMismatch:x,hasColorMismatch:v}=one(e,h,n),b=e?.filaments&&e.filaments.length>0,y=e?.filaments?.some(k=>k.nozzle_id!=null)??!1;if(!b||!h)return null;const S=x?"#f97316":v?"#facc15":"#00ae42",N=(k,T)=>{if(k>0)if(T===""){const C={...n};delete C[k],r(C)}else r({...n,[k]:parseInt(T,10)})},M=async()=>{c(!0);try{await se.refreshPrinterStatus(t),await new Promise(k=>setTimeout(k,500)),await o.refetchQueries({queryKey:["printer-status",t]})}finally{c(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>d(!u),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(s3,{className:"w-4 h-4",fill:S,stroke:"none"}),a.jsx("span",{children:"Filament Mapping"}),x?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):v?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),u?a.jsx(Wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Jn,{className:"w-4 h-4 ml-auto"})]}),u&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:M,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:l,children:[a.jsx(Ur,{className:`w-3 h-3 ${l?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),p.map((k,T)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${k.type} - ${qN(k.color)}`,children:a.jsx(s3,{className:"w-3 h-3",fill:k.color,stroke:k.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[y&&k.nozzle_id!=null&&a.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:k.nozzle_id===1?s("printModal.leftNozzleTooltip"):s("printModal.rightNozzleTooltip"),children:k.nozzle_id===1?s("printModal.leftNozzle"):s("printModal.rightNozzle")}),k.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",k.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:k.loaded?.globalTrayId??"",onChange:C=>N(k.slot_id||0,C.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${k.status==="match"?"border-bambu-green/50 text-bambu-green":k.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${k.isManual?"ring-1 ring-blue-400/50":""}`,title:k.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),f.map(C=>a.jsxs("option",{value:C.globalTrayId,className:"bg-bambu-dark text-white",children:[C.label,": ",C.type," (",C.colorName,")"]},C.globalTrayId))]}),k.status==="match"?a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}):k.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Mn,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Mn,{className:"w-3 h-3 text-orange-400"})})]},T)),x&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}const s$e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function o$e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(ik,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(Wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Jn,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:s$e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function l$e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system"}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,u]=w.useState(!0),[d,h]=w.useState(!0),f=w.useRef(null),p=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){p.current=!1;return}if(!p.current){p.current=!0;let M;t.scheduledTime?(M=new Date(t.scheduledTime),isNaN(M.getTime())&&(M=new Date,M.setHours(M.getHours()+1,0,0,0))):(M=new Date,M.setHours(M.getHours()+1,0,0,0),e({...t,scheduledTime:p3(M)})),s(HB(M,n)),l($B(M,r)),u(!0),h(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const x=M=>{e({...t,scheduleType:M})},v=(M,k)=>{const T=Wpe(M,n),C=Kpe(k);u(!!T),h(!!C),T&&C&&(T.setHours(C.hours,C.minutes,0,0),T>new Date&&e({...t,scheduledTime:p3(T)}))},b=M=>{s(M),v(M,o)},y=M=>{l(M),v(i,M)},S=M=>{const k=M.target.value;if(k){const T=new Date(k);isNaN(T.getTime())||(s(HB(T,n)),l($B(T,r)),u(!0),h(!0),e({...t,scheduledTime:k}))}},N=()=>{f.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("asap"),children:[a.jsx(Xn,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("scheduled"),children:[a.jsx(ai,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("manual"),children:[a.jsx(aX,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${c?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:i,onChange:M=>b(M.target.value),placeholder:Gpe(n)}),a.jsx("button",{type:"button",onClick:N,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(ai,{className:"w-4 h-4"})})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:o,onChange:M=>y(M.target.value),placeholder:qpe(r)})})]}),a.jsx("input",{ref:f,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:S,tabIndex:-1}),(!c||!d)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:M=>e({...t,requirePreviousSuccess:M.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:M=>e({...t,autoOffAfter:M.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:"text-sm text-bambu-gray flex items-center gap-1",children:[a.jsx(fd,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Cg={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},c$e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Qu({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:s,onSuccess:o}){const{t:l}=Ut(),c=Zt(),{showToast:u}=hn(),d=!!n&&!e,[h,f]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[p,x]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[v,b]=w.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Cg.bed_levelling,flow_cali:i.flow_cali??Cg.flow_cali,vibration_cali:i.vibration_cali??Cg.vibration_cali,layer_inspect:i.layer_inspect??Cg.layer_inspect,timelapse:i.timelapse??Cg.timelapse}:Cg),[y,S]=w.useState(()=>{if(t==="edit-queue-item"&&i){let ye="asap";i.manual_start?ye="manual":i.scheduled_time&&!s9(i.scheduled_time)&&(ye="scheduled");let we="";if(i.scheduled_time&&!s9(i.scheduled_time)){const Ce=new Date(i.scheduled_time);we=p3(Ce)}return{scheduleType:ye,scheduledTime:we,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return c$e}),[N,M]=w.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ye={};return i.ams_mapping.forEach((we,Ce)=>{we!==-1&&(ye[Ce+1]=we)}),ye}return{}}),[k,T]=w.useState({}),[C,j]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[E,P]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[U,L]=w.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[B]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[D]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[H,G]=w.useState(!1),[I,K]=w.useState({current:0,total:0}),[Q,ae]=w.useState(new Set),V=h.length,Y=h.length>0?h[0]:null,{data:ne}=et({queryKey:["settings"],queryFn:se.getSettings}),{data:ee,isLoading:ve}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:fe}=et({queryKey:["archive",e],queryFn:()=>se.getArchive(e),enabled:!!e&&!d}),{data:de}=et({queryKey:["library-file",n],queryFn:()=>se.getLibraryFile(n),enabled:d&&!!n}),Re=fe?.sliced_for_model||de?.sliced_for_model||null,{data:ue,isError:le}=et({queryKey:["archive-plates",e],queryFn:()=>se.getArchivePlates(e),enabled:!!e&&!d,retry:!1}),{data:Ne}=et({queryKey:["library-file-plates",n],queryFn:()=>se.getLibraryFilePlates(n),enabled:d&&!!n}),J=d?Ne:ue,{data:Le,isError:$}=et({queryKey:["archive-filaments",e,p],queryFn:()=>se.getArchiveFilamentRequirements(e,p??void 0),enabled:!!e&&!d&&(p!==null||!J?.is_multi_plate),retry:!1}),{data:X}=et({queryKey:["library-file-filaments",n,p],queryFn:()=>se.getLibraryFileFilamentRequirements(n,p??void 0),enabled:d&&!!n&&(p!==null||!J?.is_multi_plate)}),ce=!d&&(le||$),q=d?X:Le,{data:ie}=et({queryKey:["printer-status",Y],queryFn:()=>se.getPrinterStatus(Y),enabled:!!Y}),{amsMapping:te}=one(q,ie,N),he=t$e(h,ee,q,N,k,T);w.useEffect(()=>{J?.plates?.length===1&&!p&&x(J.plates[0].index)},[J,p]),w.useEffect(()=>{if(t==="edit-queue-item")return;const ye=ee?.filter(we=>we.is_active)||[];ye.length===1&&h.length===0&&f([ye[0].id])},[t,ee,h.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(h.sort())!==JSON.stringify(B.sort())||p!==D)&&(M({}),T({}),ae(new Set)):(M({}),T({}),ae(new Set))},[t,h,p,B,D]),w.useEffect(()=>{if(!ne?.per_printer_mapping_expanded||h.length<=1)return;const ye=h.filter(we=>{if(Q.has(we))return!1;const Ce=he.printerResults.find(Ue=>Ue.printerId===we);return Ce&&Ce.status&&!Ce.isLoading});ye.length>0&&(ae(we=>{const Ce=new Set(we);return ye.forEach(Ue=>Ce.add(Ue)),Ce}),ye.forEach(we=>{he.autoConfigurePrinter(we)}))},[ne?.per_printer_mapping_expanded,h,Q,he]),w.useEffect(()=>{const ye=we=>{we.key==="Escape"&&!H&&s()};return window.addEventListener("keydown",ye),()=>window.removeEventListener("keydown",ye)},[s,H]);const ge=J?.is_multi_plate??!1,Z=J?.plates??[],z=ot({mutationFn:ye=>se.addToQueue(ye)}),F=ot({mutationFn:ye=>se.updateQueueItem(i.id,ye),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),o?.(),s()},onError:ye=>{u(ye.message||"Failed to update queue item","error")}}),W=async ye=>{if(ye?.preventDefault(),C==="printer"&&h.length===0){u("Please select at least one printer","error");return}if(C==="model"&&!E){u("Please select a target printer model","error");return}G(!0);const we=C==="model"?1:h.length;K({current:0,total:we});const Ce={success:0,failed:0,errors:[]},Ue=Ve=>{if(h.length>1){const Ae=k[Ve];if(Ae&&!Ae.useDefault)return he.getFinalMapping(Ve)}return te},je=Ve=>({printer_id:C==="printer"?Ve:null,target_model:C==="model"?E:null,target_location:C==="model"?U:null,archive_id:d?void 0:e,library_file_id:d?n:void 0,require_previous_success:y.requirePreviousSuccess,auto_off_after:y.autoOffAfter,manual_start:y.scheduleType==="manual",ams_mapping:Ve?Ue(Ve):void 0,plate_id:p,scheduled_time:y.scheduleType==="scheduled"&&y.scheduledTime?new Date(y.scheduledTime).toISOString():void 0,...v});if(C==="model"){K({current:1,total:1});try{if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),G(!1);return}else if(t==="edit-queue-item"){const Ve={printer_id:null,target_model:E,target_location:U,require_previous_success:y.requirePreviousSuccess,auto_off_after:y.autoOffAfter,manual_start:y.scheduleType==="manual",ams_mapping:void 0,plate_id:p,scheduled_time:y.scheduleType==="scheduled"&&y.scheduledTime?new Date(y.scheduledTime).toISOString():null,...v};await F.mutateAsync(Ve)}else await z.mutateAsync(je(null));Ce.success++}catch(Ve){Ce.failed++,Ce.errors.push(Ve.message)}}else for(let Ve=0;VeXe.id===Ae)?.name||`Printer ${Ae}`;Ce.errors.push(`${Pe}: ${Ze.message}`)}}if(G(!1),Ce.failed===0){if(C==="model")u(t==="edit-queue-item"?"Queue item updated":`Queued for any ${E}`);else{const Ve=t==="reprint"?"sent to":t==="edit-queue-item"?"updated/queued for":"queued for";Ce.success===1?u(t==="edit-queue-item"?"Queue item updated":`Print ${Ve} printer`):u(`Print ${Ve} ${Ce.success} printers`)}c.invalidateQueries({queryKey:["queue"]}),o?.(),s()}else Ce.success===0?u(`Failed: ${Ce.errors[0]}`,"error"):(u(`${Ce.success} succeeded, ${Ce.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},me=H||F.isPending,_e=w.useMemo(()=>!(me||C==="printer"&&h.length===0||C==="model"&&!E||C==="model"&&t==="reprint"||!d&&ge&&!p),[h.length,C,E,t,ge,p,me,d]),He=(()=>{const ye=h.length;return t==="reprint"?{title:l(d?"queue.print":"queue.reprint"),icon:Cr,submitText:ye>1?l("queue.printToPrinters",{count:ye}):l("queue.print"),submitIcon:Cr,loadingText:I.total>1?l("queue.sendingProgress",{current:I.current,total:I.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:ai,submitText:ye>1?l("queue.queueToPrinters",{count:ye}):l("queue.addToQueue"),submitIcon:ai,loadingText:I.total>1?l("queue.addingProgress",{current:I.current,total:I.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:$i,submitText:l("common.save"),submitIcon:$i,loadingText:I.total>1?l("queue.savingProgress",{current:I.current,total:I.total}):l("common.saving")}})(),Se=He.icon,$e=He.submitIcon,Qe=Y&&(d||(ge?p!==null:!0));return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:H?void 0:s,children:a.jsx(_t,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:ye=>ye.stopPropagation(),children:a.jsxs(Nt,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Se,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:He.title})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:s,disabled:H,children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:W,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(i$e,{plates:Z,isMultiPlate:ge,selectedPlate:p,onSelect:x}),a.jsx(r$e,{printers:ee||[],selectedPrinterIds:h,onMultiSelect:f,isLoading:ve,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:he.printerResults,filamentReqs:q,onAutoConfigurePrinter:he.autoConfigurePrinter,onUpdatePrinterConfig:he.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":C,onAssignmentModeChange:t!=="reprint"?j:void 0,targetModel:E,onTargetModelChange:t!=="reprint"?P:void 0,targetLocation:U,onTargetLocationChange:t!=="reprint"?L:void 0,slicedForModel:Re}),Re&&C==="printer"&&h.length===1&&(()=>{const ye=ee?.find(we=>we.id===h[0]);return ye&&ye.model&&Re!==ye.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(Mn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",Re,", but printing on ",ye.model]})]}):null})(),ce&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(Bi,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Qe&&!ce&&h.length===1&&a.jsx(a$e,{printerId:Y,filamentReqs:q,manualMappings:N,onManualMappingChange:M,defaultExpanded:ne?.per_printer_mapping_expanded??!1}),(t==="reprint"||V>0||C==="model"&&E)&&a.jsx(o$e,{options:v,onChange:b}),t!=="reprint"&&a.jsx(l$e,{options:y,onChange:S,dateFormat:ne?.date_format||"system",timeFormat:ne?.time_format||"system"}),F.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:F.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:H,children:"Cancel"}),a.jsx(Te,{type:"submit",disabled:!_e,className:"flex-1",children:me?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),He.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx($e,{className:"w-4 h-4"}),He.submitText]})})]})]})]})})})}function u$e({onClose:t,initialFiles:e}){const{t:n}=Ut(),r=Zt(),{showToast:i}=hn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(k=>k.name.endsWith(".3mf")).map(k=>({file:k,status:"pending"}))||[]),[c,u]=w.useState(!1),[d,h]=w.useState(null);w.useEffect(()=>{const k=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const f=ot({mutationFn:k=>se.uploadArchivesBulk(k),onSuccess:k=>{h(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(T=>T.map(C=>{const j=k.results.find(P=>P.filename===C.file.name),E=k.errors.find(P=>P.filename===C.file.name);return j?{...C,status:"success",archiveId:j.id}:E?{...C,status:"error",error:E.error}:C})),k.failed===0?i(`${k.uploaded} file${k.uploaded!==1?"s":""} uploaded`):k.uploaded===0?i(`Failed to upload ${k.failed} file${k.failed!==1?"s":""}`,"error"):i(`${k.uploaded} uploaded, ${k.failed} failed`,"warning")},onError:()=>{l(k=>k.map(T=>({...T,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),p=w.useCallback(k=>{k.preventDefault(),u(!0)},[]),x=w.useCallback(k=>{k.preventDefault(),u(!1)},[]),v=w.useCallback(k=>{k.preventDefault(),u(!1);const T=Array.from(k.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));T.length>0&&l(C=>[...C,...T.map(j=>({file:j,status:"pending"}))])},[]),b=w.useCallback(k=>{const T=Array.from(k.target.files||[]).filter(C=>C.name.endsWith(".3mf"));T.length>0&&l(C=>[...C,...T.map(j=>({file:j,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(k=>{l(T=>T.filter((C,j)=>j!==k))},[]),S=()=>{if(o.length===0)return;const k=o.filter(T=>T.status==="pending");k.length!==0&&(l(T=>T.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(k.map(T=>T.file)))},N=o.filter(k=>k.status==="pending").length,M=f.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.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:p,onDragLeave:x,onDrop:v,children:[a.jsx(sa,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Te,{variant:"secondary",onClick:()=>s.current?.click(),disabled:M,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((k,T)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(YC,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:k.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(k.file.size/(1024*1024)).toFixed(1)," MB"]}),k.status==="pending"&&a.jsx("button",{onClick:()=>y(T),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:M,children:a.jsx(Rt,{className:"w-4 h-4"})}),k.status==="uploading"&&a.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),k.status==="success"&&a.jsx(gr,{className:"w-4 h-4 text-bambu-green"}),k.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:k.error}),a.jsx(Bi,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${T}`))})}),d&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:d.uploaded})," ",n("uploadModal.uploaded"),d.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:d.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Te,{variant:"secondary",onClick:t,className:"flex-1",children:n(d?"common.close":"common.cancel")}),!d&&a.jsx(Te,{onClick:S,disabled:N===0||M,className:"flex-1",children:M?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(sa,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const d$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],h$e=["completed","failed","aborted","printing"];function lne({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Ut();w.useEffect(()=>{const ue=le=>{le.key==="Escape"&&e()};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[e]);const i=Zt(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[u,d]=w.useState(t.project_id??null),[h,f]=w.useState(t.notes||""),[p,x]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[y,S]=w.useState(t.status),[N,M]=w.useState(t.quantity??1),[k,T]=w.useState(t.photos||[]),[C,j]=w.useState(t.external_url||""),[E,P]=w.useState(!1),[U,L]=w.useState(!1),B=w.useRef(null),D=w.useRef(null),H=w.useRef(null),{data:G}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:I}=et({queryKey:["projects"],queryFn:()=>se.getProjects()}),{data:K}=et({queryKey:["tags"],queryFn:se.getTags,enabled:n.length===0}),Q=n.length>0?n:K?.map(ue=>ue.name)||[],ae=p.split(",").map(ue=>ue.trim()).filter(Boolean),V=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),Y=Q.filter(ue=>!ae.includes(ue)&&(V===""||ue.toLowerCase().includes(V))),ne=ue=>{let le;if(V&&!Q.includes(V)?le=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(Ne=>Ne.trim()).filter(Boolean):[]:le=ae,!le.includes(ue)){const Ne=[...le,ue].join(", ");x(Ne)}H.current!==null&&clearTimeout(H.current),B.current?.focus()},ee=ue=>{const le=ae.filter(Ne=>Ne!==ue).join(", ");x(le)},ve=ot({mutationFn:ue=>se.updateArchive(t.id,ue),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),fe=async ue=>{const le=ue.target.files?.[0];if(le){P(!0);try{const Ne=await se.uploadArchivePhoto(t.id,le);T(Ne.photos),i.invalidateQueries({queryKey:["archives"]})}catch(Ne){console.error("Failed to upload photo:",Ne)}finally{P(!1),D.current&&(D.current.value="")}}},de=async ue=>{try{const le=await se.deleteArchivePhoto(t.id,ue);T(le.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(le){console.error("Failed to delete photo:",le)}},Re=ue=>{ue.preventDefault();const le={print_name:s||void 0,printer_id:l,project_id:u,notes:h||void 0,tags:p||void 0,quantity:N,external_url:C||null};y!==t.status&&(le.status=y),y==="failed"||y==="aborted"?le.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(le.failure_reason=null),ve.mutate(le)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:ue=>ue.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Re,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:ue=>o(ue.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")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:ue=>c(ue.target.value?Number(ue.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),G?.map(ue=>a.jsx("option",{value:ue.id,children:ue.name},ue.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(ys,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:u??"",onChange:ue=>d(ue.target.value?Number(ue.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),I?.map(ue=>a.jsx("option",{value:ue.id,children:ue.name},ue.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(cme,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:ue=>M(Math.max(1,parseInt(ue.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:h,onChange:ue=>f(ue.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")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Vb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:C,onChange:ue=>j(ue.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/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),ae.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:ae.map(ue=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(Gh,{className:"w-3 h-3"}),ue,a.jsx("button",{type:"button",onClick:()=>ee(ue),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Rt,{className:"w-3 h-3"})})]},ue))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:B,type:"text",value:p,onChange:ue=>x(ue.target.value),onFocus:()=>{H.current!==null&&clearTimeout(H.current),L(!0)},onBlur:()=>{H.current=window.setTimeout(()=>L(!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:ae.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),U&&Y.length>0&&a.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:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[V?r("editArchive.matchingTags",{query:V}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:Y.map(ue=>a.jsx("button",{type:"button",onClick:()=>ne(ue),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:ue},ue))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:y,onChange:ue=>{S(ue.target.value),ue.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:h$e.map(ue=>a.jsx("option",{value:ue,children:r(`editArchive.statuses.${ue}`)},ue))})]}),(y==="failed"||y==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:ue=>b(ue.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),d$e.map(ue=>a.jsx("option",{value:r(`editArchive.failureReasons.${ue}`),children:r(`editArchive.failureReasons.${ue}`)},ue))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(cb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[k.map(ue=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:se.getArchivePhotoUrl(t.id,ue),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>de(ue),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(en,{className:"w-3 h-3 text-white"})})]},ue)),a.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:[a.jsx("input",{ref:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:fe,className:"hidden",disabled:E}),E?a.jsx(it,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(rr,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Te,{type:"submit",disabled:ve.isPending,className:"flex-1",children:[a.jsx(xs,{className:"w-4 h-4"}),ve.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function cne({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,u]=w.useState({x:t,y:e,visible:!1}),[d,h]=w.useState(!1),[f,p]=w.useState({});w.useEffect(()=>{const b=N=>{i.current&&!i.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},S=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",y),document.addEventListener("scroll",S,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",y),document.removeEventListener("scroll",S,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),y=window.innerWidth,S=window.innerHeight,N=8;let M=t,k=e;t+b.width>y-N&&(M=Math.max(N,y-b.width-N)),MS-N&&(k=Math.max(N,S-b.height-N)),kT),u({x:M,y:k,visible:!0})}},[t,e]);const x=(b,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const S=y.getBoundingClientRect(),N=window.innerHeight,M=300,C=N-S.top-8M;p(j=>({...j,[b]:C?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,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((b,y)=>{if(b.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const S=b.submenu&&b.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:N=>S&&x(y,N.currentTarget),onMouseLeave:()=>S&&v(),children:[a.jsxs("button",{onMouseEnter:N=>S&&x(y,N.currentTarget.parentElement),onClick:()=>{S?o(s===y?null:y):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${S&&s===y?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),a.jsx("span",{className:"flex-1",children:b.label}),S&&a.jsx(Fa,{className:"w-4 h-4 text-bambu-gray"})]}),S&&s===y&&a.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] ${d?"right-full mr-1":"left-full ml-1"} ${f[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((N,M)=>a.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&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},M))})]},y)})})}function m$e({selectedIds:t,existingTags:e,onClose:n}){const r=Zt(),{showToast:i}=hn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[u,d]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const h=ot({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const y of t)try{const S=await se.getArchive(y),N=S.tags?S.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let M;u==="add"?M=[...new Set([...N,...v])]:M=N.filter(k=>!l.has(k)),await se.updateArchive(y,{tags:M.join(", ")}),b++}catch(S){throw console.error(`Failed to update archive ${y}:`,S),new Error(`Failed on archive ${y}: ${S instanceof Error?S.message:"Unknown error"}`)}return{count:b,mode:u,tags:v}},onSuccess:({count:v,mode:b,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),f=v=>{c(b=>{const y=new Set(b);return y.has(v)?y.delete(v):y.add(v),y})},p=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),p())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-md",children:a.jsxs(Nt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Gh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Te,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),a.jsx(Te,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.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}),a.jsx(Te,{size:"sm",variant:"secondary",onClick:p,disabled:!s.trim(),children:a.jsx(rr,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>f(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&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>f(v),className:"hover:opacity-70",children:a.jsx(Rt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Te,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Te,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Gh,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function f$e({selectedIds:t,onClose:e}){const n=Zt(),{showToast:r}=hn(),{data:i,isLoading:s}=et({queryKey:["projects"],queryFn:()=>se.getProjects()});w.useEffect(()=>{const d=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=ot({mutationFn:async d=>(await se.addArchivesToProject(d,t),d),onSuccess:d=>{const h=i?.find(f=>f.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=ot({mutationFn:async()=>{for(const d of t)await se.updateArchive(d,{project_id:null});return t.length},onSuccess:d=>{o(),r(`Removed ${d} archive${d!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),u=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:u,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:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(ha,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(d=>a.jsxs("button",{onClick:()=>l.mutate(d.id),disabled:u,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:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:d.color?`${d.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(ys,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:d.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[d.archive_count," archive",d.archive_count!==1?"s":"",d.status&&` • ${d.status}`]})]}),l.isPending&&l.variables===d.id&&a.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(Te,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function p$e(t,e){return new Date(t,e+1,0).getDate()}function g$e(t,e){return new Date(t,e,1).getDay()}const b$e=["January","February","March","April","May","June","July","August","September","October","November","December"],x$e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function y$e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,u]=w.useState(null),[d,h]=w.useState(null),f=w.useMemo(()=>{const k=new Map;return t.forEach(T=>{const C=Ji(T.completed_at||T.created_at)||new Date,j=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,E=k.get(j)||[];E.push(T),k.set(j,E)}),k},[t]),p=p$e(o,i),x=g$e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},S=[];for(let k=0;k{k!==c&&h(null),u(k)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Fc,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[b$e[i]," ",o]}),a.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"})]}),a.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Fa,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:x$e.map(k=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:k},k))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:S.map((k,T)=>{if(k===null)return a.jsx("div",{className:"aspect-square"},`empty-${T}`);const C=`${o}-${String(i+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,j=f.get(C)||[],E=j.length>0,P=k===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),U=C===c,L=j.filter(D=>D.status==="completed").length,B=j.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>M(U?null:C),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${U?"bg-bambu-green text-white":P?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":E?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${P&&!U?"text-bambu-green":""}`,children:k}),E&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${B>0&&L===0?"bg-red-400":B>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:j.length})]})]},k)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(k=>{const T=new Date(k.completed_at||k.created_at);return T.getMonth()===i&&T.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(k=>{const T=new Date(k.completed_at||k.created_at);return T.getMonth()===i&&T.getFullYear()===o&&k.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(k=>{const T=new Date(k.completed_at||k.created_at);return T.getMonth()===i&&T.getFullYear()===o&&k.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.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?a.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:N.map(k=>{const T=k.id===d||k.id===n;return a.jsxs("button",{onClick:()=>{h(k.id),e?.(k)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${T?"":"hover:bg-bambu-dark-tertiary"}`,style:T?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?a.jsx("img",{src:se.getArchiveThumbnail(k.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:k.print_name||k.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:k.status==="failed"?"text-red-400":"text-green-400",children:k.status==="failed"?"Failed":"Completed"}),k.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:k.filament_color.split(",").map((C,j)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:C}},j))})]})]})]},k.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function une({archiveId:t,archiveName:e,onClose:n}){const r=se.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(Te,{onClick:i,className:"w-full",children:[a.jsx(ui,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function dne({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const p=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",p),()=>window.removeEventListener("keydown",p)},[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 u=n[s],d=se.getArchivePhotoUrl(t,u),h=()=>{const p=document.createElement("a");p.href=d,p.download=`${e}_photo_${s+1}.jpg`,p.click()},f=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:p=>p.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Te,{variant:"secondary",size:"sm",onClick:h,children:[a.jsx(ui,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Te,{variant:"secondary",size:"sm",onClick:f,className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(p=>p-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Fc,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:d,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(p=>p+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Fa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((p,x)=>a.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:a.jsx("img",{src:se.getArchivePhotoUrl(t,p),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},p))})]}),l&&a.jsx(Pn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function Ya(t){this.content=t}Ya.prototype={constructor:Ya,find:function(t){for(var e=0;e>1}};Ya.from=function(t){if(t instanceof Ya)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Ya(e)};function hne(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=hne(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function mne(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),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 u=0,d=Math.min(o.text.length,l.text.length);for(;ue&&r(c,i+l,s||null,o)!==!1&&c.content.size){let d=l+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let u=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&u||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=u},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.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),i+=l.nodeSize),o=c}return new Tt(r,i)}cutByIndex(e,n){return e==n?Tt.empty:e==0&&n==this.content.length?this:new Tt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new Tt(i,s)}addToStart(e){return new Tt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Tt(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 i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?AS(n+1,s):AS(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 Tt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Tt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Tt.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),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-i.type.rank),n}};Hr.none=[];class KN extends Error{}class Bt{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=pne(this.content,e+this.openStart,n);return r&&new Bt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Bt(fne(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 Bt.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Bt(Tt.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=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)i++;return new Bt(e,r,i)}}Bt.empty=new Bt(Tt.empty,0,0);function fne(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==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(fne(s.content,e-i-1,n-i-1)))}function pne(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=pne(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function v$e(t,e,n){if(n.openStart>t.depth)throw new KN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new KN("Inconsistent open depths");return gne(t,e,n,0)}function gne(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function Zy(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(Nf(t.nodeAfter,r),s++));for(let l=s;li&&NR(t,e,i+1),o=r.depth>i&&NR(n,r,i+1),l=[];return Zy(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(bne(s,o),Nf(Cf(s,xne(t,e,n,r,i+1)),l)):(s&&Nf(Cf(s,XN(t,e,i+1)),l),Zy(e,n,i,l),o&&Nf(Cf(o,XN(n,r,i+1)),l)),Zy(r,null,i,l),new Tt(l)}function XN(t,e,n){let r=[];if(Zy(null,t,n,r),t.depth>n){let i=NR(t,e,n+1);Nf(Cf(i,XN(t,e,n+1)),r)}return Zy(e,null,n,r),new Tt(r)}function w$e(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)i=e.node(s).copy(Tt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class W0{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],i=e.child(n);return r?e.child(n).cut(r):i}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],i=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 YN(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=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),u=s-c;if(r.push(o,l,i+c),!u||(o=o.child(l),o.isText))break;s=u-1,i+=c+1}return new W0(n,r,s)}static resolveCached(e,n){let r=c9.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}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()+")"),yne(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=Tt.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;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 i=Tt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Bh.prototype.text=void 0;class QN extends Bh{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):yne(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 QN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new QN(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 yne(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Qf{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new C$e(e,n);if(r.next==null)return Qf.empty;let i=vne(r);r.next&&r.err("Unexpected trailing text");let s=j$e(P$e(i));return D$e(s,r),s}matchType(e){for(let n=0;nu.createAndFill()));for(let u=0;u=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 i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` + `,title:M("printers:control")?b(Ot?"printers.resume":"printers.pause"):b("printers.permission.noControl"),children:[Ot?a.jsx(jo,{className:"w-3 h-3"}):a.jsx(tk,{className:"w-3 h-3"}),b(Ot?"printers.resume":"printers.pause")]})]})]})]})})(),(Je?.length>0||ye.vt_tray.length>0)&&r==="expanded"&&(()=>{const bt=Je.filter(vt=>vt.tray.length>1),Ot=Je.filter(vt=>vt.tray.length===1),zn=t.nozzle_count===2||ye?.temperatures?.nozzle_2!==void 0;return a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx("span",{className:"text-[10px] uppercase tracking-wider text-bambu-gray font-medium",children:b("printers.filaments")}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary/30"})]}),a.jsxs("div",{className:"space-y-3",children:[bt.length>0&&a.jsx("div",{className:"grid grid-cols-2 gap-3",children:bt.map(vt=>{const Cn=Oe[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,fr=Cn!==void 0?Cn:Zr,mi=fr===1,_a=fr===0;return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:ih(vt.id,vt.tray.length)}),zn&&(mi||_a)&&a.jsx(J7,{side:mi?"L":"R"})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex items-center gap-1.5",children:[vt.humidity!=null&&a.jsx(t9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"humidity"}),compact:!0}),vt.temp!=null&&a.jsx(n9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"temperature"}),compact:!0})]})]}),a.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:[0,1,2,3].map(Gt=>{const gn=vt.tray[Gt]||vt.tray.find(vr=>vr.id===Gt),za=gn?.tray_type&&gn.remain>=0,Jr=!gn?.tray_type,Ua=vt.id*4+Gt,Nl=an===Ua,Sa=gn?.tray_info_idx?Ue?.[gn.tray_info_idx]:null,Vi=je?.[Ua],Gi=gn?.tray_uuid?.toUpperCase(),Li=Gi?c?.[Gi]:void 0,Or=ej(Li),Cl=d?.(t.id,vt.id,Gt),Ba=(()=>{const vr=Cl?.spool;return vr&&vr.label_weight>0&&vr.weight_used>0?Math.round(Math.max(0,vr.label_weight-vr.weight_used)/vr.label_weight*100):null})(),wi=za&&gn.remain>0?gn.remain:Or??Ba??(za?gn.remain:null),ic=za&&gn.remain===0&&(Or!==null||Ba!==null)?Or!==null?"spoolman":"inventory":"ams",Wr=gn?.tray_type?{vendor:tj(gn)?"Bambu Lab":"Generic",profile:Sa?.name||Vi?.preset_name||gn.tray_sub_brands||gn.tray_type,colorName:XP(gn.tray_id_name)||YP(gn.tray_color),colorHex:gn.tray_color||null,kFactor:QP(gn.k),fillLevel:wi,trayUuid:gn.tray_uuid||null,tagUid:gn.tag_uid||null,fillSource:ic}:null,_i=xe?.amsId===vt.id&&xe?.slotId===Gt,co=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Jr?"opacity-50":""} ${Nl?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:gn?.tray_color?`#${gn.tray_color}`:gn?.tray_type?"#333":"transparent",borderColor:Jr?"#666":"rgba(255,255,255,0.1)",borderStyle:Jr?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:gn?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:wi!==null&&wi>=0&&gn?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${wi}%`,backgroundColor:JP(wi)}}):gn?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"relative group",children:[_i&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Ur,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ye?.state!=="RUNNING"&&a.jsx("button",{onClick:vr=>{vr.stopPropagation(),Gn(_n?.amsId===vt.id&&_n?.slotId===Gt?null:{amsId:vt.id,slotId:Gt})},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:b("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ye?.state!=="RUNNING"&&_n?.amsId===vt.id&&_n?.slotId===Gt&&a.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:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${M("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:vr=>{vr.stopPropagation(),M("printers:ams_rfid")&&($t.mutate({amsId:vt.id,slotId:Gt}),Gn(null))},disabled:_i||!M("printers:ams_rfid"),title:M("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Ur,{className:`w-3 h-3 ${_i?"animate-spin":""}`}),b("printers.rfid.reread")]})}),Wr?a.jsx(WP,{data:Wr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Wr.trayUuid?c?.[Wr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Wr.trayUuid?vr=>{$({tagUid:Wr.tagUid||"",trayUuid:vr,printerId:t.id,amsId:vt.id,trayId:Gt})}:void 0},inventory:o?void 0:(()=>{const vr=d?.(t.id,vt.id,Gt);return{assignedSpool:vr?.spool?{id:vr.spool.id,material:vr.spool.material,brand:vr.spool.brand,color_name:vr.spool.color_name}:null,onAssignSpool:Wr.vendor!=="Bambu Lab"?()=>ce({printerId:t.id,amsId:vt.id,trayId:Gt,trayInfo:{type:Wr.profile,color:Wr.colorHex||"",location:`${ih(vt.id,vt.tray.length)} Slot ${Gt+1}`}}):void 0,onUnassignSpool:vr&&Wr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,Gt):void 0}})(),configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:Gt,trayCount:vt.tray.length,trayType:gn?.tray_type||void 0,trayColor:gn?.tray_color||void 0,traySubBrands:gn?.tray_sub_brands||void 0,trayInfoIdx:gn?.tray_info_idx||void 0,extruderId:Cn,caliIdx:gn?.cali_idx,savedPresetId:Vi?.preset_id})},children:co}):a.jsx(KP,{configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:Gt,trayCount:vt.tray.length,extruderId:Cn})},children:co})]},Gt)})})]},vt.id)})}),(Ot.length>0||ye.vt_tray.length>0)&&a.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[Ot.map(vt=>{const Cn=Oe[String(vt.id)],Zr=vt.id>=128?vt.id-128:vt.id,fr=Cn!==void 0?Cn:Zr,mi=fr===1,_a=fr===0,Gt=vt.tray[0],gn=Gt?.tray_type&&Gt.remain>=0,za=!Gt?.tray_type,Jr=vt.id*4+(Gt?.id??0),Ua=an===Jr,Nl=Gt?.tray_info_idx?Ue?.[Gt.tray_info_idx]:null,Sa=je?.[Jr],Vi=Gt?.tray_uuid?.toUpperCase(),Gi=Vi?c?.[Vi]:void 0,Li=ej(Gi),Or=Gt?.id??0,Cl=d?.(t.id,vt.id,Or),Ba=(()=>{const Yn=Cl?.spool;return Yn&&Yn.label_weight>0&&Yn.weight_used>0?Math.round(Math.max(0,Yn.label_weight-Yn.weight_used)/Yn.label_weight*100):null})(),wi=gn&&Gt.remain>0?Gt.remain:Li??Ba??(gn?Gt.remain:null),ic=gn&&Gt.remain===0&&(Li!==null||Ba!==null)?Li!==null?"spoolman":"inventory":"ams",Wr=Gt?.tray_type?{vendor:tj(Gt)?"Bambu Lab":"Generic",profile:Nl?.name||Sa?.preset_name||Gt.tray_sub_brands||Gt.tray_type,colorName:XP(Gt.tray_id_name)||YP(Gt.tray_color),colorHex:Gt.tray_color||null,kFactor:QP(Gt.k),fillLevel:wi,trayUuid:Gt.tray_uuid||null,tagUid:Gt.tag_uid||null,fillSource:ic}:null,_i=Gt?.id??0,co=xe?.amsId===vt.id&&xe?.slotId===_i,vr=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${za?"opacity-50":""} ${Ua?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:Gt?.tray_color?`#${Gt.tray_color}`:Gt?.tray_type?"#333":"transparent",borderColor:za?"#666":"rgba(255,255,255,0.1)",borderStyle:za?"dashed":"solid"}}),a.jsx("div",{className:"text-[9px] text-white font-bold truncate",children:Gt?.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:wi!==null&&wi>=0?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${wi}%`,backgroundColor:JP(wi)}}):Gt?.tray_type?a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"}):null})]});return a.jsxs("div",{className:"p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30",children:[a.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[a.jsx("span",{className:"text-[10px] text-white font-medium",children:ih(vt.id,vt.tray.length)}),zn&&(mi||_a)&&a.jsx(J7,{side:mi?"L":"R"})]}),a.jsxs("div",{className:"flex gap-1.5",children:[a.jsxs("div",{className:"relative group flex-1",children:[co&&a.jsx("div",{className:"absolute inset-0 bg-bambu-dark-tertiary/80 rounded flex items-center justify-center z-20",children:a.jsx(Ur,{className:"w-4 h-4 text-bambu-green animate-spin"})}),ye?.state!=="RUNNING"&&a.jsx("button",{onClick:Yn=>{Yn.stopPropagation(),Gn(_n?.amsId===vt.id&&_n?.slotId===_i?null:{amsId:vt.id,slotId:_i})},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:b("printers.slotOptions"),children:a.jsx(Th,{className:"w-2.5 h-2.5 text-bambu-gray"})}),ye?.state!=="RUNNING"&&_n?.amsId===vt.id&&_n?.slotId===_i&&a.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:a.jsxs("button",{className:`w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 ${M("printers:ams_rfid")?"text-white hover:bg-bambu-dark-tertiary":"text-bambu-gray/50 cursor-not-allowed"}`,onClick:Yn=>{Yn.stopPropagation(),M("printers:ams_rfid")&&($t.mutate({amsId:vt.id,slotId:_i}),Gn(null))},disabled:co||!M("printers:ams_rfid"),title:M("printers:ams_rfid")?void 0:b("printers.permission.noAmsRfid"),children:[a.jsx(Ur,{className:`w-3 h-3 ${co?"animate-spin":""}`}),b("printers.rfid.reread")]})}),Wr?a.jsx(WP,{data:Wr,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Wr.trayUuid?c?.[Wr.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Wr.trayUuid?Yn=>{$({tagUid:Wr.tagUid||"",trayUuid:Yn,printerId:t.id,amsId:vt.id,trayId:_i})}:void 0},inventory:o?void 0:(()=>{const Yn=d?.(t.id,vt.id,_i);return{assignedSpool:Yn?.spool?{id:Yn.spool.id,material:Yn.spool.material,brand:Yn.spool.brand,color_name:Yn.spool.color_name}:null,onAssignSpool:Wr.vendor!=="Bambu Lab"?()=>ce({printerId:t.id,amsId:vt.id,trayId:_i,trayInfo:{type:Wr.profile,color:Wr.colorHex||"",location:ih(vt.id,vt.tray.length)}}):void 0,onUnassignSpool:Yn&&Wr.vendor!=="Bambu Lab"?()=>h?.(t.id,vt.id,_i):void 0}})(),configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:_i,trayCount:vt.tray.length,trayType:Gt?.tray_type||void 0,trayColor:Gt?.tray_color||void 0,traySubBrands:Gt?.tray_sub_brands||void 0,trayInfoIdx:Gt?.tray_info_idx||void 0,extruderId:Cn,caliIdx:Gt?.cali_idx,savedPresetId:Sa?.preset_id})},children:vr}):a.jsx(KP,{configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:vt.id,trayId:_i,trayCount:vt.tray.length,extruderId:Cn})},children:vr})]}),(vt.humidity!=null||vt.temp!=null)&&a.jsxs("div",{className:"flex flex-col justify-center gap-1 shrink-0",children:[vt.temp!=null&&a.jsx(n9,{temp:vt.temp,goodThreshold:s?.tempGood,fairThreshold:s?.tempFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"temperature"}),compact:!0}),vt.humidity!=null&&a.jsx(t9,{humidity:vt.humidity,goodThreshold:s?.humidityGood,fairThreshold:s?.humidityFair,onClick:()=>J({amsId:vt.id,amsLabel:ih(vt.id,vt.tray.length),mode:"humidity"}),compact:!0})]})]})]},vt.id)}),ye.vt_tray.length>0&&a.jsxs("div",{className:`p-2.5 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary/30 ${ye.vt_tray.length===1?"max-w-[50%]":""}`,children:[a.jsx("div",{className:"flex items-center gap-1 mb-2",children:a.jsx("span",{className:"text-[10px] text-white font-medium",children:b("printers.external")})}),a.jsx("div",{className:`grid ${ye.vt_tray.length>1?"grid-cols-2":"grid-cols-1"} gap-1.5`,children:[...ye.vt_tray].sort((vt,Cn)=>(vt.id??254)-(Cn.id??254)).map(vt=>{const Cn=vt.id??254,Zr=an===Cn,fr=Cn-254,mi=zn?b(Cn===254?"printers.extL":"printers.extR"):"",_a=vt.tray_info_idx?Ue?.[vt.tray_info_idx]:null,Gt=je?.[1020+fr],gn=vt.tray_uuid?.toUpperCase(),za=gn?c?.[gn]:void 0,Jr=ej(za),Ua=d?.(t.id,255,fr),Nl=(()=>{const Or=Ua?.spool;return Or&&Or.label_weight>0&&Or.weight_used>0?Math.round(Math.max(0,Or.label_weight-Or.weight_used)/Or.label_weight*100):null})(),Sa=Jr??Nl??null,Vi={vendor:tj(vt)?"Bambu Lab":"Generic",profile:_a?.name||Gt?.preset_name||vt.tray_sub_brands||vt.tray_type||"Unknown",colorName:XP(vt.tray_id_name)||YP(vt.tray_color),colorHex:vt.tray_color||null,kFactor:QP(vt.k),fillLevel:Sa,trayUuid:vt.tray_uuid||null,tagUid:vt.tag_uid||null,fillSource:Jr!==null?"spoolman":Nl!==null?"inventory":void 0},Gi=!vt.tray_type,Li=a.jsxs("div",{className:`bg-bambu-dark-tertiary rounded p-1 text-center ${Gi?"opacity-50":""} ${Zr?"ring-2 ring-bambu-green ring-offset-1 ring-offset-bambu-dark":""}`,children:[a.jsx("div",{className:"w-3.5 h-3.5 rounded-full mx-auto mb-0.5 border-2",style:{backgroundColor:vt.tray_color?`#${vt.tray_color}`:vt.tray_type?"#333":"transparent",borderColor:Gi?"#666":"rgba(255,255,255,0.1)",borderStyle:Gi?"dashed":"solid"}}),a.jsx("div",{className:`text-[9px] font-bold truncate ${Gi?"text-white/40":"text-white"}`,children:vt.tray_type||"—"}),a.jsx("div",{className:"mt-1 h-1.5 bg-black/30 rounded-full overflow-hidden",children:Sa!==null&&Sa>=0&&!Gi?a.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Sa}%`,backgroundColor:JP(Sa)}}):Gi?null:a.jsx("div",{className:"h-full w-full rounded-full bg-white/50 dark:bg-gray-500/40"})}),mi&&a.jsx("div",{className:"text-[7px] text-white/40 mt-0.5 truncate",children:mi})]});return a.jsx("div",{className:"relative group",children:Gi?a.jsx(KP,{configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:255,trayId:fr,trayCount:1,extruderId:zn?Cn===254?1:0:void 0})},children:Li}):a.jsx(WP,{data:Vi,spoolman:{enabled:o,hasUnlinkedSpools:l,linkedSpoolId:Vi.trayUuid?c?.[Vi.trayUuid.toUpperCase()]?.id:void 0,spoolmanUrl:u,onLinkSpool:o&&Vi.trayUuid?Or=>{$({tagUid:Vi.tagUid||"",trayUuid:Or,printerId:t.id,amsId:255,trayId:fr})}:void 0},inventory:o?void 0:(()=>{const Or=d?.(t.id,255,fr);return{assignedSpool:Or?.spool?{id:Or.spool.id,material:Or.spool.material,brand:Or.spool.brand,color_name:Or.spool.color_name}:null,onAssignSpool:()=>ce({printerId:t.id,amsId:255,trayId:fr,trayInfo:{type:Vi.profile,color:Vi.colorHex||"",location:mi||b("printers.external")}}),onUnassignSpool:Or?()=>h?.(t.id,255,fr):void 0}})(),configureSlot:{enabled:M("printers:control"),onConfigure:()=>ie({amsId:255,trayId:fr,trayCount:1,trayType:vt.tray_type||void 0,trayColor:vt.tray_color||void 0,traySubBrands:vt.tray_sub_brands||void 0,trayInfoIdx:vt.tray_info_idx||void 0,extruderId:zn?Cn===254?1:0:void 0,caliIdx:vt.cali_idx,savedPresetId:Gt?.preset_id})},children:Li})},Cn)})})]})]})]})]})})()]}),Pt&&r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx(qh,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"text-sm text-white truncate",children:Pt.name}),gt&&a.jsxs("span",{className:`text-xs px-1.5 py-0.5 rounded flex-shrink-0 ${gt.state==="ON"?"bg-bambu-green/20 text-bambu-green":gt.state==="OFF"?"bg-red-500/20 text-red-400":"bg-bambu-gray/20 text-bambu-gray"}`,children:[gt.state||"?",gt.state==="ON"&>.energy?.power!=null&&a.jsxs("span",{className:"text-yellow-400 ml-1.5",children:["· ",gt.energy.power,"W"]})]})]}),a.jsx("div",{className:"flex-1"}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("button",{onClick:()=>K(!0),disabled:De.isPending||gt?.state==="ON"||!M("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${M("smart_plugs:control")?gt?.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:M("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(fd,{className:"w-3 h-3"}),"On"]}),a.jsxs("button",{onClick:()=>ae(!0),disabled:De.isPending||gt?.state==="OFF"||!M("smart_plugs:control"),className:`px-2 py-1 text-xs rounded transition-colors flex items-center gap-1 ${M("smart_plugs:control")?gt?.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:M("smart_plugs:control")?void 0:b("printers.permission.noSmartPlugControl"),children:[a.jsx(nk,{className:"w-3 h-3"}),"Off"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[a.jsx("span",{className:`text-xs hidden sm:inline ${Pt.auto_off_executed?"text-bambu-green":"text-bambu-gray"}`,children:Pt.auto_off_executed?"Auto-off done":"Auto-off"}),a.jsx("button",{onClick:()=>nt.mutate(!Pt.auto_off),disabled:nt.isPending||Pt.auto_off_executed||!M("smart_plugs:control"),title:M("smart_plugs:control")?Pt.auto_off_executed?b("printers.autoOffExecuted"):b("printers.autoOffAfterPrint"):b("printers.permission.noSmartPlugControl"),className:`relative w-9 h-5 rounded-full transition-colors flex-shrink-0 ${M("smart_plugs:control")?Pt.auto_off_executed?"bg-bambu-green/50 cursor-not-allowed":Pt.auto_off?"bg-bambu-green":"bg-bambu-dark-tertiary":"bg-bambu-dark-tertiary/50 cursor-not-allowed"}`,children:a.jsx("span",{className:`absolute top-[2px] left-[2px] w-4 h-4 bg-white rounded-full transition-transform ${Pt.auto_off||Pt.auto_off_executed?"translate-x-4":"translate-x-0"}`})})]})]}),Ie&&Ie.length>0&&a.jsxs("div",{className:"flex items-center gap-2 mt-2 pt-2 border-t border-bambu-dark-tertiary/50",children:[a.jsx(dv,{className:"w-3.5 h-3.5 text-blue-400 flex-shrink-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"HA:"}),a.jsx("div",{className:"flex flex-wrap gap-1",children:Ie.map(bt=>a.jsxs("button",{onClick:()=>dt.mutate(bt.id),disabled:dt.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:[a.jsx(jo,{className:"w-2.5 h-2.5"}),bt.name]},bt.id))})]})]}),r==="expanded"&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[a.jsxs("div",{className:"text-xs text-bambu-gray",children:[a.jsx("p",{children:t.ip_address}),a.jsx("p",{className:"truncate",children:t.serial_number})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>pe.mutate(!ye?.chamber_light),disabled:!ye?.connected||pe.isPending||!M("printers:control"),title:M("printers:control")?ye?.chamber_light?b("printers.chamberLightOff"):b("printers.chamberLightOn"):b("printers.permission.noControl"),className:ye?.chamber_light?"bg-yellow-500/20 hover:bg-yellow-500/30 border-yellow-500/30":"",children:a.jsx(hL,{on:ye?.chamber_light??!1,className:"w-4 h-4"})}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>{if(p==="embedded"&&x)x(t.id,t.name);else{const bt=localStorage.getItem("cameraWindowState"),Ot=bt?JSON.parse(bt):{width:640,height:400},zn=[`width=${Ot.width}`,`height=${Ot.height}`,Ot.left!==void 0?`left=${Ot.left}`:"",Ot.top!==void 0?`top=${Ot.top}`:"","menubar=no,toolbar=no,location=no,status=no,noopener"].filter(Boolean).join(",");window.open(`/camera/${t.id}`,`camera-${t.id}`,zn)}},disabled:!ye?.connected,title:b(p==="embedded"?"printers.openCameraOverlay":"printers.openCameraWindow"),children:a.jsx(RF,{className:"w-4 h-4"})}),a.jsxs("div",{className:`inline-flex rounded-md ${t.plate_detection_enabled?"ring-1 ring-green-500":""}`,children:[a.jsx(Te,{variant:"secondary",size:"sm",onClick:Tn,disabled:!ye?.connected||ze.isPending||!M("printers:update"),title:M("printers:update")?t.plate_detection_enabled?b("printers.plateDetection.enabledClick"):b("printers.plateDetection.disabledClick"):b("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:ze.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(T1,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:bn,disabled:!ye?.connected||z||!M("printers:update"),title:M("printers:update")?b("printers.plateDetection.manageCalibration"):b("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:z?a.jsx(it,{className:"w-3 h-3 animate-spin"}):a.jsx(Jn,{className:"w-3 h-3"})})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>D(!0),disabled:!M("printers:files"),title:M("printers:files")?b("printers.browseFiles"):b("printers.permission.noFiles"),children:[a.jsx($b,{className:"w-4 h-4"}),"Files"]})]})]})]}),B&&a.jsx(qMe,{printerId:t.id,printerName:t.name,onClose:()=>D(!1)}),H&&a.jsx(ZMe,{printerId:t.id,printerName:t.name,onClose:()=>G(!1)}),ge&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Vt(),children:a.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:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[ge.needs_calibration?a.jsx(T1,{className:"w-5 h-5 text-blue-500"}):ge.is_empty?a.jsx(gr,{className:"w-5 h-5 text-green-500"}):a.jsx(ha,{className:"w-5 h-5 text-yellow-500"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Build Plate Check"}),ge.reference_count!==void 0&&ge.max_references&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary px-2 py-1 rounded",children:[ge.reference_count,"/",ge.max_references," refs"]})]}),a.jsx("button",{onClick:()=>Vt(),className:"p-1 text-bambu-gray hover:text-white rounded transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[ge.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/20 border border-blue-500/50",children:[a.jsx("p",{className:"font-medium text-blue-400",children:b("printers.plateDetection.calibrationRequired")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationInstructions")}})]}),a.jsxs("div",{className:"text-sm text-bambu-gray space-y-2",children:[a.jsx("p",{children:b("printers.plateDetection.calibrationDescription")}),a.jsx("p",{dangerouslySetInnerHTML:{__html:b("printers.plateDetection.calibrationTip")}})]})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`p-3 rounded-lg ${ge.is_empty?"bg-green-500/20 border border-green-500/50":"bg-yellow-500/20 border border-yellow-500/50"}`,children:[a.jsx("p",{className:`font-medium ${ge.is_empty?"text-green-400":"text-yellow-400"}`,children:ge.is_empty?b("printers.plateDetection.plateEmpty"):b("printers.plateDetection.objectsDetected")}),a.jsxs("p",{className:"text-sm text-bambu-gray mt-1",children:[b("printers.plateDetection.confidence"),": ",Math.round(ge.confidence*100),"% | ",b("printers.plateDetection.difference"),": ",ge.difference_percent.toFixed(1),"%"]})]}),ge.debug_image_url&&a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:b("printers.plateDetection.analysisPreview")}),a.jsx("img",{src:ge.debug_image_url,alt:b("printers.plateDetection.analysisPreview"),className:"w-full rounded-lg border border-bambu-dark-tertiary"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:b("printers.plateDetection.analysisLegend")})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:ge.message})]}),Dt&&Dt.references.length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:b("printers.plateDetection.savedReferences",{count:Dt.references.length,max:Dt.max_references})}),a.jsx("div",{className:"grid grid-cols-5 gap-2",children:Dt.references.map(bt=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:se.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"}),a.jsx("button",{onClick:()=>Gr(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:b("printers.plateDetection.deleteReference"),children:a.jsx(Rt,{className:"w-3 h-3 text-white"})}),Jt?.index===bt.index?a.jsx("input",{type:"text",value:Jt.label,onChange:Ot=>Kt({...Jt,label:Ot.target.value}),onBlur:()=>pn(bt.index,Jt.label),onKeyDown:Ot=>{Ot.key==="Enter"&&pn(bt.index,Jt.label),Ot.key==="Escape"&&Kt(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:b("printers.plateDetection.labelPlaceholder")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1 truncate cursor-pointer hover:text-white",onClick:()=>Kt({index:bt.index,label:bt.label}),title:bt.label?b("printers.plateDetection.clickToEdit",{label:bt.label}):b("printers.plateDetection.clickToAddLabel"),children:bt.label||a.jsx("span",{className:"italic opacity-50",children:b("printers.noLabel")})}),a.jsx("p",{className:"text-[10px] text-bambu-gray/60",children:bt.timestamp?new Date(bt.timestamp).toLocaleDateString():""})]},bt.index))})]}),!ge.needs_calibration&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("p",{className:"text-sm font-medium text-white",children:b("printers.roi.title")}),_e?a.jsxs("div",{className:"flex gap-1",children:[a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>be(null),disabled:He,children:b("common.cancel")}),a.jsx(Te,{size:"sm",onClick:qr,disabled:He,children:He?a.jsx(it,{className:"w-3 h-3 animate-spin"}):b("common.save")})]}):a.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>be(ge.roi||{x:.15,y:.35,w:.7,h:.55}),children:[a.jsx($i,{className:"w-3 h-3 mr-1"}),b("common.edit")]})]}),_e?a.jsxs("div",{className:"space-y-3 bg-bambu-dark-tertiary/50 p-3 rounded-lg",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.xStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_e.x,onChange:bt=>be({..._e,x:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.x*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.roi.yStart")}),a.jsx("input",{type:"range",min:"0",max:"0.9",step:"0.01",value:_e.y,onChange:bt=>be({..._e,y:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.y*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.width")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_e.w,onChange:bt=>be({..._e,w:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.w*100),"%"]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"text-xs text-bambu-gray",children:b("printers.height")}),a.jsx("input",{type:"range",min:"0.1",max:"1",step:"0.01",value:_e.h,onChange:bt=>be({..._e,h:parseFloat(bt.target.value)}),className:"w-full h-1.5 bg-bambu-dark-tertiary rounded-lg cursor-pointer accent-green-500"}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[Math.round(_e.h*100),"%"]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:b("printers.roi.instruction")})]}):a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Current: X=",Math.round((ge.roi?.x||.15)*100),"%, Y=",Math.round((ge.roi?.y||.35)*100),"%, W=",Math.round((ge.roi?.w||.7)*100),"%, H=",Math.round((ge.roi?.h||.55)*100),"%"]})]})]}),a.jsx("div",{className:"flex justify-end gap-2 p-4 border-t border-bambu-dark-tertiary",children:ge.needs_calibration?a.jsxs(a.Fragment,{children:[a.jsx(Te,{variant:"ghost",onClick:()=>Vt(),children:b("common.cancel")}),a.jsx(Te,{onClick:()=>fn(),disabled:W,children:W?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 mr-2 animate-spin"}),"Calibrating..."]}):"Calibrate Empty Plate"})]}):a.jsxs(a.Fragment,{children:[a.jsx(Te,{variant:"ghost",onClick:()=>fn(),disabled:W,children:W?"Adding...":`Add Reference (${Dt?.references.length||0}/${Dt?.max_references||5})`}),a.jsx(Te,{onClick:()=>Vt(),children:"Close"})]})})]})}),I&&Pt&&a.jsx(Pn,{title:b("printers.confirm.powerOnTitle"),message:b("printers.confirm.powerOnMessage",{name:t.name}),confirmText:b("printers.confirm.powerOnButton"),variant:"default",onConfirm:()=>{De.mutate("on"),K(!1)},onCancel:()=>K(!1)}),Q&&Pt&&a.jsx(Pn,{title:b("printers.confirm.powerOffTitle"),message:ye?.state==="RUNNING"?b("printers.confirm.powerOffWarning",{name:t.name}):b("printers.confirm.powerOffMessage",{name:t.name}),confirmText:b("printers.confirm.powerOffButton"),variant:"danger",onConfirm:()=>{De.mutate("off"),ae(!1)},onCancel:()=>ae(!1)}),ne&&a.jsx(Pn,{title:b("printers.confirm.stopTitle"),message:b("printers.confirm.stopMessage",{name:t.name}),confirmText:b("printers.confirm.stopButton"),variant:"danger",onConfirm:()=>{pt.mutate(),ee(!1)},onCancel:()=>ee(!1)}),ve&&a.jsx(Pn,{title:b("printers.confirm.pauseTitle"),message:b("printers.confirm.pauseMessage",{name:t.name}),confirmText:b("printers.confirm.pauseButton"),variant:"default",onConfirm:()=>{lt.mutate(),fe(!1)},onCancel:()=>fe(!1)}),de&&a.jsx(Pn,{title:b("printers.confirm.resumeTitle"),message:b("printers.confirm.resumeMessage",{name:t.name}),confirmText:b("printers.confirm.resumeButton"),variant:"default",onConfirm:()=>{Ft.mutate(),Re(!1)},onCancel:()=>Re(!1)}),a.jsx(mL,{printerId:t.id,isOpen:ue,onClose:()=>le(!1)}),V&&a.jsx(nAe,{printerName:t.name,errors:ye?.hms_errors||[],onClose:()=>Y(!1)}),Ne&&a.jsx(pHe,{isOpen:!!Ne,onClose:()=>J(null),printerId:t.id,printerName:t.name,amsId:Ne.amsId,amsLabel:Ne.amsLabel,initialMode:Ne.mode,thresholds:s}),Le&&a.jsx(gHe,{isOpen:!!Le,onClose:()=>$(null),tagUid:Le.tagUid,trayUuid:Le.trayUuid,printerId:Le.printerId,amsId:Le.amsId,trayId:Le.trayId}),X&&a.jsx(bHe,{isOpen:!!X,onClose:()=>ce(null),printerId:X.printerId,amsId:X.amsId,trayId:X.trayId,trayInfo:X.trayInfo}),q&&a.jsx(kHe,{isOpen:!!q,onClose:()=>ie(null),printerId:t.id,slotInfo:q,printerModel:_R(t.model)||void 0,onSuccess:()=>{y.invalidateQueries({queryKey:["slotPresets",t.id]}),y.invalidateQueries({queryKey:["printerStatus",t.id]})}}),U&&a.jsx($He,{printer:t,onClose:()=>L(!1)}),te&&we&&a.jsx(HHe,{printer:t,firmwareInfo:we,onClose:()=>he(!1)}),_n&&a.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>Gn(null)})]})}function BHe({onClose:t,onAdd:e,existingSerials:n}){const{t:r}=Ut(),[i,s]=w.useState({name:"",serial_number:"",ip_address:"",access_code:"",model:"",location:"",auto_archive:!0}),[o,l]=w.useState(!1),[c,u]=w.useState([]),[d,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(!1),[b,y]=w.useState([]),[S,N]=w.useState(""),[M,k]=w.useState({scanned:0,total:0});w.useEffect(()=>{uc.getInfo().then(E=>{v(E.is_docker),E.subnets.length>0&&(y(E.subnets),N(E.subnets[0]))}).catch(()=>{})},[]);const T=c.filter(E=>!n.includes(E.serial)),C=async()=>{h(""),u([]),l(!0),p(!1),k({scanned:0,total:0});try{if(x){await uc.startSubnetScan(S);const E=setInterval(async()=>{try{const P=await uc.getScanStatus();k({scanned:P.scanned,total:P.total});const U=await uc.getDiscoveredPrinters();u(U),P.running||(clearInterval(E),l(!1),p(!0))}catch(P){console.error("Failed to get scan status:",P)}},500)}else{await uc.startDiscovery(10);const E=setInterval(async()=>{try{const P=await uc.getDiscoveredPrinters();u(P)}catch(P){console.error("Failed to get discovered printers:",P)}},1e3);setTimeout(async()=>{clearInterval(E);try{await uc.stopDiscovery()}catch{}l(!1),p(!0);try{const P=await uc.getDiscoveredPrinters();u(P)}catch(P){console.error("Failed to get final discovered printers:",P)}},1e4)}}catch(E){console.error("Failed to start discovery:",E),h(E instanceof Error?E.message:r("printers.discovery.failedToStart")),l(!1),p(!0)}},j=E=>{const P=E.serial.startsWith("unknown-")?"":E.serial;s({...i,name:E.name||"",serial_number:P,ip_address:E.ip_address,model:_R(E.model)}),u([])};return w.useEffect(()=>()=>{uc.stopDiscovery().catch(()=>{}),uc.stopSubnetScan().catch(()=>{})},[]),w.useEffect(()=>{const E=P=>{P.key==="Escape"&&t()};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[t]),a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:t,children:a.jsx(_t,{className:"w-full max-w-md",onClick:E=>E.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:r("printers.addPrinter")}),a.jsxs("div",{className:"mb-4 pb-4 border-b border-bambu-dark-tertiary",children:[x&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.discovery.subnetToScan")}),b.length>0?a.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:S,onChange:E=>N(E.target.value),disabled:o,children:b.map(E=>a.jsx("option",{value:E,children:E},E))}):a.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:S,onChange:E=>N(E.target.value),placeholder:"192.168.1.0/24",disabled:o}),a.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:r("printers.discovery.dockerNote")})]}),a.jsx(Te,{type:"button",variant:"secondary",onClick:C,disabled:o,className:"w-full",children:o?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),x&&M.total>0?r("printers.discovery.scanProgress",{scanned:M.scanned,total:M.total}):r("printers.discovery.scanning")]}):a.jsxs(a.Fragment,{children:[a.jsx(Br,{className:"w-4 h-4"}),r(x?"printers.discovery.scanSubnet":"printers.discovery.discoverNetwork")]})}),d&&a.jsx("div",{className:"mt-2 text-sm text-red-400",children:d}),T.length>0&&a.jsx("div",{className:"mt-3 space-y-2 max-h-40 overflow-y-auto",children:T.map(E=>a.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:()=>j(E),children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"font-medium text-white text-sm truncate",children:E.name||E.serial}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[_R(E.model)||r("printers.discovery.unknown")," • ",E.ip_address,E.serial.startsWith("unknown-")&&a.jsxs("span",{className:"text-yellow-500",children:[" • ",r("printers.discovery.serialRequired")]})]})]}),a.jsx(Jn,{className:"w-4 h-4 text-bambu-gray -rotate-90 flex-shrink-0 ml-2"})]},E.serial))}),o&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.scanningSubnet":"printers.discovery.scanningNetwork")}),f&&!o&&c.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r(x?"printers.discovery.noPrintersFoundSubnet":"printers.discovery.noPrintersFoundNetwork")}),f&&!o&&c.length>0&&T.length===0&&a.jsx("p",{className:"mt-2 text-sm text-bambu-gray text-center",children:r("printers.discovery.allConfigured")})]}),a.jsxs("form",{onSubmit:E=>{E.preventDefault(),e(i)},className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.name")}),a.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:i.name,onChange:E=>s({...i,name:E.target.value}),placeholder:r("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.ipAddress")}),a.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:i.ip_address,onChange:E=>s({...i,ip_address:E.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.serialNumber")}),a.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:i.serial_number,onChange:E=>s({...i,serial_number:E.target.value}),placeholder:"01P00A000000000"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.accessCode")}),a.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:i.access_code,onChange:E=>s({...i,access_code:E.target.value}),placeholder:r("printers.modal.fromPrinterSettings")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.modelOptional")}),a.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:i.model||"",onChange:E=>s({...i,model:E.target.value}),children:[a.jsx("option",{value:"",children:r("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("printers.modal.locationGroup")}),a.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:i.location||"",onChange:E=>s({...i,location:E.target.value}),placeholder:r("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"auto_archive",checked:i.auto_archive,onChange:E=>s({...i,auto_archive:E.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"auto_archive",className:"text-sm text-bambu-gray",children:r("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:t,className:"flex-1",children:r("common.cancel")}),a.jsx(Te,{type:"submit",className:"flex-1",children:r("printers.addPrinter")})]})]})]})})})}function HHe({printer:t,firmwareInfo:e,onClose:n}){const{t:r}=Ut(),i=Zt(),{showToast:s}=hn(),{hasPermission:o}=Fr(),l=o("firmware:update"),[c,u]=w.useState(null),[d,h]=w.useState(!1),[f,p]=w.useState(null),{data:x,isLoading:v}=et({queryKey:["firmwarePrepare",t.id],queryFn:()=>XS.prepareUpload(t.id),staleTime:3e4,enabled:e.update_available&&l}),b=ot({mutationFn:()=>XS.startUpload(t.id),onSuccess:()=>{h(!0);const S=setInterval(async()=>{try{const N=await XS.getUploadStatus(t.id);u(N),(N.status==="complete"||N.status==="error")&&(clearInterval(S),p(null),h(!1),N.status==="complete"&&(s(r("printers.firmwareModal.uploadedToast"),"success"),i.invalidateQueries({queryKey:["firmwareUpdate",t.id]})))}catch{}},2e3);p(S)},onError:S=>{s(r("printers.firmwareModal.uploadFailed",{error:S.message}),"error"),h(!1)}});w.useEffect(()=>()=>{f&&clearInterval(f)},[f]);const y=()=>{u(null),b.mutate()};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsx(_t,{className:"w-full max-w-md mx-4",children:a.jsxs(Nt,{children:[a.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[a.jsx("div",{className:`p-2 rounded-full ${e.update_available?"bg-orange-500/20":"bg-status-ok/20"}`,children:e.update_available?a.jsx(ui,{className:"w-5 h-5 text-orange-400"}):a.jsx(gr,{className:"w-5 h-5 text-status-ok"})}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:e.update_available?r("printers.firmwareModal.title"):r("printers.firmwareModal.titleUpToDate")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t.name})]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3 mb-4",children:[a.jsxs("div",{className:"flex justify-between items-center text-sm",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.currentVersion")}),a.jsx("span",{className:`font-mono ${e.update_available?"text-white":"text-status-ok"}`,children:e.current_version||r("common.unknown")})]}),e.update_available&&a.jsxs("div",{className:"flex justify-between items-center text-sm mt-1",children:[a.jsx("span",{className:"text-bambu-gray",children:r("printers.firmwareModal.latestVersion")}),a.jsx("span",{className:"text-orange-400 font-mono",children:e.latest_version})]}),e.release_notes&&a.jsxs("details",{className:"mt-3 text-sm",open:!e.update_available,children:[a.jsx("summary",{className:`cursor-pointer hover:underline ${e.update_available?"text-orange-400":"text-status-ok"}`,children:r("printers.firmwareModal.releaseNotes")}),a.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?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm mb-4",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),r("printers.firmwareModal.checkingPrereqs")]}):x&&!d&&!c?a.jsx("div",{className:"mb-4",children:x.can_proceed?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green text-sm",children:[a.jsx(Zi,{className:"w-4 h-4"}),r("printers.firmwareModal.sdCardReady")]}):a.jsx("div",{className:"space-y-1",children:x.errors.map((S,N)=>a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm",children:[a.jsx(Bi,{className:"w-4 h-4 flex-shrink-0"}),S]},N))})}):null:null,(d||c)&&c&&a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-bambu-gray capitalize",children:c.status}),a.jsxs("span",{className:"text-white",children:[c.progress,"%"]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.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}%`}})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:c.message}),c.error&&a.jsx("p",{className:"text-xs text-red-400 mt-1",children:c.error})]}),c?.status==="complete"&&a.jsxs("div",{className:"bg-bambu-green/10 border border-bambu-green/30 rounded-lg p-3 mb-4",children:[a.jsx("p",{className:"text-sm text-bambu-green font-medium mb-2",children:r("printers.firmwareModal.uploadedSuccess")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("printers.firmwareModal.applyInstructions")}),a.jsxs("ol",{className:"text-xs text-bambu-gray mt-1 list-decimal list-inside space-y-1",children:[a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step1")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step2")}}),a.jsx("li",{dangerouslySetInnerHTML:{__html:r("printers.firmwareModal.step3")}}),a.jsx("li",{children:r("printers.firmwareModal.step4")})]})]}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Te,{variant:"secondary",onClick:n,children:c?.status==="complete"?r("printers.firmwareModal.done"):r("common.cancel")}),x?.can_proceed&&!d&&c?.status!=="complete"&&l&&a.jsx(Te,{onClick:y,disabled:b.isPending,children:b.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}),r("printers.firmwareModal.starting")]}):a.jsxs(a.Fragment,{children:[a.jsx(ui,{className:"w-4 h-4 mr-2"}),r("printers.firmwareModal.uploadFirmware")]})})]})]})})})}function $He({printer:t,onClose:e}){const{t:n}=Ut(),r=Zt(),{showToast:i}=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=ot({mutationFn:u=>se.updatePrinter(t.id,u),onSuccess:()=>{r.invalidateQueries({queryKey:["printers"]}),r.invalidateQueries({queryKey:["printerStatus",t.id]}),e()},onError:u=>i(u.message||n("printers.toast.failedToUpdate"),"error")});w.useEffect(()=>{const u=d=>{d.key==="Escape"&&e()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[e]);const c=u=>{u.preventDefault();const d={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&&(d.access_code=s.access_code),l.mutate(d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:e,children:a.jsx(_t,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:a.jsxs(Nt,{children:[a.jsx("h2",{className:"text-xl font-semibold mb-4",children:n("printers.editPrinter")}),a.jsxs("form",{onSubmit:c,className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.name")}),a.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:u=>o({...s,name:u.target.value}),placeholder:n("printers.modal.myPrinter")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.ipAddress")}),a.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:u=>o({...s,ip_address:u.target.value}),placeholder:"192.168.1.100 or printer.local"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.serialNumber")}),a.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}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.serialCannotBeChanged")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.accessCode")}),a.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:u=>o({...s,access_code:u.target.value}),placeholder:n("printers.accessCodePlaceholder")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:n("printers.model")}),a.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:u=>o({...s,model:u.target.value}),children:[a.jsx("option",{value:"",children:n("printers.modal.selectModel")}),a.jsxs("optgroup",{label:"H2 Series",children:[a.jsx("option",{value:"H2C",children:"H2C"}),a.jsx("option",{value:"H2D",children:"H2D"}),a.jsx("option",{value:"H2D Pro",children:"H2D Pro"}),a.jsx("option",{value:"H2S",children:"H2S"})]}),a.jsxs("optgroup",{label:"X1 Series",children:[a.jsx("option",{value:"X1E",children:"X1E"}),a.jsx("option",{value:"X1C",children:"X1 Carbon"}),a.jsx("option",{value:"X1",children:"X1"})]}),a.jsxs("optgroup",{label:"P Series",children:[a.jsx("option",{value:"P2S",children:"P2S"}),a.jsx("option",{value:"P1S",children:"P1S"}),a.jsx("option",{value:"P1P",children:"P1P"})]}),a.jsxs("optgroup",{label:"A1 Series",children:[a.jsx("option",{value:"A1",children:"A1"}),a.jsx("option",{value:"A1 Mini",children:"A1 Mini"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Location / Group"}),a.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:u=>o({...s,location:u.target.value}),placeholder:n("printers.modal.locationPlaceholder")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n("printers.locationHelp")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"edit_auto_archive",checked:s.auto_archive,onChange:u=>o({...s,auto_archive:u.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"edit_auto_archive",className:"text-sm text-bambu-gray",children:n("printers.modal.autoArchiveLabel")})]}),a.jsxs("div",{className:"flex gap-3 pt-4",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:n("common.cancel")}),a.jsx(Te,{type:"submit",className:"flex-1",disabled:l.isPending,children:l.isPending?n("common.saving"):n("printers.modal.saveChanges")})]})]})]})})})}function VHe(t){const{data:e}=et({queryKey:["printerStatus",t],queryFn:()=>se.getPrinterStatus(t),refetchInterval:3e4});return!e?.connected}function GHe({printer:t,plug:e,onPowerOn:n,isPowering:r}){const i=VHe(t.id),{data:s}=et({queryKey:["smartPlugStatus",e.id],queryFn:()=>se.getSmartPlugStatus(e.id),refetchInterval:1e4});return i?a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-gray-100 dark:hover:bg-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-sm text-gray-900 dark:text-white truncate",children:t.name}),s&&a.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||"?"})]}),a.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:[a.jsx(fd,{className:"w-3 h-3"}),r?"...":"On"]})]}):null}function qHe(){const{t}=Ut(),[e,n]=w.useState(!1),[r,i]=w.useState(()=>localStorage.getItem("hideDisconnectedPrinters")==="true"),[s,o]=w.useState(!1),[l,c]=w.useState(null),[u,d]=w.useState(()=>localStorage.getItem("printerSortBy")||"name"),[h,f]=w.useState(()=>localStorage.getItem("printerSortAsc")!=="false"),[p,x]=w.useState(()=>{const le=localStorage.getItem("printerCardSize");return le?parseInt(le,10):2}),v=p===1?"compact":"expanded",b=Zt(),{showToast:y}=hn(),{hasPermission:S}=Fr(),[N,M]=w.useState(()=>{const le=localStorage.getItem("openEmbeddedCameras");if(le)try{const Ne=JSON.parse(le);return new Map(Ne.map(J=>[J.id,J]))}catch{return new Map}return new Map});w.useEffect(()=>{const le=Array.from(N.values());le.length>0?localStorage.setItem("openEmbeddedCameras",JSON.stringify(le)):localStorage.removeItem("openEmbeddedCameras")},[N]);const{data:k,isLoading:T}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:C}=et({queryKey:["settings"],queryFn:se.getSettings});w.useEffect(()=>{C?.camera_view_mode==="window"&&N.size>0&&M(new Map)},[C?.camera_view_mode,N.size]);const{data:j}=et({queryKey:["smart-plugs"],queryFn:se.getSmartPlugs}),{data:E}=et({queryKey:["maintenanceOverview"],queryFn:se.getMaintenanceOverview,staleTime:60*1e3}),{data:P}=et({queryKey:["spoolman-status"],queryFn:se.getSpoolmanStatus,staleTime:60*1e3}),U=P?.enabled&&P?.connected,{data:L}=et({queryKey:["unlinked-spools"],queryFn:se.getUnlinkedSpools,enabled:!!U,staleTime:30*1e3}),B=L&&L.length>0,{data:D}=et({queryKey:["linked-spools"],queryFn:se.getLinkedSpools,enabled:!!U,staleTime:30*1e3}),H=D?.linked,{data:G}=et({queryKey:["spool-assignments"],queryFn:()=>se.getAssignments(),staleTime:30*1e3}),I=ot({mutationFn:({printerId:le,amsId:Ne,trayId:J})=>se.unassignSpool(le,Ne,J),onSuccess:()=>{b.invalidateQueries({queryKey:["spool-assignments"]})}}),K=(le,Ne,J)=>G?.find(Le=>Le.printer_id===le&&Le.ams_id===Number(Ne)&&Le.tray_id===Number(J)),Q=E?.reduce((le,Ne)=>(le[Ne.printer_id]={due_count:Ne.due_count,warning_count:Ne.warning_count,total_print_hours:Ne.total_print_hours},le),{})||{},ae=j?.reduce((le,Ne)=>(Ne.printer_id&&(le[Ne.printer_id]=Ne),le),{})||{},V=ot({mutationFn:se.createPrinter,onSuccess:()=>{b.invalidateQueries({queryKey:["printers"]}),b.invalidateQueries({queryKey:["maintenanceOverview"]}),n(!1)},onError:le=>y(le.message||t("printers.toast.failedToAdd"),"error")}),Y=ot({mutationFn:le=>se.controlSmartPlug(le,"on"),onSuccess:()=>{b.invalidateQueries({queryKey:["smart-plugs"]}),c(null)},onError:()=>{c(null)}}),ne=()=>{const le=!r;i(le),localStorage.setItem("hideDisconnectedPrinters",String(le))},ee=le=>{d(le),localStorage.setItem("printerSortBy",le)},ve=()=>{const le=!h;f(le),localStorage.setItem("printerSortAsc",String(le))},fe=()=>{switch(p){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"}},de=["S","M","L","XL"],Re=w.useMemo(()=>{if(!k)return[];const le=[...k];switch(u){case"name":le.sort((Ne,J)=>Ne.name.localeCompare(J.name));break;case"model":le.sort((Ne,J)=>(Ne.model||"").localeCompare(J.model||""));break;case"location":le.sort((Ne,J)=>{const Le=Ne.location||"",$=J.location||"";return!Le&&$?1:Le&&!$?-1:Le.localeCompare($)||Ne.name.localeCompare(J.name)});break;case"status":le.sort((Ne,J)=>{const Le=b.getQueryData(["printerStatus",Ne.id]),$=b.getQueryData(["printerStatus",J.id]),X=ce=>ce?.connected?ce.state==="RUNNING"?0:1:2;return X(Le)-X($)});break}return h||le.reverse(),le},[k,u,h,b]),ue=w.useMemo(()=>{if(u!=="location")return null;const le={};return Re.forEach(Ne=>{const J=Ne.location||"Ungrouped";le[J]||(le[J]=[]),le[J].push(Ne)}),le},[u,Re]);return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("printers.title")}),a.jsx(UHe,{printers:k})]}),a.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsxs("select",{value:u,onChange:le=>ee(le.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:[a.jsx("option",{value:"name",children:t("printers.sort.name")}),a.jsx("option",{value:"status",children:t("printers.sort.status")}),a.jsx("option",{value:"model",children:t("printers.sort.model")}),a.jsx("option",{value:"location",children:t("printers.sort.location")})]}),a.jsx("button",{onClick:ve,className:"p-1.5 rounded-lg hover:bg-bambu-dark-tertiary transition-colors",title:t(h?"printers.sort.descending":"printers.sort.ascending"),children:h?a.jsx(jf,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(lb,{className:"w-4 h-4 text-bambu-gray"})})]}),a.jsx("div",{className:"flex items-center bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:de.map((le,Ne)=>{const J=Ne+1,Le=p===J;return a.jsx("button",{onClick:()=>{x(J),localStorage.setItem("printerCardSize",String(J))},className:`px-2 py-1.5 text-xs font-medium transition-colors ${Ne===0?"rounded-l-lg":""} ${Ne===de.length-1?"rounded-r-lg":""} ${Le?"bg-bambu-green text-white":"text-bambu-gray hover:bg-bambu-dark-tertiary hover:text-white"}`,title:t(le==="S"?"printers.cardSize.small":le==="M"?"printers.cardSize.medium":le==="L"?"printers.cardSize.large":"printers.cardSize.extraLarge"),children:le},le)})}),a.jsx("div",{className:"w-px h-6 bg-bambu-dark-tertiary"}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:r,onChange:ne,className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),t("printers.hideOffline")]}),r&&Object.keys(ae).length>0&&a.jsxs("div",{className:"relative",children:[a.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:[a.jsx(fd,{className:"w-4 h-4"}),t("printers.powerOn"),a.jsx(Jn,{className:`w-3 h-3 transition-transform ${s?"rotate-180":""}`})]}),s&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>o(!1)}),a.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:[a.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")}),k?.filter(le=>ae[le.id]).map(le=>a.jsx(GHe,{printer:le,plug:ae[le.id],onPowerOn:Ne=>{c(Ne),Y.mutate(Ne)},isPowering:l===ae[le.id]?.id},le.id)),k?.filter(le=>ae[le.id]).length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No printers with smart plugs"})]})]})]}),a.jsxs(Te,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})]}),T?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):k?.length===0?a.jsx(_t,{children:a.jsxs(Nt,{className:"text-center py-12",children:[a.jsx("p",{className:"text-bambu-gray mb-4",children:t("printers.noPrintersConfigured")}),a.jsxs(Te,{onClick:()=>n(!0),disabled:!S("printers:create"),title:S("printers:create")?void 0:t("printers.permission.noAdd"),children:[a.jsx(rr,{className:"w-4 h-4"}),t("printers.addPrinter")]})]})}):ue?a.jsx("div",{className:"space-y-6",children:Object.entries(ue).map(([le,Ne])=>a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-3 flex items-center gap-2",children:[a.jsx("span",{className:"w-2 h-2 rounded-full bg-bambu-green"}),le,a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ne.length,")"]})]}),a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${fe()}`,children:Ne.map(J=>a.jsx(i9,{printer:J,hideIfDisconnected:r,maintenanceInfo:Q[J.id],viewMode:v,cardSize:p,amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,spoolmanEnabled:U,hasUnlinkedSpools:B,linkedSpools:H,spoolmanUrl:P?.url,onGetAssignment:K,onUnassignSpool:(Le,$,X)=>I.mutate({printerId:Le,amsId:$,trayId:X}),timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Le,$)=>M(X=>new Map(X).set(Le,{id:Le,name:$})),checkPrinterFirmware:C?.check_printer_firmware!==!1},J.id))})]},le))}):a.jsx("div",{className:`grid gap-4 ${p>=3?"gap-6":""} ${fe()}`,children:Re.map(le=>a.jsx(i9,{printer:le,hideIfDisconnected:r,maintenanceInfo:Q[le.id],viewMode:v,cardSize:p,spoolmanEnabled:U,hasUnlinkedSpools:B,linkedSpools:H,spoolmanUrl:P?.url,onGetAssignment:K,onUnassignSpool:(Ne,J,Le)=>I.mutate({printerId:Ne,amsId:J,trayId:Le}),amsThresholds:C?{humidityGood:Number(C.ams_humidity_good)||40,humidityFair:Number(C.ams_humidity_fair)||60,tempGood:Number(C.ams_temp_good)||28,tempFair:Number(C.ams_temp_fair)||35}:void 0,timeFormat:C?.time_format||"system",cameraViewMode:C?.camera_view_mode||"window",onOpenEmbeddedCamera:(Ne,J)=>M(Le=>new Map(Le).set(Ne,{id:Ne,name:J})),checkPrinterFirmware:C?.check_printer_firmware!==!1},le.id))}),e&&a.jsx(BHe,{onClose:()=>n(!1),onAdd:le=>V.mutate(le),existingSerials:k?.map(le=>le.serial_number)||[]}),Array.from(N.values()).map((le,Ne)=>a.jsx(QMe,{printerId:le.id,printerName:le.name,viewerIndex:Ne,onClose:()=>M(J=>{const Le=new Map(J);return Le.delete(le.id),Le})},le.id))]})}function WHe(){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 Nc(t,e="bambu_studio"){let n;e==="orcaslicer"?n=`orcaslicer://open?file=${t}`:n=`${WHe()==="windows"?"bambustudio":"bambustudioopen"}://${encodeURIComponent(t)}`;const r=document.createElement("a");r.href=n,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r)}function x4({archiveId:t,libraryFileId:e,title:n,fileType:r,onClose:i}){const{t:s}=Ut(),{data:o}=et({queryKey:["settings"],queryFn:se.getSettings}),l=o?.preferred_slicer||"bambu_studio",c=e!=null,[u,d]=w.useState(null),[h,f]=w.useState(null),[p,x]=w.useState(!0),[v,b]=w.useState(null),[y,S]=w.useState(!1),[N,M]=w.useState(null),[k,T]=w.useState(0),[C,j]=w.useState(!1),[E,P]=w.useState(null),[U,L]=w.useState(!1),[B,D]=w.useState(!1),H=w.useRef(null),G=w.useRef(null),I=10,K=160,Q=240,ae=.35;w.useEffect(()=>{const ge=Z=>{Z.key==="Escape"&&i()};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[i]),w.useEffect(()=>{if(x(!0),c){const ge=(r||"").toLowerCase(),Z=ge==="3mf"||ge==="stl",z=ge==="gcode"||ge==="3mf";f({has_model:Z,has_gcode:z,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d(Z?"3d":z?"gcode":null),x(!1);return}if(!t){f(null),d(null),x(!1);return}se.getArchiveCapabilities(t).then(ge=>{f(ge),ge.has_model?d("3d"):ge.has_gcode&&d("gcode"),x(!1)}).catch(()=>{f({has_model:!0,has_gcode:!1,has_source:!1,build_volume:{x:256,y:256,z:256},filament_colors:[]}),d("3d"),x(!1)})},[t,r,c]),w.useEffect(()=>{if(S(!0),M(null),T(0),c){const ge=(r||"").toLowerCase();if(!e||ge!=="3mf"){b(null),S(!1);return}se.getLibraryFilePlates(e).then(Z=>b(Z)).catch(()=>b(null)).finally(()=>S(!1));return}if(!t){b(null),S(!1);return}se.getArchivePlates(t).then(ge=>b(ge)).catch(()=>b(null)).finally(()=>S(!1))},[t,r,c,e]);const V=w.useMemo(()=>v?.plates??[],[v]),Y=(v?.is_multi_plate??!1)&&V.length>1,ne=C&&Y,ee=N==null?null:V.find(ge=>ge.index===N)??null,ve=ge=>ge.object_count??ge.objects?.length??0,fe=V.reduce((ge,Z)=>ge+ve(Z),0),de=ee?ve(ee):fe,Re=ee?s("modelViewer.plateNumber",{number:ee.index}):s("modelViewer.allPlates"),ue=V.length>0,le=w.useRef(null),Ne=w.useRef(null),[J,Le]=w.useState(10),[$,X]=w.useState(3),ce=V.length>J,q=Math.max(1,Math.ceil(V.length/J)),ie=ce?V.slice(k*J,(k+1)*J):V;w.useEffect(()=>{if(!ne){Le(10),X(3);return}const ge=le.current,Z=Ne.current;if(!ge||!Z)return;let z=0;const F=()=>{const _e=Z.clientWidth,He=Math.floor(_e/210),Se=Math.max(3,Math.min(5,He||3));X(Ae=>Ae===Se?Ae:Se);const $e=window.getComputedStyle(ge),Qe=Number.parseFloat($e.rowGap||"0"),we=ge.querySelector("button")?.getBoundingClientRect().height??44,Ce=Z.clientHeight,je=Math.max(1,Math.floor((Ce+Qe)/(we+Qe)))*Se,Ve=Math.max(1,je-1);Le(Ae=>Ae===Ve?Ae:Ve)},W=()=>{z&&cancelAnimationFrame(z),z=requestAnimationFrame(F)};W();const me=new ResizeObserver(W);return me.observe(Z),me.observe(ge),()=>{z&&cancelAnimationFrame(z),me.disconnect()}},[ne,V.length]),w.useEffect(()=>{if(!ce){T(0);return}T(ge=>Math.min(ge,q-1))},[V.length,ce,q]),w.useEffect(()=>{if(!ce||N==null)return;const ge=V.findIndex(z=>z.index===N);if(ge<0)return;const Z=Math.floor(ge/J);T(z=>z===Z?z:Z)},[V,J,N,ce]),w.useEffect(()=>{if(!ne){P(null),D(!1);return}if(B)return;const ge=H.current,Z=G.current;if(!ge||!Z)return;const z=ge.clientHeight;if(!z)return;const F=Math.max(Q,z*ae),W=Math.max(K,z-I-F),me=Math.min(Z.scrollHeight,W);P(Math.max(K,me))},[ne,B,V.length,k,I,K,Q,ae]),w.useEffect(()=>{if(!U)return;const ge=z=>{const F=H.current;if(!F)return;const W=F.getBoundingClientRect(),me=W.height;if(!me)return;const _e=Math.max(Q,me*ae),be=Math.max(K,me-I-_e),He=Math.min(be,Math.max(K,z.clientY-W.top));P(He)},Z=()=>{L(!1),D(!0)};return document.addEventListener("mousemove",ge),document.addEventListener("mouseup",Z),document.body.style.cursor="row-resize",document.body.style.userSelect="none",()=>{document.removeEventListener("mousemove",ge),document.removeEventListener("mouseup",Z),document.body.style.cursor="",document.body.style.userSelect=""}},[U,I,K,Q,ae]);const te=c?(r||"").toLowerCase()==="3mf":!0,he=()=>{if(!te)return;const ge=n||"model";if(c){const z=`${window.location.origin}${se.getLibraryFileDownloadUrl(e)}`;Nc(z,l);return}const Z=`${window.location.origin}${se.getArchiveForSlicer(t,ge)}`;Nc(Z,l)};return a.jsx("div",{className:`fixed inset-0 bg-black/70 flex items-center justify-center z-50 ${C?"p-0":"p-8"}`,onClick:i,children:a.jsxs("div",{className:`bg-bambu-dark-secondary border border-bambu-dark-tertiary w-full flex flex-col ${C?"h-full max-w-none rounded-none":"h-[80vh] max-w-4xl rounded-xl"}`,onClick:ge=>ge.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1 mr-4",children:[a.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:n}),ue&&a.jsxs("span",{className:"text-xs text-bambu-gray bg-bambu-dark-tertiary/70 px-2 py-1 rounded whitespace-nowrap",children:[Re,": ",s("modelViewer.objectCount",{count:de})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Te,{variant:"secondary",size:"sm",onClick:he,disabled:!te,children:[a.jsx(Xr,{className:"w-4 h-4"}),s("modelViewer.openInSlicer")]}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>j(ge=>!ge),title:C?"Exit fullscreen":"Enter fullscreen",children:C?a.jsx(EF,{className:"w-4 h-4"}):a.jsx(TF,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:i,children:a.jsx(Rt,{className:"w-5 h-5"})})]})]}),h&&a.jsxs("div",{className:"flex border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>h.has_model&&d("3d"),disabled:!h.has_model,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="3d"?"text-bambu-green border-b-2 border-bambu-green":h.has_model?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(Zi,{className:"w-4 h-4"}),s("modelViewer.tabs.model"),!h.has_model&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notAvailable"),")"]})]}),a.jsxs("button",{onClick:()=>h.has_gcode&&d("gcode"),disabled:!h.has_gcode,className:`flex items-center gap-2 px-6 py-3 text-sm font-medium transition-colors ${u==="gcode"?"text-bambu-green border-b-2 border-bambu-green":h.has_gcode?"text-bambu-gray hover:text-white":"text-bambu-gray/30 cursor-not-allowed"}`,children:[a.jsx(lhe,{className:"w-4 h-4"}),s("modelViewer.tabs.gcode"),!h.has_gcode&&a.jsxs("span",{className:"text-xs",children:["(",s("modelViewer.notSliced"),")"]})]})]}),a.jsx("div",{className:"flex-1 overflow-hidden p-4",children:p?a.jsx("div",{className:"w-full h-full flex items-center justify-center",children:a.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):u==="3d"&&h?a.jsxs("div",{ref:H,className:`w-full h-full flex flex-col ${ne?"gap-0 min-h-0":"gap-3"}`,children:[Y&&a.jsxs("div",{ref:G,style:ne&&E!=null?{height:E}:void 0,className:`rounded-lg border border-bambu-dark-tertiary bg-bambu-dark p-3 ${ne?"flex flex-col shrink-0":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray mb-2",children:[a.jsx(is,{className:"w-4 h-4"}),s("modelViewer.plates"),y&&a.jsx(it,{className:"w-3 h-3 animate-spin"})]}),a.jsxs("div",{className:ne?"flex flex-col min-h-0 flex-1":void 0,children:[a.jsx("div",{ref:Ne,className:ne?"min-h-0 overflow-hidden pr-1 flex-1":void 0,children:a.jsxs("div",{ref:le,className:ne?"grid gap-2":"grid grid-cols-2 md:grid-cols-3 gap-2",style:ne?{gridTemplateColumns:`repeat(${$}, minmax(0, 1fr))`}:void 0,children:[a.jsxs("button",{type:"button",onClick:()=>M(null),className:`flex items-center rounded-lg border text-left transition-colors ${ne?"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:[a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ne?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${ne?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ne?"text-xs":"text-sm"} text-white font-medium truncate`,children:s("modelViewer.allPlates")}),a.jsx("p",{className:`${ne?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.plateCount",{count:V.length})})]}),N==null&&a.jsx(Yr,{className:`${ne?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]}),ie.map(ge=>a.jsxs("button",{type:"button",onClick:()=>M(ge.index),className:`flex items-center rounded-lg border text-left transition-colors ${ne?"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?a.jsx("img",{src:ge.thumbnail_url,alt:`Plate ${ge.index}`,className:`${ne?"w-8 h-8":"w-10 h-10"} rounded object-cover bg-bambu-dark-tertiary`}):a.jsx("div",{className:`rounded bg-bambu-dark-tertiary flex items-center justify-center ${ne?"w-8 h-8":"w-10 h-10"}`,children:a.jsx(is,{className:`${ne?"w-4 h-4":"w-5 h-5"} text-bambu-gray`})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:`${ne?"text-xs":"text-sm"} text-white font-medium truncate`,children:ge.name||s("modelViewer.plateNumber",{number:ge.index})}),a.jsx("p",{className:`${ne?"text-[10px]":"text-xs"} text-bambu-gray truncate`,children:s("modelViewer.objectCount",{count:ge.object_count??ge.objects?.length??0})})]}),N===ge.index&&a.jsx(Yr,{className:`${ne?"w-3.5 h-3.5":"w-4 h-4"} text-bambu-green flex-shrink-0`})]},ge.index))]})}),(ee||ce)&&a.jsxs("div",{className:"mt-auto pt-3 flex items-center gap-4 text-xs text-bambu-gray overflow-x-auto",children:[ee&&a.jsxs("div",{className:"flex items-center gap-3 whitespace-nowrap",children:[a.jsx("span",{children:s("modelViewer.plateNumber",{number:ee.index})}),ee.print_time_seconds!=null&&a.jsx("span",{children:s("modelViewer.eta",{minutes:Math.round(ee.print_time_seconds/60)})}),ee.filament_used_grams!=null&&a.jsxs("span",{children:[ee.filament_used_grams.toFixed(1)," g"]}),ee.filaments.length>0&&a.jsx("span",{children:s("modelViewer.filamentCount",{count:ee.filaments.length})})]}),ce&&a.jsxs("div",{className:`flex items-center gap-2 whitespace-nowrap ${ee?"ml-auto":""}`,children:[a.jsx("span",{children:s("modelViewer.pagination.pageOf",{current:k+1,total:q})}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{type:"button",onClick:()=>T(ge=>Math.max(ge-1,0)),disabled:k===0,className:`px-2 py-1 rounded border text-xs ${k===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 Z=Math.max(0,k-Math.floor(2.5));const z=Math.min(q,Z+5);z-Z<5&&(Z=Math.max(0,z-5));const F=Array.from({length:z-Z},(W,me)=>Z+me);return a.jsxs(a.Fragment,{children:[Z>0&&a.jsx("button",{type:"button",onClick:()=>T(0),className:`px-2 py-1 rounded border text-xs ${k===0?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:"1"}),Z>1&&a.jsx("span",{className:"px-1",children:"…"}),F.map(W=>a.jsx("button",{type:"button",onClick:()=>T(W),className:`px-2 py-1 rounded border text-xs ${k===W?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:W+1},W)),zT(q-1),className:`px-2 py-1 rounded border text-xs ${k===q-1?"border-bambu-green text-bambu-green":"border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,children:q})]})})(),a.jsx("button",{type:"button",onClick:()=>T(ge=>Math.min(ge+1,q-1)),disabled:k>=q-1,className:`px-2 py-1 rounded border text-xs ${k>=q-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")})]})]})]})]})]}),ne&&a.jsx("div",{role:"separator","aria-orientation":"horizontal",onMouseDown:ge=>{ge.preventDefault(),L(!0),D(!0)},className:`h-2 cursor-row-resize flex items-center justify-center ${U?"bg-bambu-dark-tertiary":"bg-bambu-dark-secondary/60 hover:bg-bambu-dark-tertiary"}`,children:a.jsx("div",{className:"w-12 h-1 rounded-full bg-bambu-gray/50"})}),a.jsx("div",{className:`flex-1 ${ne?"min-h-0":""}`,children:a.jsx(aY,{url:c?se.getLibraryFileDownloadUrl(e):h.has_source?se.getSource3mfDownloadUrl(t):se.getArchiveDownload(t),fileType:r,buildVolume:h.build_volume,filamentColors:h.filament_colors,selectedPlateId:N,className:"w-full h-full"})})]}):u==="gcode"&&h?a.jsx(BY,{gcodeUrl:c?se.getLibraryFileGcodeUrl(e):se.getArchiveGcode(t),filamentColors:h.filament_colors,className:"w-full h-full"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s("modelViewer.noPreview")})})]})})}const GN={"000000":"Black","001489":"Blue","002e96":"Blue","0047bb":"Blue","00482b":"Pine Green","004ea8":"Blue","0056b8":"Cobalt Blue","0069b1":"Lake Blue","0072ce":"Blue","0078bf":"Marine Blue","0085ad":"Light Blue","0086d6":"Cyan","008bda":"Blue","009639":"Green","009bd8":"Cyan","009fa1":"Teal","00a6a0":"Green","00ae42":"Bambu Green","00b1b7":"Turquoise","00bb31":"Green","018814":"Candy Green","042f56":"Dark Blue","0a2989":"Blue","0a2ca5":"Blue","0c2340":"Navy Blue","0c3b95":"Blue",101820:"Black","147bd1":"Blue","164b35":"Green","16b08e":"Malachite Green","1d7c6a":"Oxide Green Metallic","1f79e5":"Lake Blue","2140b4":"Blue","25282a":"Black","2842ad":"Royal Blue","2d2b28":"Onyx Black Sparkle",324585:"Indigo Blue",353533:"Gray","39541a":"Forest Green","39699e":"Cobalt Blue Metallic","3b665e":"Green","3f5443":"Alpine Green Sparkle","3f8e43":"Mistletoe Green",424379:"Nebulae","43403d":"Iron Gray Metallic",482960:"Indigo Purple","483d8b":"Royal Purple Sparkle","489fdf":"Azure","4c241c":"Rosewood","4ce4a0":"Green","4d3324":"Dark Chocolate","4d5054":"Lava Gray","4dafda":"Cyan","4f3f24":"Black Walnut",515151:"Dark Gray","515a6c":"Gray",545454:"Dark Gray",565656:"Titan Gray","56b7e6":"Sky Blue",583061:"Violet Purple","5898dd":"Blue",594177:"Purple","5b492f":"Brown","5b6579":"Blue Gray","5c9748":"Matcha Green","5e43b7":"Purple","5e4b3c":"Copper","5f6367":"Titan Gray","61b0ff":"Translucent Light Blue","61bf36":"Green","61c680":"Grass Green","6667ab":"Lavender Blue","684a43":"Brown",686865:"Black","68724d":"Dark Green",688197:"Blue Gray","69398e":"Iris Purple","6e88bc":"Jeans Blue","6ee53c":"Lime Green","6f5034":"Cocoa Brown","7248bd":"Lavender","748c45":"Translucent Olive",757575:"Nardo Gray","75aed8":"Blue","77edd7":"Translucent Teal","789d4a":"Olive","792b36":"Crimson Red Sparkle","7ac0e9":"Glow Blue","7ae1bf":"Mint","7cd82b":"Lime Green","7d6556":"Dark Brown","8344b0":"Purple","847d48":"Bronze","854ce4":"Purple","8671cb":"Purple",875718:"Peanut Brown","87909a":"Silver","898d8d":"Gray","8a949e":"Gray","8e8e8e":"Translucent Gray","8e9089":"Gray","90ff1a":"Neon Green",918669:"Classic Birch",939393:"Gray",950051:"Plum","951e23":"Burgundy Red",959698:"Silver","96d8af":"Light Jade","96dcb9":"Mint","995f11":"Clay Brown","999d9d":"Gray","9b9ea0":"Ash Gray","9d2235":"Maroon Red","9d432c":"Brown","9e007e":"Purple","9ea2a2":"Gray","9f332a":"Brick Red",a1ffac:"Glow Green",a3d8e1:"Ice Blue",a6a9aa:"Silver",a8a8aa:"Gray",a8c6ee:"Baby Blue",aa6443:"Copper Brown Metallic",ad4e38:"Red Granite",adb1b2:"Gray",ae835b:"Caramel",ae96d4:"Lilac Purple",af1685:"Purple",afb1ae:"Gray",b15533:"Terracotta",b28b33:"Gold",b39b84:"Iridium Gold Metallic",b50011:"Red",b8acd6:"Lavender",b8cde9:"Ice Blue",ba9594:"Rose Gold",bb3d43:"Dark Red",bc0900:"Red",becf00:"Bright Green",c0df16:"Green",c12e1f:"Red",c2e189:"Apple Green",c3e2d6:"Light Cyan",c5ed48:"Lime",c6001a:"Red",c6c6c6:"Gray",c8102e:"Red",c8c8c8:"Silver",c98935:"Ochre Yellow",c9a381:"Translucent Brown",cbc6b8:"Bone White",cdceca:"Gray",cea629:"Classic Gold Sparkle",d02727:"Candy Red",d1d3d5:"Light Gray",d32941:"Red",d3b7a7:"Latte Brown",d6001c:"Red",d6abff:"Translucent Purple",d6cca3:"White Oak",dc3a27:"Orange",dd3c22:"Vermilion Red",de4343:"Scarlet Red",dfd1a7:"Beige",e02928:"Red",e4bd68:"Gold",e5b03d:"Gold",e83100:"Red",e8afcf:"Sakura Pink",e8dbb7:"Desert Tan",eaeae4:"White",eaeceb:"Silver",ec008c:"Magenta",ed0000:"Red",eeb1c1:"Pink",efe255:"Yellow",f0f1a8:"Clear",f17b8f:"Glow Pink",f3cfb2:"Champagne",f3e600:"Yellow",f48438:"Orange",f4a925:"Gold",f4d53f:"Yellow",f4ee2a:"Yellow",f5547c:"Hot Pink",f55a74:"Pink",f5b6cd:"Cherry Pink",f5dbab:"Mellow Yellow",f5f1dd:"White",f68b1b:"Neon Orange",f74e02:"Orange",f75403:"Orange",f7ada6:"Pink",f7d959:"Lemon Yellow",f7e6de:"Beige",f7f3f0:"White Marble",f8ff80:"Glow Yellow",f99963:"Mandarin Orange",f9c1bd:"Translucent Pink",f9dfb9:"Cream",f9ef41:"Yellow",f9f7f2:"Nature",f9f7f4:"White",fce300:"Yellow",fce900:"Yellow",fec600:"Sunflower Yellow",fedb00:"Yellow",ff4800:"Orange",ff671f:"Orange",ff6a13:"Orange",ff7f41:"Orange",ff9016:"Pumpkin Orange",ff911a:"Translucent Orange",ff9d5b:"Glow Orange",ffb549:"Sunflower Yellow",ffc72c:"Tangerine Yellow",ffce00:"Yellow",ffd00b:"Yellow",ffe133:"Yellow",fffaf2:"White",ffffff:"White"};function KHe(t){if(!t||t.length<6)return"Unknown";const e=t.replace("#",""),n=parseInt(e.substring(0,2),16),r=parseInt(e.substring(2,4),16),i=parseInt(e.substring(4,6),16),s=Math.max(n,r,i)/255,o=Math.min(n,r,i)/255,l=(s+o)/2;let c=0,u=0;if(s!==o){const d=s-o;u=l>.5?d/(2-s-o):d/(s+o);const h=n/255,f=r/255,p=i/255;s===h?c=((f-p)/d+(f.85?"White":u<.15?l<.4?"Dark Gray":l>.6?"Light Gray":"Gray":c<15||c>=345?"Red":c<45?"Orange":c<70?"Yellow":c<150?"Green":c<200?"Cyan":c<260?"Blue":c<290?"Purple":"Pink"}function qN(t){const e=t.replace("#","").toLowerCase().substring(0,6);return GN[e]?GN[e]:KHe(t)}function sne(t,e){if(t&&!/^[A-Z]\d+-[A-Z]\d+$/.test(t))return t;if(e&&e.length>=6){const n=e.substring(0,6).toLowerCase();if(GN[n])return GN[n]}return null}function a9(t){return t?`#${t.replace("#","").substring(0,6)}`:"#808080"}function ji(t){return t?t.replace("#","").toLowerCase().substring(0,6):""}function Rc(t,e,n=40){const r=ji(t),i=ji(e);if(!r||!i||r.length<6||i.length<6)return!1;const s=parseInt(r.substring(0,2),16),o=parseInt(r.substring(2,4),16),l=parseInt(r.substring(4,6),16),c=parseInt(i.substring(0,2),16),u=parseInt(i.substring(2,4),16),d=parseInt(i.substring(4,6),16);return Math.abs(s-c)<=n&&Math.abs(o-u)<=n&&Math.abs(l-d)<=n}function XHe(t,e,n,r){const i=String.fromCharCode(65+(t>=128?t-128:t));return n?`HT-${i}`:`AMS-${i} Slot ${e+1}`}function YHe(t,e,n){return t>=128?t:t*4+e}function QHe(t){if(!t)return"";const e=Math.floor(t/3600),n=Math.floor(t%3600/60);return e>0?`${e}h ${n}m`:`${n}m`}function s9(t){if(!t)return!1;const e=Date.now()+4320*60*60*1e3;return new Date(t).getTime()>e}function mM(t){const e=[],n=t?.ams_extruder_map,r=n&&Object.keys(n).length>0;t?.ams?.forEach(i=>{const s=i.tray.length===1;i.tray.forEach(o=>{if(o.tray_type){const l=a9(o.tray_color);e.push({type:o.tray_type,color:l,colorName:qN(l),amsId:i.id,trayId:o.id,isHt:s,isExternal:!1,label:XHe(i.id,o.id,s),globalTrayId:YHe(i.id,o.id),trayInfoIdx:o.tray_info_idx||"",extruderId:n?.[String(i.id)]})}})});for(const i of t?.vt_tray??[])if(i.tray_type){const s=a9(i.tray_color),o=i.id??254,l=(t?.vt_tray?.length??0)>1;e.push({type:i.tray_type,color:s,colorName:qN(s),amsId:-1,trayId:o-254,isHt:!1,isExternal:!0,label:l?o===254?"Ext-L":"Ext-R":"External",globalTrayId:o,trayInfoIdx:i.tray_info_idx||"",extruderId:r?o-254:void 0})}return e}function o9(t,e){if(!t?.filaments||t.filaments.length===0)return;const n=mM(e);if(n.length===0)return;const r=new Set,i=t.filaments.map(l=>{const c=l.tray_info_idx||"";let u=n.filter(v=>!r.has(v.globalTrayId));if(l.nozzle_id!=null){const v=u.filter(b=>b.extruderId===l.nozzle_id);v.length>0&&(u=v)}let d,h,f,p;if(c){const v=u.filter(b=>b.trayInfoIdx===c);v.length===1?d=v[0]:v.length>1&&(h=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&ji(b.color)===ji(l.color)),h||(f=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(b.color,l.color))),!h&&!f&&(p=v.find(b=>b.type?.toUpperCase()===l.type?.toUpperCase())))}!d&&!h&&!f&&!p&&(h=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&ji(v.color)===ji(l.color)),h||(f=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase()&&Rc(v.color,l.color))),!h&&!f&&(p=u.find(v=>v.type?.toUpperCase()===l.type?.toUpperCase())));const x=d||h||f||p||void 0;return x&&r.add(x.globalTrayId),{slot_id:l.slot_id,globalTrayId:x?.globalTrayId??-1}}),s=Math.max(...i.map(l=>l.slot_id||0));if(s<=0)return;const o=new Array(s).fill(-1);return i.forEach(l=>{l.slot_id&&l.slot_id>0&&(o[l.slot_id-1]=l.globalTrayId)}),o}function ZHe(t){return w.useMemo(()=>mM(t),[t])}function one(t,e,n){const r=ZHe(e),i=w.useMemo(()=>{if(!t?.filaments||t.filaments.length===0)return[];const c=new Set(Object.values(n));return t.filaments.map(u=>{const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const T=n[d],C=r.find(j=>j.globalTrayId===T);if(C){const j=C.type?.toUpperCase()===u.type?.toUpperCase(),E=ji(C.color)===ji(u.color)||Rc(C.color,u.color);let P;return j&&E?P="match":j?P="type_only":P="mismatch",{...u,loaded:C,hasFilament:!0,typeMatch:j,colorMatch:E,status:P,isManual:!0}}}const h=u.tray_info_idx||"";let f=r.filter(T=>!c.has(T.globalTrayId));if(u.nozzle_id!=null){const T=f.filter(C=>C.extruderId===u.nozzle_id);T.length>0&&(f=T)}let p,x,v,b;if(h){const T=f.filter(C=>C.trayInfoIdx===h);T.length===1?p=T[0]:T.length>1&&(x=T.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase()&&ji(C.color)===ji(u.color)),x||(v=T.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(C.color,u.color))),!x&&!v&&(b=T.find(C=>C.type?.toUpperCase()===u.type?.toUpperCase())))}!p&&!x&&!v&&!b&&(x=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&ji(T.color)===ji(u.color)),x||(v=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(T.color,u.color))),!x&&!v&&(b=f.find(T=>T.type?.toUpperCase()===u.type?.toUpperCase())));const y=p||x||v||b||void 0;y&&c.add(y.globalTrayId);const S=!!y,N=S,M=!!p||!!x||!!v;let k;return p||x||v?k="match":b?k="type_only":k="mismatch",{...u,loaded:y,hasFilament:S,typeMatch:N,colorMatch:M,status:k,isManual:!1}})},[t,r,n]),s=w.useMemo(()=>{if(i.length===0)return;const c=Math.max(...i.map(d=>d.slot_id||0));if(c<=0)return;const u=new Array(c).fill(-1);return i.forEach(d=>{d.slot_id&&d.slot_id>0&&(u[d.slot_id-1]=d.loaded?.globalTrayId??-1)}),u},[i]),o=i.some(c=>c.status==="mismatch"),l=i.some(c=>c.status==="type_only");return{loadedFilaments:r,filamentComparison:i,amsMapping:s,hasTypeMismatch:o,hasColorMismatch:l}}function JHe(t,e,n){if(!t||t.length===0)return{exactMatches:0,typeOnlyMatches:0,missingTypes:0,totalSlots:0,status:"full"};let r=0,i=0,s=0;const o=new Set(Object.values(n));for(const u of t){const d=u.slot_id||0;if(d>0&&n[d]!==void 0){const b=n[d],y=e.find(S=>S.globalTrayId===b);if(y){const S=y.type?.toUpperCase()===u.type?.toUpperCase(),N=ji(y.color)===ji(u.color)||Rc(y.color,u.color);S&&N?r++:S?i++:s++;continue}}let h=e.filter(b=>!o.has(b.globalTrayId));if(u.nozzle_id!=null){const b=h.filter(y=>y.extruderId===u.nozzle_id);b.length>0&&(h=b)}const f=h.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&ji(b.color)===ji(u.color)),p=f?void 0:h.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(b.color,u.color)),x=f||p?void 0:h.find(b=>b.type?.toUpperCase()===u.type?.toUpperCase()),v=f??p??x;v&&o.add(v.globalTrayId),f||p?r++:x?i++:s++}const l=t.length;let c="full";return s>0?c="missing":i>0&&(c="partial"),{exactMatches:r,typeOnlyMatches:i,missingTypes:s,totalSlots:l,status:c}}function e$e(t,e,n){if(!t?.filaments||t.filaments.length===0)return;const r=mM(e);if(r.length===0)return;const i=new Set(Object.values(n)),s=[];for(const c of t.filaments){const u=c.slot_id||0;if(u>0&&n[u]!==void 0){s.push({slot_id:u,globalTrayId:n[u]});continue}let d=r.filter(v=>!i.has(v.globalTrayId));if(c.nozzle_id!=null){const v=d.filter(b=>b.extruderId===c.nozzle_id);v.length>0&&(d=v)}const h=d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&ji(v.color)===ji(c.color)),f=h?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()&&Rc(v.color,c.color)),p=h||f?void 0:d.find(v=>v.type?.toUpperCase()===c.type?.toUpperCase()),x=h??f??p;x&&i.add(x.globalTrayId),s.push({slot_id:u,globalTrayId:x?.globalTrayId??-1})}const o=Math.max(...s.map(c=>c.slot_id||0));if(o<=0)return;const l=new Array(o).fill(-1);return s.forEach(c=>{c.slot_id&&c.slot_id>0&&(l[c.slot_id-1]=c.globalTrayId)}),l}const l9={useDefault:!0,manualMappings:{},autoConfigured:!1};function t$e(t,e,n,r,i,s){const o=kF({queries:t.map(x=>({queryKey:["printer-status",x],queryFn:()=>se.getPrinterStatus(x),enabled:t.length>0,staleTime:5e3}))}),l=w.useMemo(()=>t.map((x,v)=>{const b=o[v],y=b?.data,N=e?.find(P=>P.id===x)?.name||`Printer ${x}`,M=mM(y),k=i[x]||l9,T=o9(n,y),C=k.useDefault?r:k.manualMappings,j=e$e(n,y,C),E=JHe(n?.filaments,M,C);return{printerId:x,printerName:N,status:y,isLoading:b?.isLoading??!1,loadedFilaments:M,autoMapping:T,finalMapping:j,matchStatus:E.status,exactMatches:E.exactMatches,typeOnlyMatches:E.typeOnlyMatches,missingTypes:E.missingTypes,totalSlots:E.totalSlots,config:k}}),[t,o,e,n,i,r]),c=o.some(x=>x.isLoading),u=(x,v)=>{s(b=>({...b,[x]:{...b[x]||l9,...v}}))},d=x=>{const v=l.find(S=>S.printerId===x);if(!v||!v.status||!n?.filaments)return;const b=o9(n,v.status);if(!b)return;const y={};b.forEach((S,N)=>{S!==-1&&(y[N+1]=S)}),u(x,{useDefault:!1,manualMappings:y,autoConfigured:!0})},h=()=>{for(const x of t)d(x)},f=x=>l.find(b=>b.printerId===x)?.finalMapping,p=l.every(x=>x.matchStatus!=="missing");return{printerResults:l,isLoading:c,perPrinterConfigs:i,updatePrinterConfig:u,autoConfigureAll:h,autoConfigurePrinter:d,getFinalMapping:f,allPrintersReady:p}}function n$e({printerResult:t,filamentReqs:e,onUpdateConfig:n}){const r=Zt(),[i,s]=w.useState(!1),o=(u,d)=>{if(u<=0)return;const h={...t.config.manualMappings};d===""?delete h[u]:h[u]=parseInt(d,10),n({useDefault:!1,manualMappings:h,autoConfigured:!1})},l=async()=>{s(!0);try{await se.refreshPrinterStatus(t.printerId),await new Promise(u=>setTimeout(u,500)),await r.refetchQueries({queryKey:["printer-status",t.printerId]})}finally{s(!1)}},c=e.map(u=>{const d=u.slot_id||0,h=t.config.manualMappings[d];let f,p=!1;if(h!==void 0)f=t.loadedFilaments.find(v=>v.globalTrayId===h),p=!0;else{const v=new Set(Object.values(t.config.manualMappings)),b=t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&ji(N.color)===ji(u.color)),y=b?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase()&&Rc(N.color,u.color)),S=b||y?void 0:t.loadedFilaments.find(N=>!v.has(N.globalTrayId)&&N.type?.toUpperCase()===u.type?.toUpperCase());f=b??y??S}let x="mismatch";if(f){const v=f.type?.toUpperCase()===u.type?.toUpperCase(),b=ji(f.color)===ji(u.color)||Rc(f.color,u.color);v&&b?x="match":v&&(x="type_only")}return{req:u,loaded:f,status:x,isManual:p}});return a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom slot mapping"}),a.jsxs("button",{type:"button",onClick:l,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:i,children:[a.jsx(Ur,{className:`w-3 h-3 ${i?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),c.map(({req:u,loaded:d,status:h,isManual:f},p)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${u.type} - ${qN(u.color)}`,children:a.jsx(s3,{className:"w-3 h-3",fill:u.color,stroke:u.color})}),a.jsxs("span",{className:"text-white truncate",children:[u.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",u.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:d?.globalTrayId??"",onChange:x=>o(u.slot_id||0,x.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${h==="match"?"border-bambu-green/50 text-bambu-green":h==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${f?"ring-1 ring-blue-400/50":""}`,title:f?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),t.loadedFilaments.map(x=>a.jsxs("option",{value:x.globalTrayId,className:"bg-bambu-dark text-white",children:[x.label,": ",x.type," (",x.colorName,")"]},x.globalTrayId))]}),h==="match"?a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}):h==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Mn,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Mn,{className:"w-3 h-3 text-orange-400"})})]},p))]})}function r$e({printers:t,selectedPrinterIds:e,onMultiSelect:n,isLoading:r=!1,allowMultiple:i=!1,showInactive:s=!1,printerMappingResults:o,filamentReqs:l,onAutoConfigurePrinter:c,onUpdatePrinterConfig:u,assignmentMode:d="printer",onAssignmentModeChange:h,targetModel:f,onTargetModelChange:p,targetLocation:x,onTargetLocationChange:v,slicedForModel:b}){const[y,S]=w.useState(!1),N=s?t:t.filter(I=>I.is_active),M=w.useMemo(()=>{if(d!=="printer"||!b||y)return N;const I=N.filter(K=>K.model===b);return I.length>0?I:N},[N,d,b,y]),k=N.length-M.length,T=w.useMemo(()=>{const I=N.map(K=>K.model).filter(K=>!!K);return[...new Set(I)].sort()},[N]),C=w.useMemo(()=>{if(!f)return[];const I=N.filter(K=>K.model===f&&K.location).map(K=>K.location).filter(K=>!!K);return[...new Set(I)].sort()},[N,f]),j=h&&p&&T.length>0,E=i&&e.length>1&&o&&l?.filaments&&l.filaments.length>0&&c&&u;if(r)return a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(M.length===0)return a.jsxs("div",{className:"flex items-center gap-2 text-red-400 text-sm mb-4",children:[a.jsx(Bi,{className:"w-4 h-4"}),"No ",s?"":"active ","printers available"]});const P=I=>{i?e.includes(I)?n(e.filter(K=>K!==I)):n([...e,I]):n([I])},U=()=>{n(M.map(I=>I.id))},L=()=>{n([])},B=(I,K,Q)=>{Q.stopPropagation(),!(!c||!u)&&(K?c(I):u(I,{useDefault:!0,manualMappings:{},autoConfigured:!1}))},D=I=>e.includes(I),H=e.length,G=I=>o?.find(K=>K.printerId===I);return a.jsxs("div",{className:"space-y-2 mb-6",children:[j&&a.jsxs("div",{className:"flex gap-2 mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>{h("printer"),p(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="printer"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(Cr,{className:"w-4 h-4"}),a.jsx("span",{className:"text-sm",children:"Specific Printer"})]}),a.jsxs("button",{type:"button",onClick:()=>{h("model"),n([]);const I=b&&T.includes(b)?b:T[0];p(I)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg border transition-colors ${d==="model"?"border-bambu-green bg-bambu-green/10 text-white":"border-bambu-dark-tertiary bg-bambu-dark text-bambu-gray hover:border-bambu-gray"}`,children:[a.jsx(gh,{className:"w-4 h-4"}),a.jsxs("span",{className:"text-sm",children:["Any ",b||"Model"]})]})]}),d==="model"&&j&&a.jsxs("div",{className:"space-y-3 mb-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Target Model"}),a.jsxs("select",{value:f||"",onChange:I=>{p(I.target.value||null),v&&v(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 text-sm",children:[a.jsx("option",{value:"",children:"Select a model..."}),T.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),f&&C.length>0&&v&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Location Filter (optional)"}),a.jsxs("select",{value:x||"",onChange:I=>v(I.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 text-sm",children:[a.jsx("option",{value:"",children:"Any location"}),C.map(I=>a.jsx("option",{value:I,children:I},I))]})]}),f&&a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Scheduler will assign to first available idle ",f," printer",x?` in ${x}`:""]})]}),d==="printer"&&i&&M.length>1&&a.jsxs("div",{className:"flex items-center justify-between text-xs text-bambu-gray mb-2",children:[a.jsx("span",{children:H===0?"Select printers":`${H} printer${H!==1?"s":""} selected`}),a.jsxs("div",{className:"flex gap-2",children:[H0&&a.jsx("button",{type:"button",onClick:L,className:"text-bambu-gray hover:text-white transition-colors",children:"Clear"})]})]}),d==="printer"&&M.map(I=>{const K=D(I.id),Q=G(I.id),ae=Q&&!Q.config.useDefault;return a.jsxs("div",{children:[a.jsxs("button",{type:"button",onClick:()=>P(I.id),className:`w-full flex items-center gap-3 p-3 rounded-lg border transition-colors ${K?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"} ${I.is_active?"":"opacity-60"}`,children:[a.jsx("div",{className:`p-2 rounded-lg ${K?"bg-bambu-green/20":"bg-bambu-dark-tertiary"}`,children:a.jsx(Cr,{className:`w-5 h-5 ${K?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{className:"text-left flex-1",children:[a.jsxs("p",{className:"text-white font-medium",children:[I.name,!I.is_active&&a.jsx("span",{className:"text-bambu-gray text-xs ml-2",children:"(inactive)"})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[I.model||"Unknown model"," • ",I.ip_address]})]}),i&&a.jsx("div",{className:`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${K?"bg-bambu-green border-bambu-green":"border-bambu-gray/50"}`,children:K&&a.jsx(Yr,{className:"w-3 h-3 text-white"})})]}),K&&E&&Q&&a.jsxs("div",{className:"ml-4 mt-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",onClick:V=>V.stopPropagation(),children:[a.jsx("input",{type:"checkbox",checked:ae,onChange:V=>B(I.id,V.target.checked,V),className:"w-3.5 h-3.5 rounded border-bambu-gray/30 bg-bambu-dark-secondary text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"Custom mapping"})]}),a.jsxs("span",{className:`text-xs ml-2 ${Q.matchStatus==="full"?"text-bambu-green":Q.matchStatus==="partial"?"text-yellow-400":"text-orange-400"}`,children:["(",Q.exactMatches,"/",Q.totalSlots," matched)"]}),Q.isLoading&&a.jsx(Ur,{className:"w-3 h-3 text-bambu-gray animate-spin"}),ae&&a.jsxs("button",{type:"button",onClick:V=>{V.stopPropagation(),c(I.id)},className:"ml-auto flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",children:[a.jsx(Spe,{className:"w-3 h-3"}),"Auto"]})]}),ae&&a.jsx(n$e,{printerResult:Q,filamentReqs:l.filaments,onUpdateConfig:V=>u(I.id,V)})]})]},I.id)}),d==="printer"&&k>0&&!y&&a.jsxs("button",{type:"button",onClick:()=>S(!0),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2 flex items-center gap-1",children:[a.jsx(Mn,{className:"w-3 h-3 text-yellow-400"}),k," other printer",k>1?"s":""," hidden (different model) —",a.jsx("span",{className:"underline",children:"show all"})]}),d==="printer"&&y&&b&&a.jsx("button",{type:"button",onClick:()=>S(!1),className:"text-xs text-bambu-gray hover:text-white transition-colors mt-2",children:a.jsxs("span",{className:"underline",children:["Show only ",b," printers"]})}),d==="printer"&&H===0&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Bi,{className:"w-3 h-3"}),"Select at least one printer"]}),d==="model"&&!f&&a.jsxs("p",{className:"text-xs text-orange-400 mt-1 flex items-center gap-1",children:[a.jsx(Bi,{className:"w-3 h-3"}),"Select a target printer model"]})]})}function i$e({plates:t,isMultiPlate:e,selectedPlate:n,onSelect:r}){return!e||t.length<=1?null:a.jsxs("div",{className:"mb-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[a.jsx(is,{className:"w-4 h-4 text-bambu-gray"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:"Select Plate to Print"}),!n&&a.jsxs("span",{className:"text-xs text-orange-400 flex items-center gap-1",children:[a.jsx(Mn,{className:"w-3 h-3"}),"Selection required"]})]}),a.jsx("div",{className:"grid grid-cols-2 gap-2",children:t.map(i=>a.jsxs("button",{type:"button",onClick:()=>r(i.index),className:`flex items-center gap-2 p-2 rounded-lg border transition-colors text-left ${n===i.index?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray"}`,children:[i.has_thumbnail&&i.thumbnail_url!=null?a.jsx("img",{src:i.thumbnail_url,alt:`Plate ${i.index}`,className:"w-10 h-10 rounded object-cover bg-bambu-dark-tertiary"}):a.jsx("div",{className:"w-10 h-10 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx(is,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-sm text-white font-medium truncate",children:i.name||`Plate ${i.index}`}),a.jsxs("p",{className:"text-xs text-bambu-gray truncate",children:[i.objects.length>0?i.objects.slice(0,3).join(", ")+(i.objects.length>3?"...":""):`${i.filaments.length} filament${i.filaments.length!==1?"s":""}`,i.print_time_seconds!=null?` • ${QHe(i.print_time_seconds)}`:""]})]}),n===i.index&&a.jsx(Yr,{className:"w-4 h-4 text-bambu-green flex-shrink-0"})]},i.index))})]})}function a$e({printerId:t,filamentReqs:e,manualMappings:n,onManualMappingChange:r,defaultExpanded:i=!1}){const{t:s}=Ut(),o=Zt(),[l,c]=w.useState(!1),[u,d]=w.useState(i),{data:h}=et({queryKey:["printer-status",t],queryFn:()=>se.getPrinterStatus(t),enabled:!!t}),{loadedFilaments:f,filamentComparison:p,hasTypeMismatch:x,hasColorMismatch:v}=one(e,h,n),b=e?.filaments&&e.filaments.length>0,y=e?.filaments?.some(k=>k.nozzle_id!=null)??!1;if(!b||!h)return null;const S=x?"#f97316":v?"#facc15":"#00ae42",N=(k,T)=>{if(k>0)if(T===""){const C={...n};delete C[k],r(C)}else r({...n,[k]:parseInt(T,10)})},M=async()=>{c(!0);try{await se.refreshPrinterStatus(t),await new Promise(k=>setTimeout(k,500)),await o.refetchQueries({queryKey:["printer-status",t]})}finally{c(!1)}};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>d(!u),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(s3,{className:"w-4 h-4",fill:S,stroke:"none"}),a.jsx("span",{children:"Filament Mapping"}),x?a.jsx("span",{className:"text-xs text-orange-400",children:"(Type not found)"}):v?a.jsx("span",{className:"text-xs text-yellow-400",children:"(Color mismatch)"}):a.jsx("span",{className:"text-xs text-bambu-green",children:"(Ready)"}),u?a.jsx(Wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Jn,{className:"w-4 h-4 ml-auto"})]}),u&&a.jsxs("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Click to change slot assignment"}),a.jsxs("button",{type:"button",onClick:M,className:"flex items-center gap-1 px-2 py-0.5 text-xs rounded border border-bambu-gray/30 hover:border-bambu-gray hover:bg-bambu-dark-tertiary transition-colors text-bambu-gray hover:text-white",disabled:l,children:[a.jsx(Ur,{className:`w-3 h-3 ${l?"animate-spin":""}`}),a.jsx("span",{children:"Re-read"})]})]}),p.map((k,T)=>a.jsxs("div",{className:"grid items-center gap-2 text-xs",style:{gridTemplateColumns:"16px minmax(70px, 1fr) auto 2fr 16px"},children:[a.jsx("span",{title:`Required: ${k.type} - ${qN(k.color)}`,children:a.jsx(s3,{className:"w-3 h-3",fill:k.color,stroke:k.color})}),a.jsxs("span",{className:"text-white truncate flex items-center gap-1",children:[y&&k.nozzle_id!=null&&a.jsx("span",{className:"inline-flex items-center justify-center w-3.5 h-3.5 rounded text-[9px] font-bold leading-none bg-bambu-gray/20 text-bambu-gray shrink-0",title:k.nozzle_id===1?s("printModal.leftNozzleTooltip"):s("printModal.rightNozzleTooltip"),children:k.nozzle_id===1?s("printModal.leftNozzle"):s("printModal.rightNozzle")}),k.type," ",a.jsxs("span",{className:"text-bambu-gray",children:["(",k.used_grams,"g)"]})]}),a.jsx("span",{className:"text-bambu-gray",children:"→"}),a.jsxs("select",{value:k.loaded?.globalTrayId??"",onChange:C=>N(k.slot_id||0,C.target.value),className:`flex-1 px-2 py-1 rounded border text-xs bg-bambu-dark-secondary focus:outline-none focus:ring-1 focus:ring-bambu-green ${k.status==="match"?"border-bambu-green/50 text-bambu-green":k.status==="type_only"?"border-yellow-400/50 text-yellow-400":"border-orange-400/50 text-orange-400"} ${k.isManual?"ring-1 ring-blue-400/50":""}`,title:k.isManual?"Manually selected":"Auto-matched",children:[a.jsx("option",{value:"",className:"bg-bambu-dark text-bambu-gray",children:"-- Select slot --"}),f.map(C=>a.jsxs("option",{value:C.globalTrayId,className:"bg-bambu-dark text-white",children:[C.label,": ",C.type," (",C.colorName,")"]},C.globalTrayId))]}),k.status==="match"?a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}):k.status==="type_only"?a.jsx("span",{title:"Same type, different color",children:a.jsx(Mn,{className:"w-3 h-3 text-yellow-400"})}):a.jsx("span",{title:"Filament type not loaded",children:a.jsx(Mn,{className:"w-3 h-3 text-orange-400"})})]},T)),x&&a.jsx("p",{className:"text-xs text-orange-400 mt-2",children:"Required filament type not found in printer."})]})]})}const s$e=[{key:"bed_levelling",label:"Bed Levelling",desc:"Auto-level bed before print"},{key:"flow_cali",label:"Flow Calibration",desc:"Calibrate extrusion flow"},{key:"vibration_cali",label:"Vibration Calibration",desc:"Reduce ringing artifacts"},{key:"layer_inspect",label:"First Layer Inspection",desc:"AI inspection of first layer"},{key:"timelapse",label:"Timelapse",desc:"Record timelapse video"}];function o$e({options:t,onChange:e,defaultExpanded:n=!1}){const[r,i]=w.useState(n),s=o=>{e({...t,[o]:!t[o]})};return a.jsxs("div",{className:"mb-4",children:[a.jsxs("button",{type:"button",onClick:()=>i(!r),className:"flex items-center gap-2 text-sm text-bambu-gray hover:text-white transition-colors w-full",children:[a.jsx(ik,{className:"w-4 h-4"}),a.jsx("span",{children:"Print Options"}),r?a.jsx(Wl,{className:"w-4 h-4 ml-auto"}):a.jsx(Jn,{className:"w-4 h-4 ml-auto"})]}),r&&a.jsx("div",{className:"mt-2 bg-bambu-dark rounded-lg p-3 space-y-2",children:s$e.map(({key:o,label:l,desc:c})=>a.jsxs("label",{className:"flex items-center justify-between cursor-pointer group",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:l}),a.jsx("p",{className:"text-xs text-bambu-gray",children:c})]}),a.jsx("div",{className:`relative w-10 h-5 rounded-full transition-colors ${t[o]?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,onClick:()=>s(o),children:a.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${t[o]?"translate-x-5":"translate-x-0.5"}`})})]},o))})]})}function l$e({options:t,onChange:e,dateFormat:n="system",timeFormat:r="system"}){const[i,s]=w.useState(""),[o,l]=w.useState(""),[c,u]=w.useState(!0),[d,h]=w.useState(!0),f=w.useRef(null),p=w.useRef(!1);w.useEffect(()=>{if(t.scheduleType!=="scheduled"){p.current=!1;return}if(!p.current){p.current=!0;let M;t.scheduledTime?(M=new Date(t.scheduledTime),isNaN(M.getTime())&&(M=new Date,M.setHours(M.getHours()+1,0,0,0))):(M=new Date,M.setHours(M.getHours()+1,0,0,0),e({...t,scheduledTime:p3(M)})),s(HB(M,n)),l($B(M,r)),u(!0),h(!0)}},[t.scheduleType,t.scheduledTime,n,r,e,t]);const x=M=>{e({...t,scheduleType:M})},v=(M,k)=>{const T=Wpe(M,n),C=Kpe(k);u(!!T),h(!!C),T&&C&&(T.setHours(C.hours,C.minutes,0,0),T>new Date&&e({...t,scheduledTime:p3(T)}))},b=M=>{s(M),v(M,o)},y=M=>{l(M),v(i,M)},S=M=>{const k=M.target.value;if(k){const T=new Date(k);isNaN(T.getTime())||(s(HB(T,n)),l($B(T,r)),u(!0),h(!0),e({...t,scheduledTime:k}))}},N=()=>{f.current?.showPicker()};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"When to print"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="asap"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("asap"),children:[a.jsx(Xn,{className:"w-4 h-4"}),"ASAP"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="scheduled"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("scheduled"),children:[a.jsx(ai,{className:"w-4 h-4"}),"Scheduled"]}),a.jsxs("button",{type:"button",className:`flex-1 px-2 py-2 rounded-lg border text-sm flex items-center justify-center gap-1.5 transition-colors ${t.scheduleType==="manual"?"bg-bambu-green border-bambu-green text-white":"bg-bambu-dark border-bambu-dark-tertiary text-bambu-gray hover:text-white"}`,onClick:()=>x("manual"),children:[a.jsx(aX,{className:"w-4 h-4"}),"Queue Only"]})]})]}),t.scheduleType==="scheduled"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date & Time"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"flex-1 relative",children:[a.jsx("input",{type:"text",className:`w-full px-3 py-2 pr-10 bg-bambu-dark border rounded-lg text-white focus:outline-none ${c?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:i,onChange:M=>b(M.target.value),placeholder:Gpe(n)}),a.jsx("button",{type:"button",onClick:N,className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",title:"Open calendar",children:a.jsx(ai,{className:"w-4 h-4"})})]}),a.jsx("div",{className:"w-32",children:a.jsx("input",{type:"text",className:`w-full px-3 py-2 bg-bambu-dark border rounded-lg text-white focus:outline-none ${d?"border-bambu-dark-tertiary focus:border-bambu-green":"border-red-500"}`,value:o,onChange:M=>y(M.target.value),placeholder:qpe(r)})})]}),a.jsx("input",{ref:f,type:"datetime-local",className:"sr-only",value:t.scheduledTime,onChange:S,tabIndex:-1}),(!c||!d)&&a.jsx("p",{className:"mt-1 text-xs text-red-400",children:"Please enter a valid date and time"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"requirePrevious",checked:t.requirePreviousSuccess,onChange:M=>e({...t,requirePreviousSuccess:M.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsx("label",{htmlFor:"requirePrevious",className:"text-sm text-bambu-gray",children:"Only start if previous print succeeded"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"checkbox",id:"autoOffAfter",checked:t.autoOffAfter,onChange:M=>e({...t,autoOffAfter:M.target.checked}),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("label",{htmlFor:"autoOffAfter",className:"text-sm text-bambu-gray flex items-center gap-1",children:[a.jsx(fd,{className:"w-3.5 h-3.5"}),"Power off printer when done"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t.scheduleType==="asap"?"Print will start as soon as the printer is idle.":t.scheduleType==="scheduled"?"Print will start at the scheduled time if the printer is idle. If busy, it will wait until the printer becomes available.":"Print will be staged but won't start automatically. Use the Start button to release it to the queue."})]})}const Cg={bed_levelling:!0,flow_cali:!1,vibration_cali:!0,layer_inspect:!1,timelapse:!1},c$e={scheduleType:"asap",scheduledTime:"",requirePreviousSuccess:!1,autoOffAfter:!1};function Qu({mode:t,archiveId:e,libraryFileId:n,archiveName:r,queueItem:i,onClose:s,onSuccess:o}){const{t:l}=Ut(),c=Zt(),{showToast:u}=hn(),d=!!n&&!e,[h,f]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[p,x]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[v,b]=w.useState(()=>t==="edit-queue-item"&&i?{bed_levelling:i.bed_levelling??Cg.bed_levelling,flow_cali:i.flow_cali??Cg.flow_cali,vibration_cali:i.vibration_cali??Cg.vibration_cali,layer_inspect:i.layer_inspect??Cg.layer_inspect,timelapse:i.timelapse??Cg.timelapse}:Cg),[y,S]=w.useState(()=>{if(t==="edit-queue-item"&&i){let ye="asap";i.manual_start?ye="manual":i.scheduled_time&&!s9(i.scheduled_time)&&(ye="scheduled");let we="";if(i.scheduled_time&&!s9(i.scheduled_time)){const Ce=new Date(i.scheduled_time);we=p3(Ce)}return{scheduleType:ye,scheduledTime:we,requirePreviousSuccess:i.require_previous_success,autoOffAfter:i.auto_off_after}}return c$e}),[N,M]=w.useState(()=>{if(t==="edit-queue-item"&&i?.ams_mapping&&Array.isArray(i.ams_mapping)){const ye={};return i.ams_mapping.forEach((we,Ce)=>{we!==-1&&(ye[Ce+1]=we)}),ye}return{}}),[k,T]=w.useState({}),[C,j]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?"model":"printer"),[E,P]=w.useState(()=>t==="edit-queue-item"&&i?.target_model?i.target_model:null),[U,L]=w.useState(()=>t==="edit-queue-item"&&i?.target_location?i.target_location:null),[B]=w.useState(()=>t==="edit-queue-item"&&i?.printer_id?[i.printer_id]:[]),[D]=w.useState(()=>t==="edit-queue-item"&&i?i.plate_id:null),[H,G]=w.useState(!1),[I,K]=w.useState({current:0,total:0}),[Q,ae]=w.useState(new Set),V=h.length,Y=h.length>0?h[0]:null,{data:ne}=et({queryKey:["settings"],queryFn:se.getSettings}),{data:ee,isLoading:ve}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:fe}=et({queryKey:["archive",e],queryFn:()=>se.getArchive(e),enabled:!!e&&!d}),{data:de}=et({queryKey:["library-file",n],queryFn:()=>se.getLibraryFile(n),enabled:d&&!!n}),Re=fe?.sliced_for_model||de?.sliced_for_model||null,{data:ue,isError:le}=et({queryKey:["archive-plates",e],queryFn:()=>se.getArchivePlates(e),enabled:!!e&&!d,retry:!1}),{data:Ne}=et({queryKey:["library-file-plates",n],queryFn:()=>se.getLibraryFilePlates(n),enabled:d&&!!n}),J=d?Ne:ue,{data:Le,isError:$}=et({queryKey:["archive-filaments",e,p],queryFn:()=>se.getArchiveFilamentRequirements(e,p??void 0),enabled:!!e&&!d&&(p!==null||!J?.is_multi_plate),retry:!1}),{data:X}=et({queryKey:["library-file-filaments",n,p],queryFn:()=>se.getLibraryFileFilamentRequirements(n,p??void 0),enabled:d&&!!n&&(p!==null||!J?.is_multi_plate)}),ce=!d&&(le||$),q=d?X:Le,{data:ie}=et({queryKey:["printer-status",Y],queryFn:()=>se.getPrinterStatus(Y),enabled:!!Y}),{amsMapping:te}=one(q,ie,N),he=t$e(h,ee,q,N,k,T);w.useEffect(()=>{J?.plates?.length===1&&!p&&x(J.plates[0].index)},[J,p]),w.useEffect(()=>{if(t==="edit-queue-item")return;const ye=ee?.filter(we=>we.is_active)||[];ye.length===1&&h.length===0&&f([ye[0].id])},[t,ee,h.length]),w.useEffect(()=>{t==="edit-queue-item"?(JSON.stringify(h.sort())!==JSON.stringify(B.sort())||p!==D)&&(M({}),T({}),ae(new Set)):(M({}),T({}),ae(new Set))},[t,h,p,B,D]),w.useEffect(()=>{if(!ne?.per_printer_mapping_expanded||h.length<=1)return;const ye=h.filter(we=>{if(Q.has(we))return!1;const Ce=he.printerResults.find(Ue=>Ue.printerId===we);return Ce&&Ce.status&&!Ce.isLoading});ye.length>0&&(ae(we=>{const Ce=new Set(we);return ye.forEach(Ue=>Ce.add(Ue)),Ce}),ye.forEach(we=>{he.autoConfigurePrinter(we)}))},[ne?.per_printer_mapping_expanded,h,Q,he]),w.useEffect(()=>{const ye=we=>{we.key==="Escape"&&!H&&s()};return window.addEventListener("keydown",ye),()=>window.removeEventListener("keydown",ye)},[s,H]);const ge=J?.is_multi_plate??!1,Z=J?.plates??[],z=ot({mutationFn:ye=>se.addToQueue(ye)}),F=ot({mutationFn:ye=>se.updateQueueItem(i.id,ye),onSuccess:()=>{c.invalidateQueries({queryKey:["queue"]}),u("Queue item updated"),o?.(),s()},onError:ye=>{u(ye.message||"Failed to update queue item","error")}}),W=async ye=>{if(ye?.preventDefault(),C==="printer"&&h.length===0){u("Please select at least one printer","error");return}if(C==="model"&&!E){u("Please select a target printer model","error");return}G(!0);const we=C==="model"?1:h.length;K({current:0,total:we});const Ce={success:0,failed:0,errors:[]},Ue=Ve=>{if(h.length>1){const Ae=k[Ve];if(Ae&&!Ae.useDefault)return he.getFinalMapping(Ve)}return te},je=Ve=>({printer_id:C==="printer"?Ve:null,target_model:C==="model"?E:null,target_location:C==="model"?U:null,archive_id:d?void 0:e,library_file_id:d?n:void 0,require_previous_success:y.requirePreviousSuccess,auto_off_after:y.autoOffAfter,manual_start:y.scheduleType==="manual",ams_mapping:Ve?Ue(Ve):void 0,plate_id:p,scheduled_time:y.scheduleType==="scheduled"&&y.scheduledTime?new Date(y.scheduledTime).toISOString():void 0,...v});if(C==="model"){K({current:1,total:1});try{if(t==="reprint"){u("Model-based assignment only works with queue mode","error"),G(!1);return}else if(t==="edit-queue-item"){const Ve={printer_id:null,target_model:E,target_location:U,require_previous_success:y.requirePreviousSuccess,auto_off_after:y.autoOffAfter,manual_start:y.scheduleType==="manual",ams_mapping:void 0,plate_id:p,scheduled_time:y.scheduleType==="scheduled"&&y.scheduledTime?new Date(y.scheduledTime).toISOString():null,...v};await F.mutateAsync(Ve)}else await z.mutateAsync(je(null));Ce.success++}catch(Ve){Ce.failed++,Ce.errors.push(Ve.message)}}else for(let Ve=0;VeXe.id===Ae)?.name||`Printer ${Ae}`;Ce.errors.push(`${Pe}: ${Ze.message}`)}}if(G(!1),Ce.failed===0){if(C==="model")u(t==="edit-queue-item"?"Queue item updated":`Queued for any ${E}`);else{const Ve=t==="reprint"?"sent to":t==="edit-queue-item"?"updated/queued for":"queued for";Ce.success===1?u(t==="edit-queue-item"?"Queue item updated":`Print ${Ve} printer`):u(`Print ${Ve} ${Ce.success} printers`)}c.invalidateQueries({queryKey:["queue"]}),o?.(),s()}else Ce.success===0?u(`Failed: ${Ce.errors[0]}`,"error"):(u(`${Ce.success} succeeded, ${Ce.failed} failed`,"error"),c.invalidateQueries({queryKey:["queue"]}))},me=H||F.isPending,_e=w.useMemo(()=>!(me||C==="printer"&&h.length===0||C==="model"&&!E||C==="model"&&t==="reprint"||!d&&ge&&!p),[h.length,C,E,t,ge,p,me,d]),He=(()=>{const ye=h.length;return t==="reprint"?{title:l(d?"queue.print":"queue.reprint"),icon:Cr,submitText:ye>1?l("queue.printToPrinters",{count:ye}):l("queue.print"),submitIcon:Cr,loadingText:I.total>1?l("queue.sendingProgress",{current:I.current,total:I.total}):l("queue.sending")}:t==="add-to-queue"?{title:l("queue.schedulePrint"),icon:ai,submitText:ye>1?l("queue.queueToPrinters",{count:ye}):l("queue.addToQueue"),submitIcon:ai,loadingText:I.total>1?l("queue.addingProgress",{current:I.current,total:I.total}):l("queue.adding")}:{title:l("queue.editQueueItem"),icon:$i,submitText:l("common.save"),submitIcon:$i,loadingText:I.total>1?l("queue.savingProgress",{current:I.current,total:I.total}):l("common.saving")}})(),Se=He.icon,$e=He.submitIcon,Qe=Y&&(d||(ge?p!==null:!0));return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:H?void 0:s,children:a.jsx(_t,{className:"w-full max-w-lg max-h-[90vh] overflow-y-auto",onClick:ye=>ye.stopPropagation(),children:a.jsxs(Nt,{className:t==="reprint"?"":"p-0",children:[a.jsxs("div",{className:`flex items-center justify-between ${t==="reprint"?"mb-4":"p-4 border-b border-bambu-dark-tertiary"}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Se,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:He.title})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:s,disabled:H,children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:W,className:t==="reprint"?"":"p-4 space-y-4",children:[a.jsx("p",{className:`text-sm text-bambu-gray ${t==="reprint"?"mb-4":""}`,children:t==="reprint"?a.jsxs(a.Fragment,{children:["Send ",a.jsx("span",{className:"text-white",children:r})," to printer(s)"]}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"block text-bambu-gray mb-1",children:"Print Job"}),a.jsx("span",{className:"text-white font-medium truncate block",children:r})]})}),a.jsx(i$e,{plates:Z,isMultiPlate:ge,selectedPlate:p,onSelect:x}),a.jsx(r$e,{printers:ee||[],selectedPrinterIds:h,onMultiSelect:f,isLoading:ve,allowMultiple:!0,showInactive:t==="edit-queue-item",printerMappingResults:he.printerResults,filamentReqs:q,onAutoConfigurePrinter:he.autoConfigurePrinter,onUpdatePrinterConfig:he.updatePrinterConfig,assignmentMode:t==="reprint"?"printer":C,onAssignmentModeChange:t!=="reprint"?j:void 0,targetModel:E,onTargetModelChange:t!=="reprint"?P:void 0,targetLocation:U,onTargetLocationChange:t!=="reprint"?L:void 0,slicedForModel:Re}),Re&&C==="printer"&&h.length===1&&(()=>{const ye=ee?.find(we=>we.id===h[0]);return ye&&ye.model&&Re!==ye.model?a.jsxs("div",{className:"p-3 mb-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg flex items-center gap-2",children:[a.jsx(Mn,{className:"w-4 h-4 text-yellow-400 flex-shrink-0"}),a.jsxs("span",{className:"text-sm text-yellow-400",children:["File was sliced for ",Re,", but printing on ",ye.model]})]}):null})(),ce&&a.jsxs("div",{className:"flex items-start gap-2 p-3 mb-2 bg-orange-500/10 border border-orange-500/30 rounded-lg text-sm",children:[a.jsx(Bi,{className:"w-4 h-4 text-orange-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-orange-400",children:"Archive data unavailable. The source file may have been deleted. Filament mapping is disabled."})]}),Qe&&!ce&&h.length===1&&a.jsx(a$e,{printerId:Y,filamentReqs:q,manualMappings:N,onManualMappingChange:M,defaultExpanded:ne?.per_printer_mapping_expanded??!1}),(t==="reprint"||V>0||C==="model"&&E)&&a.jsx(o$e,{options:v,onChange:b}),t!=="reprint"&&a.jsx(l$e,{options:y,onChange:S,dateFormat:ne?.date_format||"system",timeFormat:ne?.time_format||"system"}),F.isError&&a.jsx("div",{className:"mb-4 p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:F.error?.message||"Failed to complete operation"}),a.jsxs("div",{className:`flex gap-3 ${t==="reprint"?"":"pt-2"}`,children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:s,className:"flex-1",disabled:H,children:"Cancel"}),a.jsx(Te,{type:"submit",disabled:!_e,className:"flex-1",children:me?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),He.loadingText]}):a.jsxs(a.Fragment,{children:[a.jsx($e,{className:"w-4 h-4"}),He.submitText]})})]})]})]})})})}function u$e({onClose:t,initialFiles:e}){const{t:n}=Ut(),r=Zt(),{showToast:i}=hn(),s=w.useRef(null),[o,l]=w.useState(()=>e?.filter(k=>k.name.endsWith(".3mf")).map(k=>({file:k,status:"pending"}))||[]),[c,u]=w.useState(!1),[d,h]=w.useState(null);w.useEffect(()=>{const k=T=>{T.key==="Escape"&&t()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t]);const f=ot({mutationFn:k=>se.uploadArchivesBulk(k),onSuccess:k=>{h(k),r.invalidateQueries({queryKey:["archives"]}),r.invalidateQueries({queryKey:["archiveStats"]}),l(T=>T.map(C=>{const j=k.results.find(P=>P.filename===C.file.name),E=k.errors.find(P=>P.filename===C.file.name);return j?{...C,status:"success",archiveId:j.id}:E?{...C,status:"error",error:E.error}:C})),k.failed===0?i(`${k.uploaded} file${k.uploaded!==1?"s":""} uploaded`):k.uploaded===0?i(`Failed to upload ${k.failed} file${k.failed!==1?"s":""}`,"error"):i(`${k.uploaded} uploaded, ${k.failed} failed`,"warning")},onError:()=>{l(k=>k.map(T=>({...T,status:"error",error:"Upload failed"}))),i("Upload failed","error")}}),p=w.useCallback(k=>{k.preventDefault(),u(!0)},[]),x=w.useCallback(k=>{k.preventDefault(),u(!1)},[]),v=w.useCallback(k=>{k.preventDefault(),u(!1);const T=Array.from(k.dataTransfer.files).filter(C=>C.name.endsWith(".3mf"));T.length>0&&l(C=>[...C,...T.map(j=>({file:j,status:"pending"}))])},[]),b=w.useCallback(k=>{const T=Array.from(k.target.files||[]).filter(C=>C.name.endsWith(".3mf"));T.length>0&&l(C=>[...C,...T.map(j=>({file:j,status:"pending"}))]),s.current&&(s.current.value="")},[]),y=w.useCallback(k=>{l(T=>T.filter((C,j)=>j!==k))},[]),S=()=>{if(o.length===0)return;const k=o.filter(T=>T.status==="pending");k.length!==0&&(l(T=>T.map(C=>C.status==="pending"?{...C,status:"uploading"}:C)),f.mutate(k.map(T=>T.file)))},N=o.filter(k=>k.status==="pending").length,M=f.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-2xl max-h-[90vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:n("uploadModal.title")}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsx("div",{className:"p-4",children:a.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:p,onDragLeave:x,onDrop:v,children:[a.jsx(sa,{className:"w-12 h-12 mx-auto mb-4 text-bambu-gray"}),a.jsx("p",{className:"text-white mb-2",children:n("uploadModal.dragDrop")}),a.jsx("p",{className:"text-bambu-gray text-sm mb-4",children:n("uploadModal.or")}),a.jsx(Te,{variant:"secondary",onClick:()=>s.current?.click(),disabled:M,children:n("uploadModal.browseFiles")}),a.jsx("input",{ref:s,type:"file",accept:".3mf",multiple:!0,className:"hidden",onChange:b})]})}),a.jsx("div",{className:"px-4 pb-4",children:a.jsx("p",{className:"text-xs text-bambu-gray",children:n("uploadModal.extractionInfo")})}),o.length>0&&a.jsx("div",{className:"px-4 pb-4 max-h-60 overflow-y-auto",children:a.jsx("div",{className:"space-y-2",children:o.map((k,T)=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx(YC,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:"flex-1 text-white text-sm truncate",children:k.file.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[(k.file.size/(1024*1024)).toFixed(1)," MB"]}),k.status==="pending"&&a.jsx("button",{onClick:()=>y(T),className:"text-bambu-gray hover:text-red-400 transition-colors",disabled:M,children:a.jsx(Rt,{className:"w-4 h-4"})}),k.status==="uploading"&&a.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"}),k.status==="success"&&a.jsx(gr,{className:"w-4 h-4 text-bambu-green"}),k.status==="error"&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-xs text-red-400",children:k.error}),a.jsx(Bi,{className:"w-4 h-4 text-red-400"})]})]},`${k.file.name}-${T}`))})}),d&&a.jsx("div",{className:"px-4 pb-4",children:a.jsx("div",{className:"p-3 bg-bambu-dark rounded-lg",children:a.jsxs("p",{className:"text-sm text-white",children:[a.jsx("span",{className:"text-bambu-green",children:d.uploaded})," ",n("uploadModal.uploaded"),d.failed>0&&a.jsxs(a.Fragment,{children:[", ",a.jsx("span",{className:"text-red-400",children:d.failed})," ",n("uploadModal.failed")]})]})})}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Te,{variant:"secondary",onClick:t,className:"flex-1",children:n(d?"common.close":"common.cancel")}),!d&&a.jsx(Te,{onClick:S,disabled:N===0||M,className:"flex-1",children:M?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),n("uploadModal.uploading")]}):a.jsxs(a.Fragment,{children:[a.jsx(sa,{className:"w-4 h-4"}),n("uploadModal.upload")," ",N>0&&`(${N})`]})})]})]})})})}const d$e=["adhesionFailure","spaghettiDetached","layerShift","cloggedNozzle","filamentRunout","warping","stringing","underExtrusion","powerFailure","userCancelled","other"],h$e=["completed","failed","aborted","printing"];function lne({archive:t,onClose:e,existingTags:n=[]}){const{t:r}=Ut();w.useEffect(()=>{const ue=le=>{le.key==="Escape"&&e()};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[e]);const i=Zt(),[s,o]=w.useState(t.print_name||""),[l,c]=w.useState(t.printer_id),[u,d]=w.useState(t.project_id??null),[h,f]=w.useState(t.notes||""),[p,x]=w.useState(t.tags||""),[v,b]=w.useState(t.failure_reason||""),[y,S]=w.useState(t.status),[N,M]=w.useState(t.quantity??1),[k,T]=w.useState(t.photos||[]),[C,j]=w.useState(t.external_url||""),[E,P]=w.useState(!1),[U,L]=w.useState(!1),B=w.useRef(null),D=w.useRef(null),H=w.useRef(null),{data:G}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:I}=et({queryKey:["projects"],queryFn:()=>se.getProjects()}),{data:K}=et({queryKey:["tags"],queryFn:se.getTags,enabled:n.length===0}),Q=n.length>0?n:K?.map(ue=>ue.name)||[],ae=p.split(",").map(ue=>ue.trim()).filter(Boolean),V=p.includes(",")?p.substring(p.lastIndexOf(",")+1).trim().toLowerCase():p.trim().toLowerCase(),Y=Q.filter(ue=>!ae.includes(ue)&&(V===""||ue.toLowerCase().includes(V))),ne=ue=>{let le;if(V&&!Q.includes(V)?le=p.includes(",")?p.substring(0,p.lastIndexOf(",")).split(",").map(Ne=>Ne.trim()).filter(Boolean):[]:le=ae,!le.includes(ue)){const Ne=[...le,ue].join(", ");x(Ne)}H.current!==null&&clearTimeout(H.current),B.current?.focus()},ee=ue=>{const le=ae.filter(Ne=>Ne!==ue).join(", ");x(le)},ve=ot({mutationFn:ue=>se.updateArchive(t.id,ue),onSuccess:()=>{i.invalidateQueries({queryKey:["archives"]}),i.invalidateQueries({queryKey:["projects"]}),e()}}),fe=async ue=>{const le=ue.target.files?.[0];if(le){P(!0);try{const Ne=await se.uploadArchivePhoto(t.id,le);T(Ne.photos),i.invalidateQueries({queryKey:["archives"]})}catch(Ne){console.error("Failed to upload photo:",Ne)}finally{P(!1),D.current&&(D.current.value="")}}},de=async ue=>{try{const le=await se.deleteArchivePhoto(t.id,ue);T(le.photos||[]),i.invalidateQueries({queryKey:["archives"]})}catch(le){console.error("Failed to delete photo:",le)}},Re=ue=>{ue.preventDefault();const le={print_name:s||void 0,printer_id:l,project_id:u,notes:h||void 0,tags:p||void 0,quantity:N,external_url:C||null};y!==t.status&&(le.status=y),y==="failed"||y==="aborted"?le.failure_reason=v||void 0:(t.status==="failed"||t.status==="aborted")&&(le.failure_reason=null),ve.mutate(le)};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:ue=>ue.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r("editArchive.title")}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Re,className:"p-6 space-y-4 overflow-y-auto flex-1",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.name")}),a.jsx("input",{type:"text",value:s,onChange:ue=>o(ue.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")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.printer")}),a.jsxs("select",{value:l??"",onChange:ue=>c(ue.target.value?Number(ue.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noPrinter")}),G?.map(ue=>a.jsx("option",{value:ue.id,children:ue.name},ue.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(ys,{className:"w-4 h-4 inline mr-1"}),r("editArchive.project")]}),a.jsxs("select",{value:u??"",onChange:ue=>d(ue.target.value?Number(ue.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.noProject")}),I?.map(ue=>a.jsx("option",{value:ue.id,children:ue.name},ue.id))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(cme,{className:"w-4 h-4 inline mr-1"}),r("editArchive.itemsPrinted")]}),a.jsx("input",{type:"number",min:1,value:N,onChange:ue=>M(Math.max(1,parseInt(ue.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"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.itemsPrintedHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.notes")}),a.jsx("textarea",{value:h,onChange:ue=>f(ue.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")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Vb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.externalLink")]}),a.jsx("input",{type:"url",value:C,onChange:ue=>j(ue.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/..."}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:r("editArchive.externalLinkHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.tags")}),ae.length>0&&a.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:ae.map(ue=>a.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-bambu-dark-tertiary rounded text-sm text-white",children:[a.jsx(Gh,{className:"w-3 h-3"}),ue,a.jsx("button",{type:"button",onClick:()=>ee(ue),className:"ml-0.5 text-bambu-gray hover:text-white",children:a.jsx(Rt,{className:"w-3 h-3"})})]},ue))}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{ref:B,type:"text",value:p,onChange:ue=>x(ue.target.value),onFocus:()=>{H.current!==null&&clearTimeout(H.current),L(!0)},onBlur:()=>{H.current=window.setTimeout(()=>L(!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:ae.length>0?r("editArchive.addMoreTags"):r("editArchive.tagsPlaceholder")}),U&&Y.length>0&&a.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:[a.jsxs("div",{className:"p-2 text-xs text-bambu-gray border-b border-bambu-dark-tertiary",children:[V?r("editArchive.matchingTags",{query:V}):r("editArchive.existingTags")," ",r("editArchive.clickToAdd")]}),a.jsx("div",{className:"p-2 flex flex-wrap gap-1.5",children:Y.map(ue=>a.jsx("button",{type:"button",onClick:()=>ne(ue),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:ue},ue))})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.status")}),a.jsx("select",{value:y,onChange:ue=>{S(ue.target.value),ue.target.value==="completed"&&b("")},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:h$e.map(ue=>a.jsx("option",{value:ue,children:r(`editArchive.statuses.${ue}`)},ue))})]}),(y==="failed"||y==="aborted")&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:r("editArchive.failureReason")}),a.jsxs("select",{value:v,onChange:ue=>b(ue.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:r("editArchive.selectReason")}),d$e.map(ue=>a.jsx("option",{value:r(`editArchive.failureReasons.${ue}`),children:r(`editArchive.failureReasons.${ue}`)},ue))]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(cb,{className:"w-4 h-4 inline mr-1"}),r("editArchive.photos")]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-2",children:[k.map(ue=>a.jsxs("div",{className:"relative group",children:[a.jsx("img",{src:se.getArchivePhotoUrl(t.id,ue),alt:r("editArchive.printResult"),className:"w-20 h-20 object-cover rounded-lg border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:()=>de(ue),className:"absolute -top-1 -right-1 p-1 bg-red-500 rounded-full opacity-0 group-hover:opacity-100 transition-opacity",children:a.jsx(en,{className:"w-3 h-3 text-white"})})]},ue)),a.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:[a.jsx("input",{ref:D,type:"file",accept:"image/jpeg,image/png,image/webp",onChange:fe,className:"hidden",disabled:E}),E?a.jsx(it,{className:"w-6 h-6 text-bambu-gray animate-spin"}):a.jsx(rr,{className:"w-6 h-6 text-bambu-gray"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:r("editArchive.photosHelp")})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:r("common.cancel")}),a.jsxs(Te,{type:"submit",disabled:ve.isPending,className:"flex-1",children:[a.jsx(xs,{className:"w-4 h-4"}),ve.isPending?r("common.saving"):r("common.save")]})]})]})]})})}function cne({x:t,y:e,items:n,onClose:r}){const i=w.useRef(null),[s,o]=w.useState(null),l=w.useRef(null),[c,u]=w.useState({x:t,y:e,visible:!1}),[d,h]=w.useState(!1),[f,p]=w.useState({});w.useEffect(()=>{const b=N=>{i.current&&!i.current.contains(N.target)&&r()},y=N=>{N.key==="Escape"&&r()},S=()=>{r()};return document.addEventListener("mousedown",b),document.addEventListener("keydown",y),document.addEventListener("scroll",S,!0),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",y),document.removeEventListener("scroll",S,!0),l.current&&clearTimeout(l.current)}},[r]),w.useLayoutEffect(()=>{if(i.current){i.current.style.visibility="hidden",i.current.style.display="block";const b=i.current.getBoundingClientRect(),y=window.innerWidth,S=window.innerHeight,N=8;let M=t,k=e;t+b.width>y-N&&(M=Math.max(N,y-b.width-N)),MS-N&&(k=Math.max(N,S-b.height-N)),kT),u({x:M,y:k,visible:!0})}},[t,e]);const x=(b,y)=>{l.current&&(clearTimeout(l.current),l.current=null);const S=y.getBoundingClientRect(),N=window.innerHeight,M=300,C=N-S.top-8M;p(j=>({...j,[b]:C?"bottom":"top"})),o(b)},v=()=>{l.current=window.setTimeout(()=>{o(null)},150)};return a.jsx("div",{ref:i,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((b,y)=>{if(b.divider)return a.jsx("div",{className:"my-1 border-t border-bambu-dark-tertiary"},y);const S=b.submenu&&b.submenu.length>0;return a.jsxs("div",{className:"relative",onMouseEnter:N=>S&&x(y,N.currentTarget),onMouseLeave:()=>S&&v(),children:[a.jsxs("button",{onMouseEnter:N=>S&&x(y,N.currentTarget.parentElement),onClick:()=>{S?o(s===y?null:y):b.disabled||(b.onClick(),r())},disabled:b.disabled,title:b.title,className:`w-full flex items-center gap-2 px-3 py-2 text-sm text-left transition-colors ${b.disabled?"text-bambu-gray cursor-not-allowed":b.danger?"text-red-400 hover:bg-red-400/10":"text-white hover:bg-bambu-dark-tertiary"} ${S&&s===y?"bg-bambu-dark-tertiary":""}`,children:[b.icon&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:b.icon}),a.jsx("span",{className:"flex-1",children:b.label}),S&&a.jsx(Fa,{className:"w-4 h-4 text-bambu-gray"})]}),S&&s===y&&a.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] ${d?"right-full mr-1":"left-full ml-1"} ${f[y]==="bottom"?"bottom-0":"top-0"}`,onMouseEnter:()=>{l.current&&(clearTimeout(l.current),l.current=null)},onMouseLeave:()=>v(),children:b.submenu.map((N,M)=>a.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&&a.jsx("span",{className:"w-4 h-4 flex-shrink-0 flex items-center justify-center",children:N.icon}),N.label]},M))})]},y)})})}function m$e({selectedIds:t,existingTags:e,onClose:n}){const r=Zt(),{showToast:i}=hn(),[s,o]=w.useState(""),[l,c]=w.useState(new Set),[u,d]=w.useState("add");w.useEffect(()=>{const v=b=>{b.key==="Escape"&&n()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[n]);const h=ot({mutationFn:async()=>{const v=Array.from(l);let b=0;for(const y of t)try{const S=await se.getArchive(y),N=S.tags?S.tags.split(",").map(k=>k.trim()).filter(Boolean):[];let M;u==="add"?M=[...new Set([...N,...v])]:M=N.filter(k=>!l.has(k)),await se.updateArchive(y,{tags:M.join(", ")}),b++}catch(S){throw console.error(`Failed to update archive ${y}:`,S),new Error(`Failed on archive ${y}: ${S instanceof Error?S.message:"Unknown error"}`)}return{count:b,mode:u,tags:v}},onSuccess:({count:v,mode:b,tags:y})=>{r.invalidateQueries({queryKey:["archives"]}),i(`${b==="add"?"Added":"Removed"} ${y.length} tag${y.length!==1?"s":""} ${b==="add"?"to":"from"} ${v} archive${v!==1?"s":""}`),n()},onError:v=>{i(v.message||"Failed to update tags","error")}}),f=v=>{c(b=>{const y=new Set(b);return y.has(v)?y.delete(v):y.add(v),y})},p=()=>{s.trim()&&!l.has(s.trim())&&(c(v=>new Set([...v,s.trim()])),o(""))},x=v=>{v.key==="Enter"&&(v.preventDefault(),p())};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-md",children:a.jsxs(Nt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Gh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:u==="add"?"Add Tags":"Remove Tags"})]}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:[u==="add"?"Add":"Remove"," tags for ",t.length," selected archive",t.length!==1?"s":""]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Te,{size:"sm",variant:u==="add"?"primary":"secondary",onClick:()=>d("add"),children:"Add Tags"}),a.jsx(Te,{size:"sm",variant:u==="remove"?"primary":"secondary",onClick:()=>d("remove"),children:"Remove Tags"})]}),u==="add"&&a.jsxs("div",{className:"flex gap-2",children:[a.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}),a.jsx(Te,{size:"sm",variant:"secondary",onClick:p,disabled:!s.trim(),children:a.jsx(rr,{className:"w-4 h-4"})})]}),e.length>0&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Existing tags:"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:e.map(v=>a.jsx("button",{onClick:()=>f(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&&a.jsxs("div",{children:[a.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Tags to ",u==="add"?"add":"remove",":"]}),a.jsx("div",{className:"flex flex-wrap gap-2",children:Array.from(l).map(v=>a.jsxs("span",{className:`px-2 py-1 rounded text-sm flex items-center gap-1 ${u==="add"?"bg-green-500/20 text-green-400":"bg-red-500/20 text-red-400"}`,children:[v,a.jsx("button",{onClick:()=>f(v),className:"hover:opacity-70",children:a.jsx(Rt,{className:"w-3 h-3"})})]},v))})]})]}),a.jsxs("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary",children:[a.jsx(Te,{variant:"secondary",onClick:n,className:"flex-1",children:"Cancel"}),a.jsx(Te,{onClick:()=>h.mutate(),disabled:l.size===0||h.isPending,className:"flex-1",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Processing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Gh,{className:"w-4 h-4"}),u==="add"?"Add Tags":"Remove Tags"]})})]})]})})})}function f$e({selectedIds:t,onClose:e}){const n=Zt(),{showToast:r}=hn(),{data:i,isLoading:s}=et({queryKey:["projects"],queryFn:()=>se.getProjects()});w.useEffect(()=>{const d=h=>{h.key==="Escape"&&e()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e]);const o=()=>{n.invalidateQueries({queryKey:["archives"]}),n.invalidateQueries({queryKey:["projects"]}),n.invalidateQueries({queryKey:["project"]}),n.invalidateQueries({queryKey:["project-archives"]})},l=ot({mutationFn:async d=>(await se.addArchivesToProject(d,t),d),onSuccess:d=>{const h=i?.find(f=>f.id===d);o(),r(`Added ${t.length} archive${t.length!==1?"s":""} to "${h?.name}"`),e()},onError:()=>{r("Failed to assign project","error")}}),c=ot({mutationFn:async()=>{for(const d of t)await se.updateArchive(d,{project_id:null});return t.length},onSuccess:d=>{o(),r(`Removed ${d} archive${d!==1?"s":""} from project`),e()},onError:()=>{r("Failed to remove from project","error")}}),u=l.isPending||c.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-md max-h-[80vh] flex flex-col",children:a.jsxs(Nt,{className:"p-0 flex flex-col min-h-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ys,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:"Assign to Project"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",disabled:u,children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-4 space-y-3 overflow-y-auto min-h-0",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Assign ",t.length," selected archive",t.length!==1?"s":""," to a project"]}),s?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-gray"})}):a.jsxs("div",{className:"space-y-2",children:[a.jsxs("button",{onClick:()=>c.mutate(),disabled:u,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:[a.jsx("div",{className:"w-8 h-8 rounded-full bg-red-500/20 flex items-center justify-center shrink-0",children:a.jsx(ha,{className:"w-4 h-4 text-red-400"})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium",children:"Remove from project"}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",children:"Clear project assignment"})]}),c.isPending&&a.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]}),i&&i.length>0&&a.jsxs("div",{className:"flex items-center gap-2 py-2",children:[a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"}),a.jsx("span",{className:"text-xs text-bambu-gray",children:"or assign to"}),a.jsx("div",{className:"flex-1 h-px bg-bambu-dark-tertiary"})]}),i?.map(d=>a.jsxs("button",{onClick:()=>l.mutate(d.id),disabled:u,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:[a.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{backgroundColor:d.color?`${d.color}20`:"rgb(var(--bambu-green) / 0.2)"},children:a.jsx(ys,{className:"w-4 h-4",style:{color:d.color||"rgb(var(--bambu-green))"}})}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:d.name}),a.jsxs("p",{className:"text-sm text-bambu-gray truncate",children:[d.archive_count," archive",d.archive_count!==1?"s":"",d.status&&` • ${d.status}`]})]}),l.isPending&&l.variables===d.id&&a.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray shrink-0"})]},d.id)),(!i||i.length===0)&&a.jsx("p",{className:"text-center text-bambu-gray py-4",children:"No projects yet. Create one from the Projects page."})]})]}),a.jsx("div",{className:"flex gap-3 p-4 border-t border-bambu-dark-tertiary shrink-0",children:a.jsx(Te,{variant:"secondary",onClick:e,className:"flex-1",disabled:u,children:"Cancel"})})]})})})}function p$e(t,e){return new Date(t,e+1,0).getDate()}function g$e(t,e){return new Date(t,e,1).getDay()}const b$e=["January","February","March","April","May","June","July","August","September","October","November","December"],x$e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function y$e({archives:t,onArchiveClick:e,highlightedArchiveId:n}){const r=new Date,[i,s]=w.useState(r.getMonth()),[o,l]=w.useState(r.getFullYear()),[c,u]=w.useState(null),[d,h]=w.useState(null),f=w.useMemo(()=>{const k=new Map;return t.forEach(T=>{const C=Ji(T.completed_at||T.created_at)||new Date,j=`${C.getFullYear()}-${String(C.getMonth()+1).padStart(2,"0")}-${String(C.getDate()).padStart(2,"0")}`,E=k.get(j)||[];E.push(T),k.set(j,E)}),k},[t]),p=p$e(o,i),x=g$e(o,i),v=()=>{i===0?(s(11),l(o-1)):s(i-1)},b=()=>{i===11?(s(0),l(o+1)):s(i+1)},y=()=>{s(r.getMonth()),l(r.getFullYear())},S=[];for(let k=0;k{k!==c&&h(null),u(k)};return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsx("button",{onClick:v,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Fc,{className:"w-5 h-5 text-bambu-gray"})}),a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:[b$e[i]," ",o]}),a.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"})]}),a.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:a.jsx(Fa,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:x$e.map(k=>a.jsx("div",{className:"text-center text-xs text-bambu-gray py-2",children:k},k))}),a.jsx("div",{className:"grid grid-cols-7 gap-1",children:S.map((k,T)=>{if(k===null)return a.jsx("div",{className:"aspect-square"},`empty-${T}`);const C=`${o}-${String(i+1).padStart(2,"0")}-${String(k).padStart(2,"0")}`,j=f.get(C)||[],E=j.length>0,P=k===r.getDate()&&i===r.getMonth()&&o===r.getFullYear(),U=C===c,L=j.filter(D=>D.status==="completed").length,B=j.filter(D=>D.status==="failed").length;return a.jsxs("button",{onClick:()=>M(U?null:C),className:`aspect-square rounded-lg p-1 flex flex-col items-center justify-center transition-colors relative ${U?"bg-bambu-green text-white":P?"bg-bambu-green/20 text-white ring-2 ring-bambu-green":E?"bg-bambu-dark-tertiary hover:bg-bambu-dark-tertiary/70 text-white":"hover:bg-bambu-dark-tertiary/50 text-bambu-gray"}`,children:[a.jsx("span",{className:`text-sm font-medium ${P&&!U?"text-bambu-green":""}`,children:k}),E&&a.jsxs("div",{className:"absolute bottom-1 left-1/2 -translate-x-1/2 flex items-center gap-1",children:[a.jsx("div",{className:`w-2 h-2 rounded-full ${B>0&&L===0?"bg-red-400":B>0?"bg-yellow-400":"bg-green-400"}`}),a.jsx("span",{className:"text-xs font-medium",children:j.length})]})]},k)})}),a.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-white",children:t.filter(k=>{const T=new Date(k.completed_at||k.created_at);return T.getMonth()===i&&T.getFullYear()===o}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Prints this month"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-green-400",children:t.filter(k=>{const T=new Date(k.completed_at||k.created_at);return T.getMonth()===i&&T.getFullYear()===o&&k.status==="completed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Successful"})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-2xl font-bold text-red-400",children:t.filter(k=>{const T=new Date(k.completed_at||k.created_at);return T.getMonth()===i&&T.getFullYear()===o&&k.status==="failed"}).length}),a.jsx("div",{className:"text-xs text-bambu-gray",children:"Failed"})]})]})})]}),a.jsx("div",{className:"lg:w-80 bg-bambu-dark rounded-xl p-4",children:c?a.jsxs(a.Fragment,{children:[a.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?a.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:N.map(k=>{const T=k.id===d||k.id===n;return a.jsxs("button",{onClick:()=>{h(k.id),e?.(k)},className:`w-full flex items-center gap-3 p-2 rounded-lg transition-colors text-left ${T?"":"hover:bg-bambu-dark-tertiary"}`,style:T?{outline:"4px solid #facc15",outlineOffset:"2px"}:void 0,children:[k.thumbnail_path?a.jsx("img",{src:se.getArchiveThumbnail(k.id),alt:"",className:"w-12 h-12 rounded object-cover"}):a.jsx("div",{className:"w-12 h-12 rounded bg-bambu-dark-tertiary flex items-center justify-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"3MF"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-sm text-white truncate",children:k.print_name||k.filename}),a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:k.status==="failed"?"text-red-400":"text-green-400",children:k.status==="failed"?"Failed":"Completed"}),k.filament_color&&a.jsx("div",{className:"flex gap-0.5",children:k.filament_color.split(",").map((C,j)=>a.jsx("div",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:C}},j))})]})]})]},k.id)})}):a.jsx("p",{className:"text-sm text-bambu-gray",children:"No prints on this day"})]}):a.jsx("div",{className:"text-center py-8",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Select a day to see prints"})})})]})}function une({archiveId:t,archiveName:e,onClose:n}){const r=se.getArchiveQRCodeUrl(t,300);w.useEffect(()=>{const s=o=>{o.key==="Escape"&&n()};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[n]);const i=()=>{const s=document.createElement("a");s.href=r,s.download=`${e}_qrcode.png`,s.click()};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:n,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-sm",onClick:s=>s.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:"QR Code"}),a.jsx("button",{onClick:n,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("div",{className:"p-6 flex flex-col items-center",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4 text-center truncate max-w-full",children:e}),a.jsx("div",{className:"bg-white p-4 rounded-lg mb-4",children:a.jsx("img",{src:r,alt:"QR Code",className:"w-64 h-64"})}),a.jsx("p",{className:"text-xs text-bambu-gray mb-4 text-center",children:"Scan to open this archive"}),a.jsxs(Te,{onClick:i,className:"w-full",children:[a.jsx(ui,{className:"w-4 h-4"}),"Download QR Code"]})]})]})})}function dne({archiveId:t,archiveName:e,photos:n,onClose:r,onDelete:i}){const[s,o]=w.useState(0),[l,c]=w.useState(!1);if(w.useEffect(()=>{const p=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",p),()=>window.removeEventListener("keydown",p)},[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 u=n[s],d=se.getArchivePhotoUrl(t,u),h=()=>{const p=document.createElement("a");p.href=d,p.download=`${e}_photo_${s+1}.jpg`,p.click()},f=()=>{i&&c(!0)};return a.jsxs("div",{className:"fixed inset-0 bg-black/90 flex items-center justify-center z-50",onClick:r,children:[a.jsxs("div",{className:"relative w-full h-full flex flex-col",onClick:p=>p.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 bg-black/50",children:[a.jsxs("div",{children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:e}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Photo ",s+1," of ",n.length]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Te,{variant:"secondary",size:"sm",onClick:h,children:[a.jsx(ui,{className:"w-4 h-4"}),"Download"]}),i&&a.jsx(Te,{variant:"secondary",size:"sm",onClick:f,className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})}),a.jsx("button",{onClick:r,className:"p-2 text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-6 h-6"})})]})]}),a.jsxs("div",{className:"flex-1 min-h-0 flex items-center justify-center p-4 relative overflow-hidden",children:[s>0&&a.jsx("button",{onClick:()=>o(p=>p-1),className:"absolute left-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Fc,{className:"w-8 h-8 text-white"})}),a.jsx("img",{src:d,alt:`Photo ${s+1}`,className:"max-w-full max-h-full object-contain rounded-lg",style:{maxHeight:"calc(100vh - 200px)"}}),so(p=>p+1),className:"absolute right-4 z-10 p-3 bg-black/50 hover:bg-black/70 rounded-full transition-colors",children:a.jsx(Fa,{className:"w-8 h-8 text-white"})})]}),n.length>1&&a.jsx("div",{className:"flex justify-center gap-2 p-4 bg-black/50",children:n.map((p,x)=>a.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:a.jsx("img",{src:se.getArchivePhotoUrl(t,p),alt:`Thumbnail ${x+1}`,className:"w-full h-full object-cover"})},p))})]}),l&&a.jsx(Pn,{title:"Delete Photo",message:"Delete this photo? This cannot be undone.",confirmText:"Delete",variant:"danger",onConfirm:()=>{i?.(u),c(!1)},onCancel:()=>c(!1)})]})}function Ya(t){this.content=t}Ya.prototype={constructor:Ya,find:function(t){for(var e=0;e>1}};Ya.from=function(t){if(t instanceof Ya)return t;var e=[];if(t)for(var n in t)e.push(n,t[n]);return new Ya(e)};function hne(t,e,n){for(let r=0;;r++){if(r==t.childCount||r==e.childCount)return t.childCount==e.childCount?null:n;let i=t.child(r),s=e.child(r);if(i==s){n+=i.nodeSize;continue}if(!i.sameMarkup(s))return n;if(i.isText&&i.text!=s.text){for(let o=0;i.text[o]==s.text[o];o++)n++;return n}if(i.content.size||s.content.size){let o=hne(i.content,s.content,n+1);if(o!=null)return o}n+=i.nodeSize}}function mne(t,e,n,r){for(let i=t.childCount,s=e.childCount;;){if(i==0||s==0)return i==s?null:{a:n,b:r};let o=t.child(--i),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 u=0,d=Math.min(o.text.length,l.text.length);for(;ue&&r(c,i+l,s||null,o)!==!1&&c.content.size){let d=l+1;c.nodesBetween(Math.max(0,e-d),Math.min(c.content.size,n-d),r,i+d)}l=u}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,n,r,i){let s="",o=!0;return this.nodesBetween(e,n,(l,c)=>{let u=l.isText?l.text.slice(Math.max(e,c)-c,n-c):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&u||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=u},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let n=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(n.isText&&n.sameMarkup(r)&&(i[i.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),i+=l.nodeSize),o=c}return new Tt(r,i)}cutByIndex(e,n){return e==n?Tt.empty:e==0&&n==this.content.length?this:new Tt(this.content.slice(e,n))}replaceChild(e,n){let r=this.content[e];if(r==n)return this;let i=this.content.slice(),s=this.size+n.nodeSize-r.nodeSize;return i[e]=n,new Tt(i,s)}addToStart(e){return new Tt([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Tt(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 i=this.child(n),s=r+i.nodeSize;if(s>=e)return s==e?AS(n+1,s):AS(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 Tt.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Tt(n.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Tt.empty;let n,r=0;for(let i=0;ithis.type.rank&&(n||(n=e.slice(0,i)),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-i.type.rank),n}};Hr.none=[];class KN extends Error{}class Bt{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=pne(this.content,e+this.openStart,n);return r&&new Bt(r,this.openStart,this.openEnd)}removeBetween(e,n){return new Bt(fne(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 Bt.empty;let r=n.openStart||0,i=n.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Bt(Tt.fromJSON(e,n.content),r,i)}static maxOpen(e,n=!0){let r=0,i=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)i++;return new Bt(e,r,i)}}Bt.empty=new Bt(Tt.empty,0,0);function fne(t,e,n){let{index:r,offset:i}=t.findIndex(e),s=t.maybeChild(r),{index:o,offset:l}=t.findIndex(n);if(i==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(fne(s.content,e-i-1,n-i-1)))}function pne(t,e,n,r){let{index:i,offset:s}=t.findIndex(e),o=t.maybeChild(i);if(s==e||o.isText)return r&&!r.canReplace(i,i,n)?null:t.cut(0,e).append(n).append(t.cut(e));let l=pne(o.content,e-s-1,n,o);return l&&t.replaceChild(i,o.copy(l))}function v$e(t,e,n){if(n.openStart>t.depth)throw new KN("Inserted content deeper than insertion position");if(t.depth-n.openStart!=e.depth-n.openEnd)throw new KN("Inconsistent open depths");return gne(t,e,n,0)}function gne(t,e,n,r){let i=t.index(r),s=t.node(r);if(i==e.index(r)&&r=0&&t.isText&&t.sameMarkup(e[n])?e[n]=t.withText(e[n].text+t.text):e.push(t)}function Zy(t,e,n,r){let i=(e||t).node(n),s=0,o=e?e.index(n):i.childCount;t&&(s=t.index(n),t.depth>n?s++:t.textOffset&&(Nf(t.nodeAfter,r),s++));for(let l=s;li&&NR(t,e,i+1),o=r.depth>i&&NR(n,r,i+1),l=[];return Zy(null,t,i,l),s&&o&&e.index(i)==n.index(i)?(bne(s,o),Nf(Cf(s,xne(t,e,n,r,i+1)),l)):(s&&Nf(Cf(s,XN(t,e,i+1)),l),Zy(e,n,i,l),o&&Nf(Cf(o,XN(n,r,i+1)),l)),Zy(r,null,i,l),new Tt(l)}function XN(t,e,n){let r=[];if(Zy(null,t,n,r),t.depth>n){let i=NR(t,e,n+1);Nf(Cf(i,XN(t,e,n+1)),r)}return Zy(e,null,n,r),new Tt(r)}function w$e(t,e){let n=e.depth-t.openStart,i=e.node(n).copy(t.content);for(let s=n-1;s>=0;s--)i=e.node(s).copy(Tt.from(i));return{start:i.resolveNoCache(t.openStart+n),end:i.resolveNoCache(i.content.size-t.openEnd-n)}}class W0{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],i=e.child(n);return r?e.child(n).cut(r):i}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],i=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 YN(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=[],i=0,s=n;for(let o=e;;){let{index:l,offset:c}=o.content.findIndex(s),u=s-c;if(r.push(o,l,i+c),!u||(o=o.child(l),o.isText))break;s=u-1,i+=c+1}return new W0(n,r,s)}static resolveCached(e,n){let r=c9.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,n,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}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()+")"),yne(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=Tt.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,n);if(!l||!l.validEnd)return!1;for(let c=i;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 i=Tt.fromJSON(e,n.content),s=e.nodeType(n.type).create(n.attrs,i,r);return s.type.checkAttrs(s.attrs),s}};Bh.prototype.text=void 0;class QN extends Bh{constructor(e,n,r,i){if(super(e,n,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):yne(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 QN(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new QN(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 yne(t,e){for(let n=t.length-1;n>=0;n--)e=t[n].type.name+"("+e+")";return e}class Qf{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,n){let r=new C$e(e,n);if(r.next==null)return Qf.empty;let i=vne(r);r.next&&r.err("Unexpected trailing text");let s=j$e(P$e(i));return D$e(s,r),s}matchType(e){for(let n=0;nu.createAndFill()));for(let u=0;u=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 i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` `)}}Qf.empty=new Qf(!0);class C$e{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 vne(t){let e=[];do e.push(k$e(t));while(t.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function k$e(t){let e=[];do e.push(M$e(t));while(t.next&&t.next!=")"&&t.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function M$e(t){let e=E$e(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=A$e(t,e);else break;return e}function u9(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function A$e(t,e){let n=u9(t),r=n;return t.eat(",")&&(t.next!="}"?r=u9(t):r=-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:e}}function T$e(t,e){let n=t.nodeTypes,r=n[e];if(r)return[r];let i=[];for(let s in n){let o=n[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&t.err("No node type or group '"+e+"' found"),i}function E$e(t){if(t.eat("(")){let e=vne(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=T$e(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 P$e(t){let e=[[]];return i(s(t,0),n()),e;function n(){return e.push([])-1}function r(o,l,c){let u={term:c,to:l};return e[o].push(u),u}function i(o,l){o.forEach(c=>c.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((c,u)=>c.concat(s(u,l)),[]);if(o.type=="seq")for(let c=0;;c++){let u=s(o.exprs[c],l);if(c==o.exprs.length-1)return u;i(u,l=n())}else if(o.type=="star"){let c=n();return r(l,c),i(s(o.expr,c),c),[r(c)]}else if(o.type=="plus"){let c=n();return i(s(o.expr,l),c),i(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 u=0;u{t[o].forEach(({term:l,to:c})=>{if(!l)return;let u;for(let d=0;d{u||i.push([l,u=[]]),u.indexOf(d)==-1&&u.push(d)})})});let s=e[r.join(",")]=new Qf(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:Sne(this.attrs,e)}create(e=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Bh(this,this.computeAttrs(e),Tt.from(n),Hr.setFrom(r))}createChecked(e=null,n,r){return n=Tt.from(n),this.checkContent(n),new Bh(this,this.computeAttrs(e),n,Hr.setFrom(r))}createAndFill(e=null,n,r){if(e=this.computeAttrs(e),n=Tt.from(n),n.size){let o=this.contentMatch.fillBefore(n);if(!o)return null;n=o.append(n)}let i=this.contentMatch.matchFragment(n),s=i&&i.fillBefore(Tt.empty,!0);return s?new Bh(this,e,n.append(s),Hr.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 kne(s,n,o));let i=n.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");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 R$e(t,e,n){let r=n.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${t}, got ${s}`)}}class F$e{constructor(e,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?R$e(e,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class fM{constructor(e,n,r,i){this.name=e,this.rank=n,this.schema=r,this.spec=i,this.attrs=Cne(e,i.attrs),this.excluded=null;let s=_ne(this.attrs);this.instance=s?new Hr(this,s):null}create(e=null){return!e&&this.instance?this.instance:new Hr(this,Sne(this.attrs,e))}static compile(e,n){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new fM(s,i++,n,o)),r}removeFromSet(e){for(var n=0;n-1}}class Mne{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let i in e)n[i]=e[i];n.nodes=Ya.from(e.nodes),n.marks=Ya.from(e.marks||{}),this.nodes=h9.compile(this.spec.nodes,this),this.marks=fM.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Qf.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?m9(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:m9(this,o.split(" "))}this.nodeFromJSON=i=>Bh.fromJSON(this,i),this.markFromJSON=i=>Hr.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,n=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof h9){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,i)}text(e,n){let r=this.nodes.text;return new QN(r,r.defaultAttrs,e,Hr.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 m9(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 L$e(t){return t.tag!=null}function O$e(t){return t.style!=null}let Jy=class kR{constructor(e,n){this.schema=e,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(i=>{if(L$e(i))this.tags.push(i);else if(O$e(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,n={}){let r=new p9(this,n,!1);return r.addAll(e,Hr.none,n.from,n.to),r.finish()}parseSlice(e,n={}){let r=new p9(this,n,!0);return r.addAll(e,Hr.none,n.from,n.to),Bt.maxOpen(r.finish())}matchTag(e,n,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.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(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=g9(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=g9(o)),o.node||o.ignore||o.mark||(o.node=i)})}return n}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new kR(e,kR.schemaRules(e)))}};const Ane={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},I$e={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Tne={ol:!0,ul:!0},K0=1,MR=2,e0=4;function f9(t,e,n){return e!=null?(e?K0:0)|(e==="full"?MR:0):t&&t.whitespace=="pre"?K0|MR:n&~e0}class TS{constructor(e,n,r,i,s,o){this.type=e,this.attrs=n,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=Hr.none,this.match=s||(o&e0?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Tt.from(e));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&K0)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let n=Tt.from(this.content);return!e&&this.match&&(n=n.append(this.match.fillBefore(Tt.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&&!Ane.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class p9{constructor(e,n,r){this.parser=e,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=n.topNode,s,o=f9(null,n.preserveWhitespace,0)|(r?e0:0);i?s=new TS(i.type,i.attrs,Hr.none,!0,n.topMatch||i.type.contentMatch,o):r?s=new TS(null,null,Hr.none,!0,null,o):s=new TS(e.schema.topNodeType,null,Hr.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,i=this.top,s=i.options&MR?"full":this.localPreserveWS||(i.options&K0)>0,{schema:o}=this.parser;if(s==="full"||i.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(u)):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,i){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(i)this.addElement(e,r,i);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,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,n);this.findAtPoint(e,s)}findPlace(e,n,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let c=this.nodes[o],u=c.findWrapping(e);if(u&&(!i||i.length>u.length+l)&&(i=u,s=c,!u.length))break;if(c.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(u.type):b9(u.type,e))?(c=u.addToSet(c),!1):!0),this.nodes.push(new TS(e,n,c,i,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|=K0)}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 i=r.length-1;i>=0;i--)e+=r[i].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,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,c)=>{for(;l>=0;l--){let u=n[l];if(u==""){if(l==n.length-1||l==0)continue;for(;c>=s;c--)if(o(l-1,c))return!0;return!1}else{let d=c>0||c==0&&i?this.nodes[c].type:r&&c>=s?r.node(c-s).type:null;if(!d||d.name!=u&&!d.isInGroup(u))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 z$e(t){for(let e=t.firstChild,n=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Tne.hasOwnProperty(r)&&n?(n.appendChild(e),e=n):r=="li"?n=e:r&&(n=null)}}function U$e(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function g9(t){let e={};for(let n in t)e[n]=t[n];return e}function b9(t,e){let n=e.schema.nodes;for(let r in n){let i=n[r];if(!i.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;i--){let s=this.serializeMark(e.marks[i],e.isInline,n);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,n,r={}){let i=this.marks[e.type.name];return i&&m1(rj(r),i(e,n),null,e.attrs)}static renderSpec(e,n,r=null,i){return m1(e,n,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new lp(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let n=x9(e.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(e){return x9(e.marks)}}function x9(t){let e={};for(let n in t){let r=t[n].spec.toDOM;r&&(e[n]=r)}return e}function rj(t){return t.document||window.document}const y9=new WeakMap;function B$e(t){let e=y9.get(t);return e===void 0&&y9.set(t,e=H$e(t)),e}function H$e(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 i=0;i-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=i.indexOf(" ");o>0&&(n=i.slice(0,o),i=i.slice(o+1));let l,c=n?t.createElementNS(n,i):t.createElement(i),u=e[1],d=1;if(u&&typeof u=="object"&&u.nodeType==null&&!Array.isArray(u)){d=2;for(let h in u)if(u[h]!=null){let f=h.indexOf(" ");f>0?c.setAttributeNS(h.slice(0,f),h.slice(f+1),u[h]):h=="style"&&c.style?c.style.cssText=u[h]:c.setAttribute(h,u[h])}}for(let h=d;hd)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:p,contentDOM:x}=m1(t,f,n,r);if(c.appendChild(p),x){if(l)throw new RangeError("Multiple content holes");l=x}}}return{dom:c,contentDOM:l}}const Ene=65535,Pne=Math.pow(2,16);function $$e(t,e){return t+e*Pne}function v9(t){return t&Ene}function V$e(t){return(t-(t&Ene))/Pne}const jne=1,Dne=2,f1=4,Rne=8;class AR{constructor(e,n,r){this.pos=e,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Rne)>0}get deletedBefore(){return(this.delInfo&(jne|f1))>0}get deletedAfter(){return(this.delInfo&(Dne|f1))>0}get deletedAcross(){return(this.delInfo&f1)>0}}class Co{constructor(e,n=!1){if(this.ranges=e,this.inverted=n,!e.length&&Co.empty)return Co.empty}recover(e){let n=0,r=v9(e);if(!this.inverted)for(let i=0;ie)break;let u=this.ranges[l+s],d=this.ranges[l+o],h=c+u;if(e<=h){let f=u?e==c?-1:e==h?1:n:n,p=c+i+(f<0?0:d);if(r)return p;let x=e==(n<0?c:h)?null:$$e(l/3,e-c),v=e==c?Dne:e==h?jne:f1;return(n<0?e!=c:e!=h)&&(v|=Rne),new AR(p,v,x)}i+=d-u}return r?e+i:new AR(e+i,0,null)}touches(e,n){let r=0,i=v9(n),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let u=this.ranges[l+s],d=c+u;if(e<=d&&l==i*3)return!0;r+=this.ranges[l+o]-u}return!1}forEach(e){let n=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;n--){let i=e.getMirror(n);this.appendMap(e._maps[n].invert(),i!=null&&i>n?r-i-1:void 0)}}invert(){let e=new X0;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)),i),n.openStart,n.openEnd);return na.fromReplace(e,this.from,this.to,s)}invert(){return new Gl(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 Ch(n.pos,r.pos,this.mark)}merge(e){return e instanceof Ch&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Ch(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 Ch(n.from,n.to,e.markFromJSON(n.mark))}}Ns.jsonID("addMark",Ch);class Gl extends Ns{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 Bt(y4(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),n.openStart,n.openEnd);return na.fromReplace(e,this.from,this.to,r)}invert(){return new Ch(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 Gl(n.pos,r.pos,this.mark)}merge(e){return e instanceof Gl&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Gl(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 Gl(n.from,n.to,e.markFromJSON(n.mark))}}Ns.jsonID("removeMark",Gl);class kh extends Ns{constructor(e,n){super(),this.pos=e,this.mark=n}apply(e){let n=e.nodeAt(this.pos);if(!n)return na.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return na.fromReplace(e,this.pos,this.pos+1,new Bt(Tt.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 i=0;ir.pos?null:new Da(n.pos,r.pos,i,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 Da(n.from,n.to,n.gapFrom,n.gapTo,Bt.fromJSON(e,n.slice),n.insert,!!n.structure)}}Ns.jsonID("replaceAround",Da);function TR(t,e,n){let r=t.resolve(e),i=n-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function G$e(t,e,n,r){let i=[],s=[],o,l;t.doc.nodesBetween(e,n,(c,u,d)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&d.type.allowsMarkType(r.type)){let f=Math.max(u,e),p=Math.min(u+c.nodeSize,n),x=r.addToSet(h);for(let v=0;vt.step(c)),s.forEach(c=>t.step(c))}function q$e(t,e,n,r){let i=[],s=0;t.doc.nodesBetween(e,n,(o,l)=>{if(!o.isInline)return;s++;let c=null;if(r instanceof fM){let u=o.marks,d;for(;d=r.isInSet(u);)(c||(c=[])).push(d),u=d.removeFromSet(u)}else r?r.isInSet(o.marks)&&(c=[r]):c=o.marks;if(c&&c.length){let u=Math.min(l+o.nodeSize,n);for(let d=0;dt.step(new Gl(o.from,o.to,o.style)))}function v4(t,e,n,r=n.contentMatch,i=!0){let s=t.doc.nodeAt(e),o=[],l=e+1;for(let c=0;c=0;c--)t.step(o[c])}function W$e(t,e,n){return(e==0||t.canReplace(e,t.childCount))&&(n==t.childCount||t.canReplace(0,n))}function ox(t){let n=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let r=t.depth,i=0,s=0;;--r){let o=t.$from.node(r),l=t.$from.index(r)+i,c=t.$to.indexAfter(r)-s;if(rn;x--)v||r.index(x)>0?(v=!0,d=Tt.from(r.node(x).copy(d)),h++):c--;let f=Tt.empty,p=0;for(let x=s,v=!1;x>n;x--)v||i.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=Tt.from(n[o].type.create(n[o].attrs,r))}let i=e.start,s=e.end;t.step(new Da(i,s,i,s,new Bt(r,0,0),n.length,!0))}function Z$e(t,e,n,r,i){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 i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,c)&&J$e(t.doc,t.mapping.slice(s).map(l),r)){let u=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",x=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!x?u=!1:!p&&x&&(u=!0)}u===!1&&Lne(t,o,l,s),v4(t,t.mapping.slice(s).map(l,1),r,void 0,u===null);let d=t.mapping.slice(s),h=d.map(l,1),f=d.map(l+o.nodeSize,1);return t.step(new Da(h,f,h+1,f-1,new Bt(Tt.from(r.create(c,null,o.marks)),0,0),1,!0)),u===!0&&Fne(t,o,l,s),!1}})}function Fne(t,e,n,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let c=t.mapping.slice(r).map(n+1+s+o.index);t.replaceWith(c,c+1,e.type.schema.linebreakReplacement.create())}}})}function Lne(t,e,n,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=t.mapping.slice(r).map(n+1+s);t.replaceWith(o,o+1,e.type.schema.text(` @@ -8666,7 +8666,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${ky(t. transition-all duration-200 hover:border-bambu-dark-tertiary/80 ${k?"opacity-50 scale-[1.02] shadow-xl z-50":""} ${C?"border-blue-500/30 bg-gradient-to-r from-blue-500/5 to-transparent":""} - `,children:a.jsxs("div",{className:"flex items-center gap-4 p-4",children:[j&&d&&a.jsx("button",{onClick:P=>{P.stopPropagation(),d()},className:`flex items-center justify-center w-6 h-6 rounded border transition-colors ${u?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:u&&a.jsx(Yr,{className:"w-4 h-4"})}),j?a.jsx("div",{...b,...y,className:"flex items-center justify-center w-10 h-10 md:w-8 md:h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation",children:a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}):e!==void 0?a.jsxs("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium",children:["#",e]}):a.jsx("div",{className:"w-8"}),a.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?a.jsx("img",{src:t.plate_id!=null?se.getArchivePlateThumbnail(t.archive_id,t.plate_id):se.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?se.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):se.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(is,{className:"w-6 h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`}),t.archive_id?a.jsx(Xs,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewArchive"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(Xs,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewInFileManager"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):null]}),a.jsxs("div",{className:"flex items-center gap-3 text-sm text-bambu-gray",children:[a.jsxs("span",{className:`flex items-center gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model?"text-blue-400":""}`,children:[a.jsx(Cr,{className:"w-3.5 h-3.5"}),t.target_model?`${x("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?x("queue.filter.unassigned"):t.printer_name||`${x("common.printer")} #${t.printer_id}`]}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Iu,{className:"w-3.5 h-3.5"}),jae(t.print_time_seconds)]}),t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1.5",title:x("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(rd,{className:"w-3.5 h-3.5"}),t.created_by_username]}),j&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Xn,{className:"w-3.5 h-3.5"}),gQe(t.scheduled_time,c,x)]})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.manual_start&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[a.jsx(aX,{className:"w-3 h-3"}),x("queue.badges.staged")]}),t.require_previous_success&&a.jsx("span",{className:"text-xs px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:x("queue.badges.requiresPrevious")}),t.auto_off_after&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[a.jsx(fd,{className:"w-3 h-3"}),x("queue.badges.autoPowerOff")]})]}),C&&a.jsxs("div",{className:"mt-3",children:[a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full bg-gradient-to-r from-blue-500 to-blue-400 animate-pulse w-full opacity-50"})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:x("queue.printingInProgress")})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-xs text-purple-400 mt-2 flex items-start gap-1",children:[a.jsx(Bi,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[a.jsx(Bi,{className:"w-3 h-3"}),t.error_message]})]}),a.jsx(bQe,{status:t.status,waitingReason:t.waiting_reason,printerState:p,t:x}),a.jsxs("div",{className:"flex items-center gap-1",children:[C&&a.jsx(Te,{variant:"ghost",size:"sm",onClick:s,disabled:!h("printers:control"),title:h("printers:control")?x("queue.actions.stopPrint"):x("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(ehe,{className:"w-4 h-4"})}),j&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Te,{variant:"ghost",size:"sm",onClick:l,disabled:!h("printers:control"),title:h("printers:control")?x("queue.actions.startPrint"):x("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:a.jsx(jo,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:n,disabled:!f("queue","update",t.created_by_id),title:f("queue","update",t.created_by_id)?x("common.edit"):x("queue.permissions.noEdit"),children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:r,disabled:!f("queue","delete",t.created_by_id),title:f("queue","delete",t.created_by_id)?x("common.cancel"):x("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(Rt,{className:"w-4 h-4"})})]}),E&&a.jsxs(a.Fragment,{children:[a.jsx(Te,{variant:"ghost",size:"sm",onClick:o,disabled:!h("queue:create"),title:h("queue:create")?x("queue.actions.requeue"):x("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:a.jsx(Ur,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:i,disabled:!f("queue","delete",t.created_by_id),title:f("queue","delete",t.created_by_id)?x("common.remove"):x("queue.permissions.noRemove"),children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})})}function yQe(){const{t}=Ut(),e=Zt(),{showToast:n}=hn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=Fr(),[o,l]=w.useState(null),[c,u]=w.useState(""),[d,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(null),[b,y]=w.useState(null),[S,N]=w.useState(null),[M,k]=w.useState([]),[T,C]=w.useState(!1),[j,E]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[P,U]=w.useState(()=>{const Z=localStorage.getItem("queue.historySortAsc");return Z!==null?Z==="true":!1}),[L,B]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[D,H]=w.useState(()=>{const Z=localStorage.getItem("queue.pendingSortAsc");return Z!==null?Z==="true":!0});w.useEffect(()=>{localStorage.setItem("queue.historySortBy",j)},[j]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(P))},[P]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",L)},[L]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(D))},[D]);const G=oae(UC(jM,{activationConstraint:{distance:8}}),UC(PM,{coordinateGetter:Eae})),{data:I}=et({queryKey:["settings"],queryFn:se.getSettings}),K=I?.time_format||"system",{data:Q,isLoading:ae}=et({queryKey:["queue",o,c],queryFn:()=>se.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:V}=et({queryKey:["printers"],queryFn:()=>se.getPrinters()}),Y=ot({mutationFn:Z=>se.cancelQueueItem(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),ne=ot({mutationFn:Z=>se.removeFromQueue(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),ee=ot({mutationFn:Z=>se.stopQueueItem(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),ve=ot({mutationFn:Z=>se.startQueueItem(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),fe=ot({mutationFn:Z=>se.reorderQueue(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),de=ot({mutationFn:async()=>{const Z=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];for(const z of Z)await se.removeFromQueue(z.id);return Z.length},onSuccess:Z=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:Z}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),Re=ot({mutationFn:Z=>se.bulkUpdateQueue(Z),onSuccess:Z=>{e.invalidateQueries({queryKey:["queue"]}),k([]),C(!1),n(Z.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),ue=ot({mutationFn:async Z=>{for(const z of Z)await se.cancelQueueItem(z);return Z.length},onSuccess:Z=>{e.invalidateQueries({queryKey:["queue"]}),k([]),n(t("queue.toast.bulkCancelled",{count:Z}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),le=Z=>{k(z=>z.includes(Z)?z.filter(F=>F!==Z):[...z,Z])},Ne=w.useMemo(()=>{const Z=new Set;return V?.forEach(z=>{z.location&&Z.add(z.location)}),Q?.forEach(z=>{z.target_location&&Z.add(z.target_location)}),Array.from(Z).sort()},[V,Q]),J=w.useCallback(Z=>d?Z.target_location?Z.target_location===d:Z.printer_id?V?.find(F=>F.id===Z.printer_id)?.location===d:!1:!0,[d,V]),Le=w.useMemo(()=>{let Z=Q?.filter(F=>F.status==="pending")||[];d&&(Z=Z.filter(J));const z=F=>{if(!F.scheduled_time)return 0;const W=new Date(F.scheduled_time).getTime(),me=Date.now()+4320*60*60*1e3;return W>me?0:W};return[...Z].sort((F,W)=>{let me;if(L==="name"){const _e=F.archive_name||F.library_file_name||"",be=W.archive_name||W.library_file_name||"";me=_e.localeCompare(be)}else L==="printer"?me=(F.printer_name||"").localeCompare(W.printer_name||""):L==="time"?me=z(F)-z(W):me=F.position-W.position;return D?me:-me})},[Q,L,D,J,d]),$=()=>{const Z=Le.map(z=>z.id);M.length===Z.length?k([]):k(Z)},X=w.useMemo(()=>{let Z=Q?.filter(z=>z.status==="printing")||[];return d&&(Z=Z.filter(J)),Z},[Q,d,J]),ce=w.useMemo(()=>{const Z=new Set;return X.forEach(z=>{z.printer_id&&Z.add(z.printer_id)}),Array.from(Z)},[X]),q=kF({queries:ce.map(Z=>({queryKey:["printerStatus",Z],queryFn:()=>se.getPrinterStatus(Z),refetchInterval:5e3}))}),ie=w.useMemo(()=>{const Z={};return ce.forEach((z,F)=>{const W=q[F];W?.data?.state&&(Z[z]=W.data.state)}),Z},[ce,q]),te=w.useMemo(()=>{let Z=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];return d&&(Z=Z.filter(J)),[...Z].sort((z,F)=>{let W;if(j==="name"){const me=z.archive_name||z.library_file_name||"",_e=F.archive_name||F.library_file_name||"";W=me.localeCompare(_e)}else j==="printer"?W=(z.printer_name||"").localeCompare(F.printer_name||""):W=new Date(F.completed_at||F.created_at).getTime()-new Date(z.completed_at||z.created_at).getTime();return P?-W:W})},[Q,j,P,J,d]),he=w.useMemo(()=>Le.reduce((Z,z)=>Z+(z.print_time_seconds||0),0),[Le]),ge=Z=>{const{active:z,over:F}=Z;if(!F||z.id===F.id)return;const W=Le.findIndex(_e=>_e.id===z.id),me=Le.findIndex(_e=>_e.id===F.id);if(W!==-1&&me!==-1){const be=FM(Le,W,me).map((He,Se)=>({id:He.id,position:Se+1}));fe.mutate(be)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(sX,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[a.jsx(_t,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:a.jsx(jo,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:X.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.printing")})]})]})})}),a.jsx(_t,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center",children:a.jsx(Xn,{className:"w-5 h-5 text-yellow-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:Le.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.queued")})]})]})})}),a.jsx(_t,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center",children:a.jsx(Iu,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:jae(he)}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.totalTime")})]})]})})}),a.jsx(_t,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-500/20 flex items-center justify-center",children:a.jsx(gr,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:te.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.history")})]})]})})})]}),a.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o===-1?"unassigned":o||"",onChange:Z=>{const z=Z.target.value;l(z==="unassigned"?-1:z===""?null:Number(z))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),V?.map(Z=>a.jsx("option",{value:Z.id,children:Z.name},Z.id))]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:Z=>u(Z.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Ne.length>0&&a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:d,onChange:Z=>h(Z.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Ne.map(Z=>a.jsx("option",{value:Z,children:Z},Z))]}),a.jsx("div",{className:"flex-1"}),te.length>0&&a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>p(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(en,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),ae?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Q?.length===0?a.jsxs(_t,{className:"p-12 text-center border-dashed",children:[a.jsx(ai,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):a.jsxs("div",{className:"space-y-8",children:[X.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-3",children:X.map(Z=>a.jsx(Dj,{item:Z,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:Z}),onRequeue:()=>{},onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,printerState:Z.printer_id?ie[Z.printer_id]:null,t},Z.id))})]}),Le.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Xn,{className:"w-5 h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:Le.length}),")"]}),a.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:L,onChange:Z=>B(Z.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>H(!D),title:t(D?"common.ascending":"common.descending"),className:"px-2",children:D?a.jsx(jf,{className:"w-4 h-4"}):a.jsx(lb,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-bambu-dark rounded-lg",children:[a.jsxs(Te,{variant:"ghost",size:"sm",onClick:$,className:"flex items-center gap-2",children:[M.length===Le.length&&Le.length>0?a.jsx(ao,{className:"w-4 h-4 text-bambu-green"}):a.jsx(gl,{className:"w-4 h-4"}),M.length===Le.length&&Le.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),M.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:M.length})}),a.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>C(!0),className:"flex items-center gap-2 text-bambu-green hover:text-bambu-green-light",disabled:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?void 0:t("queue.permissions.noEditItems"),children:[a.jsx($i,{className:"w-4 h-4"}),t("queue.bulkEdit.editSelected")]}),a.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>ue.mutate(M),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:ue.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?void 0:t("queue.permissions.noCancelItems"),children:[a.jsx(Rt,{className:"w-4 h-4"}),t("queue.bulkEdit.cancelSelected")]})]})]}),a.jsx(Nae,{sensors:G,collisionDetection:dae,onDragEnd:ge,children:a.jsx(Mae,{items:Le.map(Z=>Z.id),strategy:aQe,children:a.jsx("div",{className:"space-y-3",children:Le.map((Z,z)=>a.jsx(Dj,{item:Z,position:z+1,onEdit:()=>v(Z),onCancel:()=>N({type:"cancel",item:Z}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>ve.mutate(Z.id),timeFormat:K,isSelected:M.includes(Z.id),onToggleSelect:()=>le(Z.id),hasPermission:r,canModify:s,t},Z.id))})})})]}),te.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gr,{className:"w-5 h-5 text-bambu-gray"}),t("queue.sections.history"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:te.length}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:j,onChange:Z=>E(Z.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>U(!P),title:t(P?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:P?a.jsx(jf,{className:"w-4 h-4"}):a.jsx(lb,{className:"w-4 h-4"})})]})]}),a.jsx("div",{className:"space-y-3",children:te.slice(0,20).map((Z,z)=>a.jsx(Dj,{item:Z,position:z+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:Z}),onStop:()=>{},onRequeue:()=>y(Z),onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,t},Z.id))})]})]}),x&&a.jsx(Qu,{mode:"edit-queue-item",archiveId:x.archive_id??void 0,libraryFileId:x.library_file_id??void 0,archiveName:x.archive_name||x.library_file_name||`File #${x.archive_id||x.library_file_id}`,queueItem:x,onClose:()=>v(null)}),b&&a.jsx(Qu,{mode:"add-to-queue",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,onClose:()=>y(null)}),S&&a.jsx(Pn,{title:S.type==="cancel"?t("queue.confirm.cancelTitle"):S.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:S.type==="cancel"?t("queue.confirm.cancelMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):S.type==="stop"?t("queue.confirm.stopMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:S.type==="cancel"?t("queue.confirm.cancelButton"):S.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{S.type==="cancel"?Y.mutate(S.item.id):S.type==="stop"?ee.mutate(S.item.id):ne.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),f&&a.jsx(Pn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:te.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{de.mutate(),p(!1)},onCancel:()=>p(!1)}),T&&a.jsx(xQe,{selectedCount:M.length,printers:V?.map(Z=>({id:Z.id,name:Z.name}))||[],onSave:Z=>{Object.keys(Z).length>0&&Re.mutate({item_ids:M,...Z})},onClose:()=>C(!1),isSaving:Re.isPending,t})]})}function vQe({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const S=n.current;if(!S)return;const N=new ResizeObserver(M=>{const k=M[0]?.contentRect.width||0;i(k)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const S={};t.forEach(U=>{const L=U.split("T")[0];S[L]=(S[L]||0)+1});const N=new Date,M=new Date(N);M.setMonth(M.getMonth()-e),M.setDate(M.getDate()-M.getDay());const k=[],T=[];let C=[],j=-1;const E=new Date(M);let P=0;for(;E<=N;)E.getDay()===0&&C.length>0&&(k.push(C),C=[],P++),E.getMonth()!==j&&(T.push({month:E.toLocaleDateString("en-US",{month:"short"}),weekIndex:P}),j=E.getMonth()),C.push(new Date(E)),E.setDate(E.getDate()+1);return C.length>0&&k.push(C),{weeks:k,monthLabels:T,printCounts:S}},[t,e]),c=Math.max(1,...Object.values(l)),u=S=>{if(S===0)return"bg-bambu-dark";const N=S/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=s.length,f=32,p=2,x=r-f-16,v=h>0?Math.floor((x-(h-1)*p)/h):12,b=Math.max(8,Math.min(20,v)),y=b<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:f+4},children:o.map(({month:S,weekIndex:N},M)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:y,marginLeft:M===0?0:`${(N-(o[M-1]?.weekIndex||0))*(b+p)-24}px`},children:S},M))}),a.jsxs("div",{className:"flex",style:{gap:p},children:[a.jsx("div",{className:"flex flex-col",style:{gap:p,marginRight:4,width:f},children:d.map((S,N)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:f,height:b,fontSize:y,visibility:N%2===1?"visible":"hidden"},children:S},S))}),s.map((S,N)=>a.jsx("div",{className:"flex flex-col",style:{gap:p},children:[0,1,2,3,4,5,6].map(M=>{const k=S.find(E=>E.getDay()===M);if(!k)return a.jsx("div",{style:{width:b,height:b}},M);const T=k.toISOString().split("T")[0],C=l[T]||0,j=T===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${u(C)} ${j?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${k.toLocaleDateString()}: ${C} print${C!==1?"s":""}`},M)})},N))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:y},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:p},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),a.jsx("span",{children:"More"})]})]})})}const $S=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function wQe(t){const e=new Date;switch(t){case"7d":return new Date(e.getTime()-10080*60*1e3);case"30d":return new Date(e.getTime()-720*60*60*1e3);case"90d":return new Date(e.getTime()-2160*60*60*1e3);case"365d":return new Date(e.getTime()-365*24*60*60*1e3);case"all":return new Date(0)}}function _Qe({archives:t,currency:e="$"}){const[n,r]=w.useState("30d"),i=w.useMemo(()=>{const p=wQe(n);return t.filter(x=>(Ji(x.completed_at||x.created_at)||new Date(0))>=p)},[t,n]),s=w.useMemo(()=>{const p=new Map;return i.forEach(x=>{const v=Ji(x.completed_at||x.created_at)||new Date,b=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`,y=p.get(b)||{date:b,filament:0,cost:0,prints:0};y.filament+=x.filament_used_grams||0,y.cost+=x.cost||0,y.prints+=x.quantity||1,p.set(b,y)}),Array.from(p.values()).sort((x,v)=>x.date.localeCompare(v.date)).map(x=>({...x,dateLabel:new Date(x.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=w.useMemo(()=>{if(n==="7d"||n==="30d")return s;const p=new Map;return i.forEach(x=>{const v=Ji(x.completed_at||x.created_at)||new Date,b=new Date(v);b.setDate(v.getDate()-v.getDay());const y=`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`,S=p.get(y)||{week:y,filament:0,cost:0,prints:0};S.filament+=x.filament_used_grams||0,S.cost+=x.cost||0,S.prints+=x.quantity||1,p.set(y,S)}),Array.from(p.values()).sort((x,v)=>x.week.localeCompare(v.week)).map(x=>({date:x.week,dateLabel:`Week of ${new Date(x.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...x}))},[i,s,n]),l=w.useMemo(()=>{const p=new Map;return i.forEach(x=>{const b=(x.filament_type||"Unknown").split(", ");b.forEach(y=>{const S=(x.filament_used_grams||0)/b.length;p.set(y,(p.get(y)||0)+S)})}),Array.from(p.entries()).map(([x,v])=>({name:x,value:Math.round(v)})).sort((x,v)=>v.value-x.value)},[i]),c=w.useMemo(()=>{const p=new Date,x=[];for(let v=5;v>=0;v--){const b=new Date(p.getFullYear(),p.getMonth()-v,1),y=new Date(p.getFullYear(),p.getMonth()-v+1,0),S=b.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(M=>{const k=Ji(M.completed_at||M.created_at)||new Date(0);return k>=b&&k<=y});x.push({month:S,filament:Math.round(N.reduce((M,k)=>M+(k.filament_used_grams||0),0)),cost:N.reduce((M,k)=>M+(k.cost||0),0),prints:N.reduce((M,k)=>M+(k.quantity||1),0)})}return x},[t]),u=n==="7d"||n==="30d"?s:o,d=i.reduce((p,x)=>p+(x.filament_used_grams||0),0),h=i.reduce((p,x)=>p+(x.cost||0),0),f=i.reduce((p,x)=>p+(x.quantity||1),0);return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),a.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(p=>a.jsx("button",{onClick:()=>r(p),className:`px-3 py-1 text-sm rounded-md transition-colors ${n===p?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:p==="all"?"All":p.replace("d","D")},p))})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Filament"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[(d/1e3).toFixed(2),"kg"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Cost"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[e,h.toFixed(2)]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[f," prints"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Avg per Print"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[f>0?(d/f).toFixed(0):0,"g"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,f>0?(h/f).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),a.jsx(l1,{width:"100%",height:250,children:a.jsxs(fHe,{data:u,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(ON,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(BN,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(HN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),a.jsx(u1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:p=>[`${Number(p??0).toFixed(0)}g`,"Filament"]}),a.jsx(Rte,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(l1,{width:160,height:160,children:a.jsxs(hHe,{children:[a.jsx(ste,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((p,x)=>a.jsx(Iv,{fill:$S[x%$S.length]},`cell-${x}`))}),a.jsx(u1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:p=>[`${p??0}g`,"Usage"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((p,x)=>{const v=l.reduce((y,S)=>y+S.value,0),b=v>0?(p.value/v*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:$S[x%$S.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:p.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[b,"%"]})]},p.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),a.jsx(l1,{width:"100%",height:200,children:a.jsxs(eHe,{data:c,children:[a.jsx(ON,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(BN,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),a.jsx(HN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),a.jsx(u1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(p,x)=>[x==="filament"?`${p??0}g`:x==="cost"?`${e}${Number(p??0).toFixed(2)}`:p??0,x==="filament"?"Filament":x==="cost"?"Cost":"Prints"]}),a.jsx(BL,{}),a.jsx(zte,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function SQe({id:t,title:e,component:n,isHidden:r,size:i,onToggleVisibility:s,onToggleSize:o}){const{attributes:l,listeners:c,setNodeRef:u,transform:d,transition:h,isDragging:f}=Tae({id:t}),p={transform:Ob.Transform.toString(d),transition:h,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...p,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...l,...c,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(EF,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(TF,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:s,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(uv,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function NQe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:s}){const o=()=>{const M={};return t.forEach(k=>{M[k.id]=k.defaultSize||4}),M},[l,c]=w.useState(()=>{const M=localStorage.getItem(e);if(M)try{const k=JSON.parse(M);return k.sizes||(k.sizes=o()),k}catch{}return{order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:o()}}),[u,d]=w.useState(!1);w.useEffect(()=>{const M=()=>d(k=>!k);return window.addEventListener("toggle-hidden-panel",M),()=>window.removeEventListener("toggle-hidden-panel",M)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),w.useEffect(()=>{const k=t.map(T=>T.id).filter(T=>!l.order.includes(T));k.length>0&&c(T=>({...T,order:[...T.order,...k]}))},[t,l.order]);const h=oae(UC(jM,{activationConstraint:{distance:8}}),UC(PM,{coordinateGetter:Eae})),f=M=>{const{active:k,over:T}=M;T&&k.id!==T.id&&c(C=>{const j=C.order.indexOf(k.id),E=C.order.indexOf(T.id);return{...C,order:FM(C.order,j,E)}})},p=M=>{c(k=>({...k,hidden:k.hidden.includes(M)?k.hidden.filter(T=>T!==M):[...k.hidden,M]}))},x=M=>{c(k=>{const T=k.sizes[M]||4,C=T===1?2:T===2?4:1;return{...k,sizes:{...k.sizes,[M]:C}}})},v=()=>{const M={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:o()};c(M),i?.()},b=l.order.map(M=>t.find(k=>k.id===M)).filter(Boolean),y=b.filter(M=>!l.hidden.includes(M.id)),S=b.filter(M=>l.hidden.includes(M.id)),N=s?.({hiddenCount:S.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:v});return a.jsxs("div",{className:"space-y-4",children:[N,!r&&!s&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Te,{variant:"secondary",size:"sm",onClick:v,children:[a.jsx(Do,{className:"w-4 h-4"}),"Reset Layout"]}),S.length>0&&a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[a.jsx(Xl,{className:"w-4 h-4"}),S.length," Hidden"]})]}),u&&S.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(M=>a.jsxs("button",{onClick:()=>p(M.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[a.jsx(Xl,{className:"w-3 h-3"}),M.title]},M.id))})]}),a.jsx(Nae,{sensors:h,collisionDetection:dae,onDragEnd:f,children:a.jsx(Mae,{items:y.map(M=>M.id),strategy:dI,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:y.map(M=>a.jsx(SQe,{id:M.id,title:M.title,component:M.component,isHidden:l.hidden.includes(M.id),size:l.sizes[M.id]||2,onToggleVisibility:()=>p(M.id),onToggleSize:()=>x(M.id)},M.id))})})}),y.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Te,{className:"mt-4",onClick:v,children:"Reset Layout"})]})]})}const CQe={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽"};function ju(t){return CQe[t.toUpperCase()]||t}const kQe=[{code:"USD",label:"USD ($)"},{code:"EUR",label:"EUR (€)"},{code:"GBP",label:"GBP (£)"},{code:"CHF",label:"CHF (Fr.)"},{code:"JPY",label:"JPY (¥)"},{code:"CNY",label:"CNY (¥)"},{code:"CAD",label:"CAD ($)"},{code:"AUD",label:"AUD ($)"},{code:"INR",label:"INR (₹)"},{code:"HKD",label:"HKD (HK$)"},{code:"KRW",label:"KRW (₩)"},{code:"SEK",label:"SEK (kr)"},{code:"NOK",label:"NOK (kr)"},{code:"DKK",label:"DKK (kr)"},{code:"PLN",label:"PLN (zł)"},{code:"BRL",label:"BRL (R$)"},{code:"TWD",label:"TWD (NT$)"},{code:"SGD",label:"SGD (S$)"},{code:"NZD",label:"NZD (NZ$)"},{code:"MXN",label:"MXN (MX$)"},{code:"CZK",label:"CZK (Kč)"},{code:"THB",label:"THB (฿)"},{code:"ZAR",label:"ZAR (R)"},{code:"TRY",label:"TRY (₺)"},{code:"RUB",label:"RUB (₽)"}];function MQe({stats:t,currency:e,t:n}){return a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(ra,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),a.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:a.jsx(Xn,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:a.jsx(ra,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:a.jsx(o3,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:a.jsx(qh,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(2)||"0.00"," kWh"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:a.jsx(o3,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function AQe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,s=n===1?112:n===2?128:144,o=s/2-8,l=o*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:s,height:s},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${i/100*l} ${l}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ha,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([c,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function TQe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(i),u=i-100,d=n===1?112:n===2?128:144,h=d/2-8,f=h*2*Math.PI,p=n===1?3:n===2?6:999,x=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,p):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*f} ${f}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx(dX,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),x.length>0&&a.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:x.map(([v,b])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),a.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},v))})]})]})}function EQe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noFilamentData")});const r=Object.entries(t.prints_by_filament_type).sort(([,l],[,c])=>c-l),i=e===1?5:e===2?8:999,s=r.slice(0,i),o=r.length>i;return e===4&&s.length>4?a.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),a.jsx("span",{className:"text-bambu-gray",children:c})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):a.jsxs("div",{className:"space-y-3",children:[s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white",children:l}),a.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&a.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-i})})]})}function PQe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return a.jsx(vQe,{printDates:t,months:n})}function jQe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,i])=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:a.jsx(Cr,{className:"w-4 h-4 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[i," ",n("common.prints")]})]})]},r))})}function DQe({archives:t,currency:e,t:n}){return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):a.jsx(_Qe,{archives:t,currency:e})}function RQe({size:t=1,t:e}){const{data:n,isLoading:r}=et({queryKey:["failureAnalysis"],queryFn:()=>se.getFailureAnalysis({days:30})});if(r)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const i=t===1?5:t===2?8:999,s=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=s.slice(0,i),l=s.length>i;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Mn,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:e("stats.failedPrintsCount",{failed:n.failed_prints,total:n.total_prints})}),n.trend&&n.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(DF,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:s.length-i})})]})]})}function FQe(){const{t}=Ut(),{showToast:e}=hn(),{hasPermission:n}=Fr(),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(0),[u,d]=w.useState(0),[h,f]=w.useState(!1);w.useEffect(()=>{const E=()=>{try{const U=localStorage.getItem("bambusy-dashboard-layout");if(U){const L=JSON.parse(U);d(L.hidden?.length||0)}}catch{d(0)}};E(),window.addEventListener("storage",E);const P=setInterval(E,500);return()=>{window.removeEventListener("storage",E),clearInterval(P)}},[l]);const{data:p,isLoading:x,refetch:v}=et({queryKey:["archiveStats"],queryFn:se.getArchiveStats}),{data:b}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:y}=et({queryKey:["archives"],queryFn:()=>se.getArchives(void 0,void 0,1e3,0)}),{data:S}=et({queryKey:["settings"],queryFn:se.getSettings}),N=async E=>{o(!1),i(!0);try{const{blob:P,filename:U}=await se.exportStats({format:E,days:90}),L=URL.createObjectURL(P),B=document.createElement("a");B.href=L,B.download=U,B.click(),URL.revokeObjectURL(L),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{i(!1)}},M=async()=>{f(!0);try{const E=await se.recalculateCosts();await v(),e(t("stats.recalculatedCosts",{count:E.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},k=ju(S?.currency||"USD"),T=new Map(b?.map(E=>[String(E.id),E.name])||[]),C=y?.map(E=>E.created_at)||[];if(x)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const j=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(MQe,{stats:p,currency:k,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:E=>a.jsx(AQe,{stats:p,printerMap:T,size:E,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:E=>a.jsx(TQe,{stats:p,printerMap:T,size:E,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:E=>a.jsx(EQe,{stats:p,size:E,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:E=>a.jsx(RQe,{size:E,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:E=>a.jsx(PQe,{printDates:C,size:E}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:a.jsx(jQe,{stats:p,printerMap:T,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(DQe,{archives:y||[],currency:k,t}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Te,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(Xl,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Te,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(E=>E+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(Do,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Te,{variant:"secondary",onClick:M,disabled:h||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[h?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Dde,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Te,{variant:"secondary",onClick:()=>o(!s),disabled:r,children:[r?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(M1,{className:"w-4 h-4"}),t("stats.exportStats")]}),s&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>N("csv"),children:[a.jsx(Ps,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>N("xlsx"),children:[a.jsx(M1,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),a.jsx(NQe,{widgets:j,storageKey:"bambusy-dashboard-layout",hideControls:!0},l)]})}function LQe({plug:t,onEdit:e}){const{t:n}=Ut(),r=Zt(),{showToast:i}=hn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[u,d]=w.useState(!1),[h,f]=w.useState(!1),{data:p,isLoading:x}=et({queryKey:["smart-plug-status",t.id],queryFn:()=>se.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=et({queryKey:["printers"],queryFn:se.getPrinters}),b=v?.find(P=>P.id===t.printer_id),y=ot({mutationFn:P=>se.controlSmartPlug(t.id,P),onMutate:async P=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const U=r.getQueryData(["smart-plug-status",t.id]),L=P==="on"?"ON":P==="off"||p?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],B=>({...B,state:L})),{previousStatus:U}},onError:(P,U,L)=>{L?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],L.previousStatus),i(`Failed to turn ${U} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),S=ot({mutationFn:P=>se.updateSmartPlug(t.id,P),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=ot({mutationFn:()=>se.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),M=p?.state==="ON",k=t.plug_type==="mqtt"&&p?.energy?.power!==null&&p?.energy?.power!==void 0,T=(p?.reachable??!1)||k,C=y.isPending,E=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const P=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${P}/`:`http://${P}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(_t,{className:"relative",children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?T?"bg-teal-500/20":"bg-red-500/20":T?M?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(PF,{className:`w-5 h-5 ${T?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(dv,{className:`w-5 h-5 ${T?M?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(dl,{className:`w-5 h-5 ${T?M?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[x?a.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),T&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:T?M?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?p?.state||"?":"Offline"})]}):T?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(Wg,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:M?"text-status-ok":"text-bambu-gray",children:p?.state||"Unknown"})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(Ff,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),E&&a.jsxs("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[a.jsx(Xr,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),b&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),a.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[a.jsx(Xl,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[a.jsx(Gg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[a.jsx(ai,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?`On ${t.schedule_on_time}`:`Off ${t.schedule_off_time}`]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Te,{size:"sm",variant:M?"primary":"secondary",disabled:!T||C,onClick:()=>c(!0),className:"flex-1",children:[C?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(fd,{className:"w-4 h-4"}),"On"]}),a.jsxs(Te,{size:"sm",variant:M?"secondary":"primary",disabled:!T||C,onClick:()=>d(!0),className:"flex-1",children:[C?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(nk,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&p?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[p.energy.power!==null&&p.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(p.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),p.energy.today!==null&&p.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:p.energy.today.toFixed(2)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),a.jsxs("button",{onClick:()=>f(!h),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(nd,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),a.jsx("span",{children:h?"-":"+"})]}),h&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(hv,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:P=>S.mutate({show_in_switchbar:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:P=>S.mutate({enabled:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto On"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:P=>S.mutate({auto_on:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:P=>S.mutate({auto_off:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(Xn,{className:"w-4 h-4"}),"Time"]}),a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(ak,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:P=>S.mutate({off_delay_minutes:parseInt(P.target.value)||5}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:P=>S.mutate({off_temp_threshold:parseInt(P.target.value)||70}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(sf,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(Pn,{title:n("smartPlugs.deleteSmartPlug"),message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(Pn,{title:n("smartPlugs.turnOnSmartPlug"),message:`Are you sure you want to turn on "${t.name}"?`,confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{y.mutate("on"),c(!1)},onCancel:()=>c(!1)}),u&&a.jsx(Pn,{title:n("smartPlugs.turnOffSmartPlug"),message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{y.mutate("off"),d(!1)},onCancel:()=>d(!1)})]})}function OQe({plug:t,onClose:e}){const{t:n}=Ut(),r=Zt(),i=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[u,d]=w.useState(t?.ip_address||""),[h,f]=w.useState(t?.username||""),[p,x]=w.useState(t?.password||""),[v,b]=w.useState(t?.ha_entity_id||""),[y,S]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,M]=w.useState(t?.mqtt_power_path||""),[k,T]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,j]=w.useState(t?.mqtt_energy_topic||""),[E,P]=w.useState(t?.mqtt_energy_path||""),[U,L]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[B,D]=w.useState(t?.mqtt_state_topic||""),[H,G]=w.useState(t?.mqtt_state_path||""),[I,K]=w.useState(t?.mqtt_state_on_value||""),[Q,ae]=w.useState(t?.ha_power_entity||""),[V,Y]=w.useState(t?.ha_energy_today_entity||""),[ne,ee]=w.useState(t?.ha_energy_total_entity||""),[ve,fe]=w.useState(""),[de,Re]=w.useState(""),[ue,le]=w.useState(!1),Ne=w.useRef(null),[J,Le]=w.useState(""),[$,X]=w.useState(!1),ce=w.useRef(null),[q,ie]=w.useState(""),[te,he]=w.useState(!1),ge=w.useRef(null),[Z,z]=w.useState(""),[F,W]=w.useState(!1),me=w.useRef(null),[_e,be]=w.useState(t?.printer_id||null),[He,Se]=w.useState(null),[$e,Qe]=w.useState(null),[ye,we]=w.useState(t?.power_alert_enabled||!1),[Ce,Ue]=w.useState(t?.power_alert_high?.toString()||""),[je,Ve]=w.useState(t?.power_alert_low?.toString()||""),[Ae,Ze]=w.useState(t?.schedule_enabled||!1),[Pe,Xe]=w.useState(t?.schedule_on_time||""),[Fe,Oe]=w.useState(t?.schedule_off_time||""),[Me,Je]=w.useState(t?.show_in_switchbar||!1),[yt,Mt]=w.useState(t?.show_on_printer_card??!0),[an,Pt]=w.useState(!1),[Ie,gt]=w.useState({scanned:0,total:0}),[Qt,tn]=w.useState([]),un=w.useRef(null),{data:hr}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:yr}=et({queryKey:["smart-plugs"],queryFn:se.getSmartPlugs}),{data:sr}=et({queryKey:["settings"],queryFn:se.getSettings}),Xt=!!(sr?.ha_enabled&&sr?.ha_url&&sr?.ha_token);w.useEffect(()=>{const xe=setTimeout(()=>{Re(ve)},300);return()=>clearTimeout(xe)},[ve]),w.useEffect(()=>{const xe=at=>{Ne.current&&!Ne.current.contains(at.target)&&le(!1),ce.current&&!ce.current.contains(at.target)&&X(!1),ge.current&&!ge.current.contains(at.target)&&he(!1),me.current&&!me.current.contains(at.target)&&W(!1)};return document.addEventListener("mousedown",xe),()=>document.removeEventListener("mousedown",xe)},[]);const{data:or,isLoading:yi,error:Ia}=et({queryKey:["ha-entities",de],queryFn:()=>se.getHAEntities(de||void 0),enabled:s==="homeassistant"&&Xt,retry:!1,staleTime:0}),{data:De}=et({queryKey:["ha-sensor-entities"],queryFn:se.getHASensorEntities,enabled:s==="homeassistant"&&Xt,retry:!1,staleTime:0});w.useEffect(()=>{const xe=at=>{at.key==="Escape"&&e()};return window.addEventListener("keydown",xe),()=>{window.removeEventListener("keydown",xe),un.current&&clearInterval(un.current)}},[e]);const nt=async()=>{Pt(!0),tn([]),gt({scanned:0,total:0}),Qe(null);try{await se.startTasmotaScan();const xe=async()=>{try{const at=await se.getTasmotaScanStatus();gt({scanned:at.scanned,total:at.total});const ht=await se.getDiscoveredTasmotaDevices();tn(ht),at.running||(Pt(!1),un.current&&(clearInterval(un.current),un.current=null))}catch(at){console.error("Polling error:",at)}};await xe(),un.current=setInterval(xe,500)}catch(xe){Pt(!1);const at=xe instanceof Error?xe.message:typeof xe=="string"?xe:JSON.stringify(xe);Qe(at||"Failed to start scan")}},dt=async()=>{try{await se.stopTasmotaScan()}catch{}Pt(!1),un.current&&(clearInterval(un.current),un.current=null)},pt=xe=>{d(xe.ip_address),c(xe.name),Se(null)},lt=ot({mutationFn:()=>se.testSmartPlugConnection(u,h||null,p||null),onSuccess:xe=>{Se(xe),Qe(null),!l&&xe.device_name&&c(xe.device_name)},onError:xe=>{Se(null),Qe(xe.message)}}),Ft=ot({mutationFn:xe=>se.createSmartPlug(xe),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:xe=>{Qe(xe.message)}}),pe=ot({mutationFn:xe=>se.updateSmartPlug(t.id,xe),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:xe=>{Qe(xe.message)}}),ze=hr?.filter(xe=>s==="tasmota"?!yr?.some(ht=>ht.printer_id===xe.id&&ht.id!==t?.id&&ht.plug_type==="tasmota"):!0),Ke=xe=>{if(xe.preventDefault(),Qe(null),!l.trim()){Qe("Name is required");return}if(s==="tasmota"&&!u.trim()){Qe("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Qe("Entity is required for Home Assistant plugs");return}if(s==="mqtt"){const ht=y.trim(),rt=C.trim(),At=B.trim();if(!ht&&!rt&&!At){Qe("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const at={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?u.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&Q||null,ha_energy_today_entity:s==="homeassistant"&&V||null,ha_energy_total_entity:s==="homeassistant"&&ne||null,mqtt_power_topic:s==="mqtt"&&y.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(k)||1,mqtt_energy_topic:s==="mqtt"&&C.trim()||null,mqtt_energy_path:s==="mqtt"&&E.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(U)||1,mqtt_state_topic:s==="mqtt"&&B.trim()||null,mqtt_state_path:s==="mqtt"&&H.trim()||null,mqtt_state_on_value:s==="mqtt"&&I.trim()||null,username:s==="tasmota"&&h.trim()||null,password:s==="tasmota"&&p.trim()||null,printer_id:_e,power_alert_enabled:ye,power_alert_high:Ce?parseFloat(Ce):null,power_alert_low:je?parseFloat(je):null,schedule_enabled:Ae,schedule_on_time:Pe||null,schedule_off_time:Fe||null,show_in_switchbar:Me,show_on_printer_card:yt};i?pe.mutate(at):Ft.mutate(at)},Ge=Ft.isPending||pe.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:xe=>xe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Smart Plug":"Add Smart Plug"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Ke,className:"p-6 space-y-4 overflow-y-auto",children:[$e&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:$e}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Se(null),Qe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(dl,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Se(null),Qe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(dv,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Se(null),Qe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(PF,{className:"w-4 h-4"}),"MQTT"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[an?a.jsxs(Te,{type:"button",variant:"secondary",onClick:dt,className:"w-full",children:[a.jsx(Rt,{className:"w-4 h-4"}),"Stop Scanning"]}):a.jsxs(Te,{type:"button",variant:"primary",onClick:nt,className:"w-full",children:[a.jsx(Br,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),an&&Ie.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Ie.scanned," / ",Ie.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ie.scanned/Ie.total*100}%`}})})]}),Qt.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",Qt.length," device(s) - click to select:"]}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Qt.map(xe=>a.jsxs("button",{type:"button",onClick:()=>pt(xe),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dl,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:xe.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:xe.ip_address})]})]}),xe.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${xe.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(fd,{className:"w-3 h-3"}),xe.state]})]},xe.ip_address))})]}),!an&&Qt.length===0&&Ie.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!Xt&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["Home Assistant is not configured. Set it up in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),a.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),Xt&&a.jsxs(a.Fragment,{children:[yi&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Ia&&a.jsxs("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:["Failed to load entities: ",Ia.message]}),(()=>{const xe=yr?.filter(rt=>rt.ha_entity_id&&rt.id!==t?.id).map(rt=>rt.ha_entity_id)||[],at=(or||[]).filter(rt=>!xe.includes(rt.entity_id)),ht=or?.find(rt=>rt.entity_id===v);return a.jsxs("div",{ref:Ne,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:ue?ve:ht?`${ht.friendly_name} (${ht.entity_id})`:"",onChange:rt=>{fe(rt.target.value),ue||le(!0)},onFocus:()=>{le(!0),fe("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),v&&!ue&&a.jsx("button",{type:"button",onClick:()=>{b(""),fe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),yi&&a.jsx(it,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),ue&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[yi&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!yi&&at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:de?`No entities found matching "${de}"`:"No entities available"}),!yi&&at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{b(rt.entity_id),le(!1),fe(""),l||c(rt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${rt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:rt.entity_id}),a.jsx("span",{className:rt.state==="on"?"text-bambu-green":"",children:rt.state})]})]},rt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:de?`Searching all entities (${at.length} found)`:`Showing switch, light, input_boolean (${at.length} available)`})]})})(),v&&De&&De.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const xe=De.filter(rt=>rt.unit_of_measurement==="W"||rt.unit_of_measurement==="kW"||rt.unit_of_measurement==="mW"),at=J?xe.filter(rt=>rt.entity_id.toLowerCase().includes(J.toLowerCase())||rt.friendly_name.toLowerCase().includes(J.toLowerCase())):xe,ht=De.find(rt=>rt.entity_id===Q);return a.jsxs("div",{ref:ce,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:$?J:ht?`${ht.friendly_name} (${ht.state} ${ht.unit_of_measurement})`:"",onChange:rt=>{Le(rt.target.value),$||X(!0)},onFocus:()=>{X(!0),Le("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Q&&!$&&a.jsx("button",{type:"button",onClick:()=>{ae(""),Le("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),$&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{ae(""),X(!1),Le("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{ae(rt.entity_id),X(!1),Le("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===Q?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),at=q?xe.filter(rt=>rt.entity_id.toLowerCase().includes(q.toLowerCase())||rt.friendly_name.toLowerCase().includes(q.toLowerCase())):xe,ht=De.find(rt=>rt.entity_id===V);return a.jsxs("div",{ref:ge,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:te?q:ht?`${ht.friendly_name} (${ht.state} ${ht.unit_of_measurement})`:"",onChange:rt=>{ie(rt.target.value),te||he(!0)},onFocus:()=>{he(!0),ie("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),V&&!te&&a.jsx("button",{type:"button",onClick:()=>{Y(""),ie("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),te&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{Y(""),he(!1),ie("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{Y(rt.entity_id),he(!1),ie("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===V?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),at=Z?xe.filter(rt=>rt.entity_id.toLowerCase().includes(Z.toLowerCase())||rt.friendly_name.toLowerCase().includes(Z.toLowerCase())):xe,ht=De.find(rt=>rt.entity_id===ne);return a.jsxs("div",{ref:me,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:F?Z:ht?`${ht.friendly_name} (${ht.state} ${ht.unit_of_measurement})`:"",onChange:rt=>{z(rt.target.value),F||W(!0)},onFocus:()=>{W(!0),z("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ne&&!F&&a.jsx("button",{type:"button",onClick:()=>{ee(""),z("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),F&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{ee(""),W(!1),z("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{ee(rt.entity_id),W(!1),z("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===ne?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!sr?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["MQTT broker not configured. Set broker address in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),sr?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),a.jsx("p",{className:"text-xs opacity-80",children:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system."})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:y,onChange:xe=>S(xe.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:N,onChange:xe=>M(xe.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:k,onChange:xe=>T(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:['JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.',a.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:C,onChange:xe=>j(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:E,onChange:xe=>P(xe.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:U,onChange:xe=>L(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:B,onChange:xe=>D(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:H,onChange:xe=>G(xe.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),a.jsx("input",{type:"text",value:I,onChange:xe=>K(xe.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:u,onChange:xe=>{d(xe.target.value),Se(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>lt.mutate(),disabled:!u.trim()||lt.isPending,children:[lt.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Wg,{className:"w-4 h-4"}),"Test"]})]})]}),s==="tasmota"&&He&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${He.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:He.success?a.jsxs(a.Fragment,{children:[a.jsx(gr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:"Connected!"}),a.jsxs("p",{className:"text-sm opacity-80",children:[He.device_name&&`Device: ${He.device_name} - `,"State: ",He.state]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ff,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:l,onChange:xe=>c(xe.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s==="tasmota"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),a.jsx("input",{type:"text",value:h,onChange:xe=>f(xe.target.value),placeholder:"admin",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),a.jsx("input",{type:"password",value:p,onChange:xe=>x(xe.target.value),placeholder:"********",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),a.jsxs("select",{value:_e??"",onChange:xe=>be(xe.target.value?Number(xe.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"No printer (manual control only)"}),ze?.map(xe=>a.jsx("option",{value:xe.id,children:xe.name},xe.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Gg,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ye,onChange:xe=>we(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ye&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),a.jsx("input",{type:"number",value:Ce,onChange:xe=>Ue(xe.target.value),placeholder:"e.g. 200",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),a.jsx("input",{type:"number",value:je,onChange:xe=>Ve(xe.target.value),placeholder:"e.g. 10",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xn,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ae,onChange:xe=>Ze(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Ae&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),a.jsx("input",{type:"time",value:Pe,onChange:xe=>Xe(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),a.jsx("input",{type:"time",value:Fe,onChange:xe=>Oe(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action."})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(hv,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Me,onChange:xe=>Je(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show on Printer Card"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Display button on printer card"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:yt,onChange:xe=>Mt(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Te,{type:"submit",disabled:Ge,className:"flex-1",children:[Ge?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(xs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function $n({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:a.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}const IQe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function zQe({provider:t,onEdit:e}){const n=Zt(),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(null),{data:u}=et({queryKey:["printers"],queryFn:se.getPrinters}),d=u?.find(v=>v.id===t.printer_id),h=ot({mutationFn:v=>se.updateNotificationProvider(t.id,v),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),f=ot({mutationFn:()=>se.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=ot({mutationFn:()=>se.testNotificationProvider(t.id),onSuccess:v=>{c(v),n.invalidateQueries({queryKey:["notification-providers"]})},onError:v=>{c({success:!1,message:v.message})}}),x=v=>v||"";return a.jsxs(a.Fragment,{children:[a.jsx(_t,{className:"relative",children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(Gg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:IQe[t.provider_type]||t.provider_type})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",hb(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(Ji(t.last_error_at)?.getTime()||0)>(Ji(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),a.jsx($n,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]})]}),d&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),a.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:"Start"}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:"Plate Check"}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:"Low Filament"}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:"Maintenance"}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:"AMS Humidity"}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:"AMS Temp"}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:"AMS-HT Humidity"}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:"AMS-HT Temp"}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(A1,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(ai,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Te,{size:"sm",variant:"secondary",disabled:p.isPending,onClick:()=>{c(null),p.mutate()},className:"w-full",children:[p.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(rk,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${l.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[l.success?a.jsx(gr,{className:"w-4 h-4"}):a.jsx(ha,{className:"w-4 h-4"}),a.jsx("span",{children:l.message})]}),a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors border-t border-bambu-dark-tertiary",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(nd,{className:"w-4 h-4"}),"Event Settings"]}),s?a.jsx(Wl,{className:"w-4 h-4"}):a.jsx(Jn,{className:"w-4 h-4"})]}),s&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),a.jsx($n,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Started"}),a.jsx($n,{checked:t.on_print_start,onChange:v=>h.mutate({on_print_start:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),a.jsx($n,{checked:t.on_plate_not_empty??!0,onChange:v=>h.mutate({on_plate_not_empty:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),a.jsx($n,{checked:t.on_print_complete,onChange:v=>h.mutate({on_print_complete:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),a.jsx($n,{checked:t.on_print_failed,onChange:v=>h.mutate({on_print_failed:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),a.jsx($n,{checked:t.on_print_stopped,onChange:v=>h.mutate({on_print_stopped:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),a.jsx($n,{checked:t.on_print_progress,onChange:v=>h.mutate({on_print_progress:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),a.jsx($n,{checked:t.on_printer_offline,onChange:v=>h.mutate({on_printer_offline:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),a.jsx($n,{checked:t.on_printer_error,onChange:v=>h.mutate({on_printer_error:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:t.on_filament_low,onChange:v=>h.mutate({on_filament_low:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),a.jsx($n,{checked:t.on_maintenance_due??!1,onChange:v=>h.mutate({on_maintenance_due:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_humidity_high??!1,onChange:v=>h.mutate({on_ams_humidity_high:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_temperature_high??!1,onChange:v=>h.mutate({on_ams_temperature_high:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_humidity_high??!1,onChange:v=>h.mutate({on_ams_ht_humidity_high:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_temperature_high??!1,onChange:v=>h.mutate({on_ams_ht_temperature_high:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Added"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),a.jsx($n,{checked:t.on_queue_job_added??!1,onChange:v=>h.mutate({on_queue_job_added:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),a.jsx($n,{checked:t.on_queue_job_assigned??!1,onChange:v=>h.mutate({on_queue_job_assigned:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Started"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),a.jsx($n,{checked:t.on_queue_job_started??!1,onChange:v=>h.mutate({on_queue_job_started:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),a.jsx($n,{checked:t.on_queue_job_waiting??!0,onChange:v=>h.mutate({on_queue_job_waiting:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),a.jsx($n,{checked:t.on_queue_job_skipped??!0,onChange:v=>h.mutate({on_queue_job_skipped:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),a.jsx($n,{checked:t.on_queue_job_failed??!0,onChange:v=>h.mutate({on_queue_job_failed:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),a.jsx($n,{checked:t.on_queue_completed??!1,onChange:v=>h.mutate({on_queue_completed:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(A1,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),a.jsx($n,{checked:t.quiet_hours_enabled,onChange:v=>h.mutate({quiet_hours_enabled:v})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xn,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[x(t.quiet_hours_start)||"22:00"," - ",x(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ai,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),a.jsx($n,{checked:t.daily_digest_enabled,onChange:v=>h.mutate({daily_digest_enabled:v})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xn,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:["Send at ",x(t.daily_digest_time)||"08:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(sf,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),r&&a.jsx(Pn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{f.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const ZW=[{value:"email",label:"Email",description:"SMTP email notifications"},{value:"telegram",label:"Telegram",description:"Notifications via Telegram bot"},{value:"discord",label:"Discord",description:"Send to Discord channel via webhook"},{value:"ntfy",label:"ntfy",description:"Free, self-hostable push notifications"},{value:"pushover",label:"Pushover",description:"Simple, reliable push notifications"},{value:"callmebot",label:"CallMeBot/WhatsApp",description:"Free WhatsApp notifications via CallMeBot"},{value:"webhook",label:"Webhook",description:"Generic HTTP POST to any URL"}];function UQe({provider:t,onClose:e}){const n=Zt(),r=!!t,[i,s]=w.useState(t?.name||""),[o,l]=w.useState(t?.provider_type||"email"),[c,u]=w.useState(t?.printer_id||null),[d,h]=w.useState(t?.quiet_hours_enabled||!1),[f,p]=w.useState(t?.quiet_hours_start||"22:00"),[x,v]=w.useState(t?.quiet_hours_end||"07:00"),[b,y]=w.useState(t?.daily_digest_enabled||!1),[S,N]=w.useState(t?.daily_digest_time||"08:00"),[M,k]=w.useState(t?.on_print_start??!1),[T,C]=w.useState(t?.on_print_complete??!0),[j,E]=w.useState(t?.on_print_failed??!0),[P,U]=w.useState(t?.on_print_stopped??!0),[L,B]=w.useState(t?.on_print_progress??!1),[D,H]=w.useState(t?.on_printer_offline??!1),[G,I]=w.useState(t?.on_printer_error??!1),[K,Q]=w.useState(t?.on_filament_low??!1),[ae,V]=w.useState(t?.on_maintenance_due??!1),[Y,ne]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([q,ie])=>[q,String(ie)])):{}),[ee,ve]=w.useState(null),[fe,de]=w.useState(null),{data:Re}=et({queryKey:["printers"],queryFn:se.getPrinters});w.useEffect(()=>{const q=ie=>{ie.key==="Escape"&&e()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[e]);const ue=ot({mutationFn:()=>se.testNotificationConfig({provider_type:o,config:Y}),onSuccess:q=>{ve(q),de(null)},onError:q=>{ve({success:!1,message:q.message})}}),le=ot({mutationFn:q=>se.createNotificationProvider(q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),Ne=ot({mutationFn:q=>se.updateNotificationProvider(t.id,q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),J=q=>{if(q.preventDefault(),de(null),!i.trim()){de("Name is required");return}const ie=X(o);for(const he of ie)if(!Y[he.key]?.trim()){de(`${he.label} is required`);return}const te={name:i.trim(),provider_type:o,config:Y,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?f:null,quiet_hours_end:d?x:null,daily_digest_enabled:b,daily_digest_time:b?S:null,on_print_start:M,on_print_complete:T,on_print_failed:j,on_print_stopped:P,on_print_progress:L,on_printer_offline:D,on_printer_error:G,on_filament_low:K,on_maintenance_due:ae};r?Ne.mutate(te):le.mutate(te)},Le=le.isPending||Ne.isPending,$=q=>{switch(q){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:ie=>ie.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:ie=>ie.payload_format!=="slack"}];default:return[]}},X=q=>$(q).filter(ie=>ie.required),ce=$(o);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:q=>q.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:J,className:"p-6 space-y-4",children:[fe&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:fe}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:i,onChange:q=>s(q.target.value),placeholder:"My Notifications",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),a.jsx("select",{value:o,onChange:q=>{l(q.target.value),ne({}),ve(null)},disabled:r,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none disabled:opacity-50",children:ZW.map(q=>a.jsx("option",{value:q.value,children:q.label},q.value))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ZW.find(q=>q.value===o)?.description})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),ce.filter(q=>!("showIf"in q)||q.showIf?.(Y)!==!1).map(q=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[q.label," ",q.required&&"*"]}),q.type==="select"&&"options"in q&&q.options?a.jsx("select",{value:Y[q.key]||q.options[0]?.value||"",onChange:ie=>{ne({...Y,[q.key]:ie.target.value}),ve(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:q.options.map(ie=>a.jsx("option",{value:ie.value,children:ie.label},ie.value))}):a.jsx("input",{type:q.type,value:Y[q.key]||"",onChange:ie=>{ne({...Y,[q.key]:ie.target.value}),ve(null)},placeholder:q.placeholder,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]},q.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>{ve(null),ue.mutate()},disabled:ue.isPending||!Y[X(o)[0]?.key],className:"flex-1",children:[ue.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(rk,{className:"w-4 h-4"}),"Test Configuration"]})}),ee&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ee.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:ee.success?a.jsxs(a.Fragment,{children:[a.jsx(gr,{className:"w-5 h-5"}),a.jsx("span",{children:ee.message})]}):a.jsxs(a.Fragment,{children:[a.jsx(ha,{className:"w-5 h-5"}),a.jsx("span",{children:ee.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),a.jsxs("select",{value:c??"",onChange:q=>u(q.target.value?Number(q.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"All printers"}),Re?.map(q=>a.jsx("option",{value:q.id,children:q.name},q.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),a.jsx($n,{checked:d,onChange:h})]}),d&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),a.jsx("input",{type:"time",value:f,onChange:q=>p(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),a.jsx("input",{type:"time",value:x,onChange:q=>v(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),a.jsx($n,{checked:b,onChange:y})]}),b&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),a.jsx("input",{type:"time",value:S,onChange:q=>N(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Start"}),a.jsx($n,{checked:M,onChange:k})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Complete"}),a.jsx($n,{checked:T,onChange:C})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Failed"}),a.jsx($n,{checked:j,onChange:E})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Stopped"}),a.jsx($n,{checked:P,onChange:U})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:"Progress"}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),a.jsx($n,{checked:L,onChange:B})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Offline"}),a.jsx($n,{checked:D,onChange:H})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Error"}),a.jsx($n,{checked:G,onChange:I})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:K,onChange:Q})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),a.jsx($n,{checked:ae,onChange:V})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Te,{type:"submit",disabled:Le,className:"flex-1",children:[Le?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(xs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function BQe({template:t,onClose:e}){const n=Zt(),r=w.useRef(null),[i,s]=w.useState(t.title_template),[o,l]=w.useState(t.body_template),[c,u]=w.useState(null),[d,h]=w.useState(!0),{data:f}=et({queryKey:["template-variables"],queryFn:se.getTemplateVariables}),p=f?.find(k=>k.event_type===t.event_type),{data:x,isLoading:v}=et({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>se.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});w.useEffect(()=>{const k=T=>{T.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[e]);const b=ot({mutationFn:k=>se.updateNotificationTemplate(t.id,k),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:k=>{u(k.message)}}),y=ot({mutationFn:()=>se.resetNotificationTemplate(t.id),onSuccess:k=>{s(k.title_template),l(k.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:k=>{u(k.message)}}),S=k=>{if(k.preventDefault(),u(null),!i.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}b.mutate({title_template:i,body_template:o})},N=k=>{const T=r.current;if(!T)return;const C=T.selectionStart,j=T.selectionEnd,E=o,P=E.substring(0,C),U=E.substring(j),L=P+`{${k}}`+U;l(L),setTimeout(()=>{T.focus();const B=C+k.length+2;T.setSelectionRange(B,B)},0)},M=i!==t.title_template||o!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Rt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:S,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),a.jsx("input",{type:"text",value:i,onChange:k=>s(k.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:"Notification title..."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),a.jsx("textarea",{ref:r,value:o,onChange:k=>l(k.target.value),rows:4,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none",placeholder:"Notification body..."})]}),p&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:p.variables.map(k=>a.jsxs("button",{type:"button",onClick:()=>N(k),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(rr,{className:"w-3 h-3"}),k]},k))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4"}),"Live Preview"]}),a.jsx("button",{type:"button",onClick:()=>h(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:v?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):x?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),a.jsx("div",{className:"text-white font-medium",children:x.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:x.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Te,{type:"button",variant:"ghost",onClick:()=>y.mutate(),disabled:y.isPending,className:"text-orange-400 hover:text-orange-300",children:[y.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Do,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),a.jsxs(Te,{onClick:S,disabled:b.isPending||!M,children:[b.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(xs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const HQe={print_start:"Print Started",print_complete:"Print Complete",print_failed:"Print Failed",print_stopped:"Print Stopped",print_progress:"Progress",printer_offline:"Printer Offline",printer_error:"Printer Error",filament_low:"Low Filament",maintenance_due:"Maintenance Due",test:"Test"},$Qe={print_start:"text-blue-400",print_complete:"text-bambu-green",print_failed:"text-red-400",print_stopped:"text-orange-400",print_progress:"text-yellow-400",printer_offline:"text-gray-400",printer_error:"text-rose-400",filament_low:"text-cyan-400",maintenance_due:"text-purple-400",test:"text-bambu-gray"};function VQe({onClose:t}){const e=Zt(),{showToast:n}=hn(),[r,i]=w.useState(7),[s,o]=w.useState(null),[l,c]=w.useState(!1),{data:u}=et({queryKey:["settings"],queryFn:se.getSettings}),d=u?.time_format||"system",{data:h,isLoading:f,refetch:p,isRefetching:x}=et({queryKey:["notification-logs",r,l],queryFn:()=>se.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:v}=et({queryKey:["notification-log-stats",r],queryFn:()=>se.getNotificationLogStats(r)}),b=ot({mutationFn:()=>se.clearNotificationLogs(30),onSuccess:S=>{n(S.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:S=>{n(`Failed to clear logs: ${S.message}`,"error")}}),y=S=>{const N=Ji(S);if(!N)return"";const k=new Date().getTime()-N.getTime();return k<6e4?"Just now":k<36e5?`${Math.floor(k/6e4)}m ago`:k<864e5?`${Math.floor(k/36e5)}h ago`:N.toLocaleDateString()+" "+Xpe(N,d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(x0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),v&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",a.jsx("span",{className:"text-white font-medium",children:v.total})," notifications"]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(gr,{className:"w-4 h-4"}),v.success_count," sent"]}),v.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(ha,{className:"w-4 h-4"}),v.failure_count," failed"]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:r,onChange:S=>i(Number(S.target.value)),className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:[a.jsx("option",{value:1,children:"Last 24 hours"}),a.jsx("option",{value:7,children:"Last 7 days"}),a.jsx("option",{value:30,children:"Last 30 days"}),a.jsx("option",{value:90,children:"Last 90 days"})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:l,onChange:S=>c(S.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),"Show failed only"]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>p(),disabled:x,children:[x?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Ur,{className:"w-4 h-4"}),"Refresh"]}),a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>b.mutate(),disabled:b.isPending,className:"text-red-400 hover:text-red-300",children:[b.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),"Clear Old"]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):h&&h.length>0?a.jsx("div",{className:"space-y-2",children:h.map(S=>a.jsx(GQe,{log:S,isExpanded:s===S.id,onToggle:()=>o(s===S.id?null:S.id),formatDate:y,formatFullDate:N=>mb(N,d)},S.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(x0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function GQe({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){return a.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[a.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?a.jsx(gr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx(ha,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${$Qe[t.event_type]||"text-bambu-gray"}`,children:HQe[t.event_type]||t.event_type}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(Wl,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(Jn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsxs("span",{children:["Provider: ",t.provider_type]}),a.jsxs("span",{children:["Time: ",i(t.created_at)]})]})]})]})}function qQe({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Ut();w.useEffect(()=>{const u=d=>{d.key==="Escape"&&r()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r]);const c=u=>{e({...t,group_ids:t.group_ids.includes(u)?t.group_ids.filter(d=>d!==u):[...t.group_ids,u]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(_t,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Rt,{className:"w-5 h-5"})})]})}),a.jsxs(Nt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:u=>e({...t,username:u.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:u=>e({...t,email:u.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(u=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(u.id),onChange:()=>c(u.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:u.name}),u.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},u.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Te,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(rr,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function WQe(){const{t}=Ut(),e=Zt(),{showToast:n}=hn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[u,d]=w.useState(!1),[h,f]=w.useState(!0),[p,x]=w.useState("all"),[v,b]=w.useState(!1),[y,S]=w.useState(!1),{data:N,isLoading:M}=et({queryKey:["spoolman-settings"],queryFn:se.getSpoolmanSettings}),{data:k,isLoading:T,refetch:C}=et({queryKey:["spoolman-status"],queryFn:se.getSpoolmanStatus,refetchInterval:3e4}),{data:j}=et({queryKey:["printers"],queryFn:se.getPrinters});w.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),d(N.spoolman_disable_weight_sync==="true"),f(N.spoolman_report_partial_usage!=="false"),b(!0))},[N]),w.useEffect(()=>{if(!v||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==u||N.spoolman_report_partial_usage!=="false"!==h){const Q=setTimeout(()=>{E.mutate()},500);return()=>clearTimeout(Q)}},[r,s,l,u,h,v]);const E=ot({mutationFn:()=>se.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:u?"true":"false",spoolman_report_partial_usage:h?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),n(t("settings.toast.settingsSaved"))}}),P=ot({mutationFn:se.connectSpoolman,onSuccess:()=>{C()}}),U=ot({mutationFn:se.disconnectSpoolman,onSuccess:()=>{C()}}),L=ot({mutationFn:se.syncAllPrintersAms,onSuccess:K=>{K.success}}),B=ot({mutationFn:K=>se.syncPrinterAms(K),onSuccess:K=>{K.success}}),D=()=>{p==="all"?L.mutate():B.mutate(p)},H=L.isPending||B.isPending,G=p==="all"?L.data:B.data,I=p==="all"?L.isSuccess:B.isSuccess;return M?a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ec,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(Nt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ec,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),E.isPending&&a.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(ra,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),a.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(Xr,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&a.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Zs,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[a.jsx("li",{children:t("settings.builtInFeatureRfid")}),a.jsx("li",{children:t("settings.builtInFeatureUsage")}),a.jsx("li",{children:t("settings.builtInFeatureCatalog")}),a.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),r&&a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:t("settings.syncInfoRfidOnly")}),a.jsx("li",{children:t("settings.syncInfoAutoCreate")}),a.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),a.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:K=>o(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),a.jsxs("select",{value:l,onChange:K=>c(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),a.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u,onChange:K=>d(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),u&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:h,onChange:K=>f(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),T?a.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):k?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx(Yr,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Rt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),a.jsx("div",{className:"flex gap-2",children:k?.connected?a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:[U.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Cme,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(Te,{size:"sm",onClick:()=>P.mutate(),disabled:P.isPending||!s,children:[P.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Dh,{className:"w-4 h-4"}),t("settings.connect")]})})]}),P.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:P.error.message}),k?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:p,onChange:K=>x(K.target.value==="all"?"all":Number(K.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"all",children:t("settings.allPrinters")}),j?.map(K=>a.jsx("option",{value:K.id,children:K.name},K.id))]}),a.jsx(Jn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:D,disabled:H,children:[H?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Ur,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),I&&G&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${G.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:G.success?`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} successfully`:`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} with ${G.errors.length} error${G.errors.length!==1?"s":""}`}),G.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Mn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[G.skipped_count," spool",G.skipped_count!==1?"s":""," skipped"]})]}),G.skipped_count>5&&a.jsx("button",{onClick:()=>S(!y),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:y?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(y?G.skipped:G.skipped.slice(0,5)).map((K,Q)=>a.jsxs("li",{className:"flex items-center gap-2",children:[K.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${K.color}`}}),a.jsx("span",{children:K.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",K.reason]})]},Q)),!y&&G.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",G.skipped_count-5," more"]})]})]}),G.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:G.errors.map((K,Q)=>a.jsx("li",{children:K},Q))})]})]})]})]})]})]})}function KQe(){const{t}=Ut(),{showToast:e}=hn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,b]=w.useState(""),[y,S]=w.useState(!1),[N,M]=w.useState(null),[k,T]=w.useState(!1),C=w.useCallback(async()=>{try{const I=await se.getSpoolCatalog();r(I)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{C()},[C]);const j=n.filter(I=>I.name.toLowerCase().includes(o.toLowerCase())),E=async()=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const I=await se.addCatalogEntry({name:p.trim(),weight:parseInt(v)});r(K=>[...K,I].sort((Q,ae)=>Q.name.localeCompare(ae.name))),d(!1),x(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{S(!1)}},P=I=>{f(I.id),x(I.name),b(I.weight.toString())},U=()=>{f(null),x(""),b("")},L=async I=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const K=await se.updateCatalogEntry(I,{name:p.trim(),weight:parseInt(v)});r(Q=>Q.map(ae=>ae.id===I?K:ae).sort((ae,V)=>ae.name.localeCompare(V.name))),f(null),x(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{S(!1)}},B=async()=>{if(N)try{await se.deleteCatalogEntry(N.id),r(I=>I.filter(K=>K.id!==N.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{M(null)}},D=async()=>{T(!1),s(!0);try{await se.resetSpoolCatalog(),await C(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},H=()=>{const I=n.map(({name:V,weight:Y})=>({name:V,weight:Y})),K=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),Q=URL.createObjectURL(K),ae=document.createElement("a");ae.href=Q,ae.download="spool-catalog.json",document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(Q),e(t("settings.catalog.exported",{count:n.length}),"success")},G=async I=>{const K=I.target.files?.[0];if(K){try{const Q=await K.text(),ae=JSON.parse(Q);if(!Array.isArray(ae))throw new Error("Invalid format");let V=0,Y=0;for(const ne of ae){if(!ne.name||typeof ne.weight!="number"){Y++;continue}if(n.some(ve=>ve.name.toLowerCase()===ne.name.toLowerCase())){Y++;continue}try{const ve=await se.addCatalogEntry({name:ne.name,weight:ne.weight});r(fe=>[...fe,ve].sort((de,Re)=>de.name.localeCompare(Re.name))),V++}catch{Y++}}e(t("settings.catalog.imported",{added:V,skipped:Y}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(_t,{children:[a.jsxs(An,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Ec,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:H,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[a.jsx(ui,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[a.jsx(sa,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:G}),a.jsxs("button",{onClick:()=>T(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[a.jsx(Do,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>d(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:I=>l(I.target.value)})]}),u&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:p,onChange:I=>x(I.target.value)})}),a.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:v,onChange:I=>b(I.target.value)}),a.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),a.jsxs("button",{onClick:E,disabled:y,className:"px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center gap-1 shrink-0",children:[y?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Yr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{d(!1),x(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Rt,{className:"w-4 h-4"})})]})]}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),a.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),a.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),a.jsx("th",{className:"px-4 py-2 w-24"})]})}),a.jsx("tbody",{children:j.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):j.map(I=>a.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:h===I.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:p,onChange:K=>x(K.target.value)})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:v,onChange:K=>b(K.target.value)})}),a.jsx("td",{className:"px-4 py-2 text-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>L(I.id),disabled:y,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:y?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Yr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:U,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Rt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-4 py-2 text-white",children:I.name}),a.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[I.weight,"g"]}),a.jsx("td",{className:"px-4 py-2 text-center",children:I.is_default?a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>P(I),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>M(I),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(en,{className:"w-4 h-4"})})]})})]})},I.id))})]})})]}),N&&a.jsx(Pn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:N.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:B,onCancel:()=>M(null)}),k&&a.jsx(Pn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:D,onCancel:()=>T(!1)})]})}function XQe(){const{t}=Ut(),{showToast:e}=hn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),[c,u]=w.useState("Bambu Lab"),d=w.useRef(null),[h,f]=w.useState(!1),[p,x]=w.useState(null),[v,b]=w.useState(""),[y,S]=w.useState(""),[N,M]=w.useState("#FFFFFF"),[k,T]=w.useState(""),[C,j]=w.useState(!1),[E,P]=w.useState(!1),[U,L]=w.useState(null),[B,D]=w.useState(null),[H,G]=w.useState(!1),I=w.useCallback(async()=>{try{const le=await se.getColorCatalog();r(le)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{I()},[I]);const K=[...new Set(n.map(le=>le.manufacturer))].sort(),Q=n.filter(le=>{const Ne=o===""||le.manufacturer.toLowerCase().includes(o.toLowerCase())||le.color_name.toLowerCase().includes(o.toLowerCase())||(le.material?.toLowerCase().includes(o.toLowerCase())??!1),J=c===""||le.manufacturer===c;return Ne&&J}),ae=()=>{b(""),S(""),M("#FFFFFF"),T("")},V=async()=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const le=await se.addColorEntry({manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:k.trim()||null});r(Ne=>[...Ne,le].sort((J,Le)=>J.manufacturer.localeCompare(Le.manufacturer)||(J.material||"").localeCompare(Le.material||"")||J.color_name.localeCompare(Le.color_name))),f(!1),ae(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{j(!1)}},Y=le=>{x(le.id),b(le.manufacturer),S(le.color_name),M(le.hex_color),T(le.material||"")},ne=()=>{x(null),ae()},ee=async le=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const Ne=await se.updateColorEntry(le,{manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:k.trim()||null});r(J=>J.map(Le=>Le.id===le?Ne:Le).sort((Le,$)=>Le.manufacturer.localeCompare($.manufacturer)||(Le.material||"").localeCompare($.material||"")||Le.color_name.localeCompare($.color_name))),x(null),ae(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{j(!1)}},ve=async()=>{if(B)try{await se.deleteColorEntry(B.id),r(le=>le.filter(Ne=>Ne.id!==B.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{D(null)}},fe=async()=>{G(!1),s(!0);try{await se.resetColorCatalog(),await I(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},de=async()=>{P(!0),L(null);try{const le={},Ne=id();Ne&&(le.Authorization=`Bearer ${Ne}`);const J=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:le});if(!J.ok)throw new Error("Failed to start sync");const Le=J.body?.getReader();if(!Le)throw new Error("No response body");const $=new TextDecoder;let X="";for(;;){const{done:ce,value:q}=await Le.read();if(ce)break;X+=$.decode(q,{stream:!0});const ie=X.split(` + `,children:a.jsxs("div",{className:"flex items-center gap-4 p-4",children:[j&&d&&a.jsx("button",{onClick:P=>{P.stopPropagation(),d()},className:`flex items-center justify-center w-6 h-6 rounded border transition-colors ${u?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:u&&a.jsx(Yr,{className:"w-4 h-4"})}),j?a.jsx("div",{...b,...y,className:"flex items-center justify-center w-10 h-10 md:w-8 md:h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation",children:a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}):e!==void 0?a.jsxs("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium",children:["#",e]}):a.jsx("div",{className:"w-8"}),a.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?a.jsx("img",{src:t.plate_id!=null?se.getArchivePlateThumbnail(t.archive_id,t.plate_id):se.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?a.jsx("img",{src:t.plate_id!=null?se.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):se.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:a.jsx(is,{className:"w-6 h-6"})})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("p",{className:"text-white font-medium truncate",children:t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`}),t.archive_id?a.jsx(Xs,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewArchive"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):t.library_file_id?a.jsx(Xs,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:x("queue.viewInFileManager"),children:a.jsx(Xr,{className:"w-3.5 h-3.5"})}):null]}),a.jsxs("div",{className:"flex items-center gap-3 text-sm text-bambu-gray",children:[a.jsxs("span",{className:`flex items-center gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model?"text-blue-400":""}`,children:[a.jsx(Cr,{className:"w-3.5 h-3.5"}),t.target_model?`${x("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?x("queue.filter.unassigned"):t.printer_name||`${x("common.printer")} #${t.printer_id}`]}),t.print_time_seconds&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Iu,{className:"w-3.5 h-3.5"}),jae(t.print_time_seconds)]}),t.created_by_username&&a.jsxs("span",{className:"flex items-center gap-1.5",title:x("queue.addedBy",{name:t.created_by_username}),children:[a.jsx(rd,{className:"w-3.5 h-3.5"}),t.created_by_username]}),j&&!t.manual_start&&a.jsxs("span",{className:"flex items-center gap-1.5",children:[a.jsx(Xn,{className:"w-3.5 h-3.5"}),gQe(t.scheduled_time,c,x)]})]}),a.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.manual_start&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-purple-500/10 text-purple-400 rounded-full border border-purple-500/20 flex items-center gap-1",children:[a.jsx(aX,{className:"w-3 h-3"}),x("queue.badges.staged")]}),t.require_previous_success&&a.jsx("span",{className:"text-xs px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:x("queue.badges.requiresPrevious")}),t.auto_off_after&&a.jsxs("span",{className:"text-xs px-2 py-0.5 bg-blue-500/10 text-blue-400 rounded-full border border-blue-500/20 flex items-center gap-1",children:[a.jsx(fd,{className:"w-3 h-3"}),x("queue.badges.autoPowerOff")]})]}),C&&a.jsxs("div",{className:"mt-3",children:[a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:a.jsx("div",{className:"h-full bg-gradient-to-r from-blue-500 to-blue-400 animate-pulse w-full opacity-50"})}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:x("queue.printingInProgress")})]}),t.waiting_reason&&t.status==="pending"&&a.jsxs("p",{className:"text-xs text-purple-400 mt-2 flex items-start gap-1",children:[a.jsx(Bi,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),a.jsx("span",{children:t.waiting_reason})]}),t.error_message&&a.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[a.jsx(Bi,{className:"w-3 h-3"}),t.error_message]})]}),a.jsx(bQe,{status:t.status,waitingReason:t.waiting_reason,printerState:p,t:x}),a.jsxs("div",{className:"flex items-center gap-1",children:[C&&a.jsx(Te,{variant:"ghost",size:"sm",onClick:s,disabled:!h("printers:control"),title:h("printers:control")?x("queue.actions.stopPrint"):x("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(ehe,{className:"w-4 h-4"})}),j&&a.jsxs(a.Fragment,{children:[t.manual_start&&a.jsx(Te,{variant:"ghost",size:"sm",onClick:l,disabled:!h("printers:control"),title:h("printers:control")?x("queue.actions.startPrint"):x("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:a.jsx(jo,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:n,disabled:!f("queue","update",t.created_by_id),title:f("queue","update",t.created_by_id)?x("common.edit"):x("queue.permissions.noEdit"),children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:r,disabled:!f("queue","delete",t.created_by_id),title:f("queue","delete",t.created_by_id)?x("common.cancel"):x("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:a.jsx(Rt,{className:"w-4 h-4"})})]}),E&&a.jsxs(a.Fragment,{children:[a.jsx(Te,{variant:"ghost",size:"sm",onClick:o,disabled:!h("queue:create"),title:h("queue:create")?x("queue.actions.requeue"):x("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:a.jsx(Ur,{className:"w-4 h-4"})}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:i,disabled:!f("queue","delete",t.created_by_id),title:f("queue","delete",t.created_by_id)?x("common.remove"):x("queue.permissions.noRemove"),children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})})}function yQe(){const{t}=Ut(),e=Zt(),{showToast:n}=hn(),{hasPermission:r,hasAnyPermission:i,canModify:s}=Fr(),[o,l]=w.useState(null),[c,u]=w.useState(""),[d,h]=w.useState(""),[f,p]=w.useState(!1),[x,v]=w.useState(null),[b,y]=w.useState(null),[S,N]=w.useState(null),[M,k]=w.useState([]),[T,C]=w.useState(!1),[j,E]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[P,U]=w.useState(()=>{const Z=localStorage.getItem("queue.historySortAsc");return Z!==null?Z==="true":!1}),[L,B]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[D,H]=w.useState(()=>{const Z=localStorage.getItem("queue.pendingSortAsc");return Z!==null?Z==="true":!0});w.useEffect(()=>{localStorage.setItem("queue.historySortBy",j)},[j]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(P))},[P]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",L)},[L]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(D))},[D]);const G=oae(UC(jM,{activationConstraint:{distance:8}}),UC(PM,{coordinateGetter:Eae})),{data:I}=et({queryKey:["settings"],queryFn:se.getSettings}),K=I?.time_format||"system",{data:Q,isLoading:ae}=et({queryKey:["queue",o,c],queryFn:()=>se.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:V}=et({queryKey:["printers"],queryFn:()=>se.getPrinters()}),Y=ot({mutationFn:Z=>se.cancelQueueItem(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),ne=ot({mutationFn:Z=>se.removeFromQueue(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),ee=ot({mutationFn:Z=>se.stopQueueItem(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),ve=ot({mutationFn:Z=>se.startQueueItem(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),fe=ot({mutationFn:Z=>se.reorderQueue(Z),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),de=ot({mutationFn:async()=>{const Z=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];for(const z of Z)await se.removeFromQueue(z.id);return Z.length},onSuccess:Z=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:Z}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),Re=ot({mutationFn:Z=>se.bulkUpdateQueue(Z),onSuccess:Z=>{e.invalidateQueries({queryKey:["queue"]}),k([]),C(!1),n(Z.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),ue=ot({mutationFn:async Z=>{for(const z of Z)await se.cancelQueueItem(z);return Z.length},onSuccess:Z=>{e.invalidateQueries({queryKey:["queue"]}),k([]),n(t("queue.toast.bulkCancelled",{count:Z}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),le=Z=>{k(z=>z.includes(Z)?z.filter(F=>F!==Z):[...z,Z])},Ne=w.useMemo(()=>{const Z=new Set;return V?.forEach(z=>{z.location&&Z.add(z.location)}),Q?.forEach(z=>{z.target_location&&Z.add(z.target_location)}),Array.from(Z).sort()},[V,Q]),J=w.useCallback(Z=>d?Z.target_location?Z.target_location===d:Z.printer_id?V?.find(F=>F.id===Z.printer_id)?.location===d:!1:!0,[d,V]),Le=w.useMemo(()=>{let Z=Q?.filter(F=>F.status==="pending")||[];d&&(Z=Z.filter(J));const z=F=>{if(!F.scheduled_time)return 0;const W=new Date(F.scheduled_time).getTime(),me=Date.now()+4320*60*60*1e3;return W>me?0:W};return[...Z].sort((F,W)=>{let me;if(L==="name"){const _e=F.archive_name||F.library_file_name||"",be=W.archive_name||W.library_file_name||"";me=_e.localeCompare(be)}else L==="printer"?me=(F.printer_name||"").localeCompare(W.printer_name||""):L==="time"?me=z(F)-z(W):me=F.position-W.position;return D?me:-me})},[Q,L,D,J,d]),$=()=>{const Z=Le.map(z=>z.id);M.length===Z.length?k([]):k(Z)},X=w.useMemo(()=>{let Z=Q?.filter(z=>z.status==="printing")||[];return d&&(Z=Z.filter(J)),Z},[Q,d,J]),ce=w.useMemo(()=>{const Z=new Set;return X.forEach(z=>{z.printer_id&&Z.add(z.printer_id)}),Array.from(Z)},[X]),q=kF({queries:ce.map(Z=>({queryKey:["printerStatus",Z],queryFn:()=>se.getPrinterStatus(Z),refetchInterval:5e3}))}),ie=w.useMemo(()=>{const Z={};return ce.forEach((z,F)=>{const W=q[F];W?.data?.state&&(Z[z]=W.data.state)}),Z},[ce,q]),te=w.useMemo(()=>{let Z=Q?.filter(z=>["completed","failed","skipped","cancelled"].includes(z.status))||[];return d&&(Z=Z.filter(J)),[...Z].sort((z,F)=>{let W;if(j==="name"){const me=z.archive_name||z.library_file_name||"",_e=F.archive_name||F.library_file_name||"";W=me.localeCompare(_e)}else j==="printer"?W=(z.printer_name||"").localeCompare(F.printer_name||""):W=new Date(F.completed_at||F.created_at).getTime()-new Date(z.completed_at||z.created_at).getTime();return P?-W:W})},[Q,j,P,J,d]),he=w.useMemo(()=>Le.reduce((Z,z)=>Z+(z.print_time_seconds||0),0),[Le]),ge=Z=>{const{active:z,over:F}=Z;if(!F||z.id===F.id)return;const W=Le.findIndex(_e=>_e.id===z.id),me=Le.findIndex(_e=>_e.id===F.id);if(W!==-1&&me!==-1){const be=FM(Le,W,me).map((He,Se)=>({id:He.id,position:Se+1}));fe.mutate(be)}};return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsx("div",{className:"flex items-center justify-between mb-8",children:a.jsxs("div",{children:[a.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[a.jsx(sX,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),a.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[a.jsx(_t,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:a.jsx(jo,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:X.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.printing")})]})]})})}),a.jsx(_t,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center",children:a.jsx(Xn,{className:"w-5 h-5 text-yellow-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:Le.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.queued")})]})]})})}),a.jsx(_t,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center",children:a.jsx(Iu,{className:"w-5 h-5 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:jae(he)}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.totalTime")})]})]})})}),a.jsx(_t,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:a.jsx(Nt,{className:"p-4",children:a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-500/20 flex items-center justify-center",children:a.jsx(gr,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-2xl font-bold text-white",children:te.length}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.history")})]})]})})})]}),a.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:o===-1?"unassigned":o||"",onChange:Z=>{const z=Z.target.value;l(z==="unassigned"?-1:z===""?null:Number(z))},children:[a.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),a.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),V?.map(Z=>a.jsx("option",{value:Z.id,children:Z.name},Z.id))]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:Z=>u(Z.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allStatus")}),a.jsx("option",{value:"pending",children:t("queue.status.pending")}),a.jsx("option",{value:"printing",children:t("queue.status.printing")}),a.jsx("option",{value:"completed",children:t("queue.status.completed")}),a.jsx("option",{value:"failed",children:t("queue.status.failed")}),a.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),a.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Ne.length>0&&a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:d,onChange:Z=>h(Z.target.value),children:[a.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Ne.map(Z=>a.jsx("option",{value:Z,children:Z},Z))]}),a.jsx("div",{className:"flex-1"}),te.length>0&&a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>p(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[a.jsx(en,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),ae?a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Q?.length===0?a.jsxs(_t,{className:"p-12 text-center border-dashed",children:[a.jsx(ai,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),a.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),a.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):a.jsxs("div",{className:"space-y-8",children:[X.length>0&&a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white mb-4 flex items-center gap-2",children:[a.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),a.jsx("div",{className:"space-y-3",children:X.map(Z=>a.jsx(Dj,{item:Z,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:Z}),onRequeue:()=>{},onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,printerState:Z.printer_id?ie[Z.printer_id]:null,t},Z.id))})]}),Le.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Xn,{className:"w-5 h-5 text-yellow-400"}),t("queue.sections.queued"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:Le.length}),")"]}),a.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:L,onChange:Z=>B(Z.target.value),children:[a.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),a.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>H(!D),title:t(D?"common.ascending":"common.descending"),className:"px-2",children:D?a.jsx(jf,{className:"w-4 h-4"}):a.jsx(lb,{className:"w-4 h-4"})})]})]}),a.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-bambu-dark rounded-lg",children:[a.jsxs(Te,{variant:"ghost",size:"sm",onClick:$,className:"flex items-center gap-2",children:[M.length===Le.length&&Le.length>0?a.jsx(ao,{className:"w-4 h-4 text-bambu-green"}):a.jsx(gl,{className:"w-4 h-4"}),M.length===Le.length&&Le.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),M.length>0&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:M.length})}),a.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),a.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>C(!0),className:"flex items-center gap-2 text-bambu-green hover:text-bambu-green-light",disabled:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?void 0:t("queue.permissions.noEditItems"),children:[a.jsx($i,{className:"w-4 h-4"}),t("queue.bulkEdit.editSelected")]}),a.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>ue.mutate(M),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:ue.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?void 0:t("queue.permissions.noCancelItems"),children:[a.jsx(Rt,{className:"w-4 h-4"}),t("queue.bulkEdit.cancelSelected")]})]})]}),a.jsx(Nae,{sensors:G,collisionDetection:dae,onDragEnd:ge,children:a.jsx(Mae,{items:Le.map(Z=>Z.id),strategy:aQe,children:a.jsx("div",{className:"space-y-3",children:Le.map((Z,z)=>a.jsx(Dj,{item:Z,position:z+1,onEdit:()=>v(Z),onCancel:()=>N({type:"cancel",item:Z}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>ve.mutate(Z.id),timeFormat:K,isSelected:M.includes(Z.id),onToggleSelect:()=>le(Z.id),hasPermission:r,canModify:s,t},Z.id))})})})]}),te.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gr,{className:"w-5 h-5 text-bambu-gray"}),t("queue.sections.history"),a.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:te.length}),")"]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("select",{className:"px-3 py-1.5 text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:j,onChange:Z=>E(Z.target.value),children:[a.jsx("option",{value:"date",children:t("queue.sort.byDate")}),a.jsx("option",{value:"name",children:t("queue.sort.byName")}),a.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>U(!P),title:t(P?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:P?a.jsx(jf,{className:"w-4 h-4"}):a.jsx(lb,{className:"w-4 h-4"})})]})]}),a.jsx("div",{className:"space-y-3",children:te.slice(0,20).map((Z,z)=>a.jsx(Dj,{item:Z,position:z+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:Z}),onStop:()=>{},onRequeue:()=>y(Z),onStart:()=>{},timeFormat:K,hasPermission:r,canModify:s,t},Z.id))})]})]}),x&&a.jsx(Qu,{mode:"edit-queue-item",archiveId:x.archive_id??void 0,libraryFileId:x.library_file_id??void 0,archiveName:x.archive_name||x.library_file_name||`File #${x.archive_id||x.library_file_id}`,queueItem:x,onClose:()=>v(null)}),b&&a.jsx(Qu,{mode:"add-to-queue",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,onClose:()=>y(null)}),S&&a.jsx(Pn,{title:S.type==="cancel"?t("queue.confirm.cancelTitle"):S.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:S.type==="cancel"?t("queue.confirm.cancelMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):S.type==="stop"?t("queue.confirm.stopMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:S.type==="cancel"?t("queue.confirm.cancelButton"):S.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{S.type==="cancel"?Y.mutate(S.item.id):S.type==="stop"?ee.mutate(S.item.id):ne.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),f&&a.jsx(Pn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:te.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{de.mutate(),p(!1)},onCancel:()=>p(!1)}),T&&a.jsx(xQe,{selectedCount:M.length,printers:V?.map(Z=>({id:Z.id,name:Z.name}))||[],onSave:Z=>{Object.keys(Z).length>0&&Re.mutate({item_ids:M,...Z})},onClose:()=>C(!1),isSaving:Re.isPending,t})]})}function vQe({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const S=n.current;if(!S)return;const N=new ResizeObserver(M=>{const k=M[0]?.contentRect.width||0;i(k)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=w.useMemo(()=>{const S={};t.forEach(U=>{const L=U.split("T")[0];S[L]=(S[L]||0)+1});const N=new Date,M=new Date(N);M.setMonth(M.getMonth()-e),M.setDate(M.getDate()-M.getDay());const k=[],T=[];let C=[],j=-1;const E=new Date(M);let P=0;for(;E<=N;)E.getDay()===0&&C.length>0&&(k.push(C),C=[],P++),E.getMonth()!==j&&(T.push({month:E.toLocaleDateString("en-US",{month:"short"}),weekIndex:P}),j=E.getMonth()),C.push(new Date(E)),E.setDate(E.getDate()+1);return C.length>0&&k.push(C),{weeks:k,monthLabels:T,printCounts:S}},[t,e]),c=Math.max(1,...Object.values(l)),u=S=>{if(S===0)return"bg-bambu-dark";const N=S/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],h=s.length,f=32,p=2,x=r-f-16,v=h>0?Math.floor((x-(h-1)*p)/h):12,b=Math.max(8,Math.min(20,v)),y=b<=10?10:12;return a.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&a.jsxs("div",{children:[a.jsx("div",{className:"flex mb-1",style:{marginLeft:f+4},children:o.map(({month:S,weekIndex:N},M)=>a.jsx("div",{className:"text-bambu-gray",style:{fontSize:y,marginLeft:M===0?0:`${(N-(o[M-1]?.weekIndex||0))*(b+p)-24}px`},children:S},M))}),a.jsxs("div",{className:"flex",style:{gap:p},children:[a.jsx("div",{className:"flex flex-col",style:{gap:p,marginRight:4,width:f},children:d.map((S,N)=>a.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:f,height:b,fontSize:y,visibility:N%2===1?"visible":"hidden"},children:S},S))}),s.map((S,N)=>a.jsx("div",{className:"flex flex-col",style:{gap:p},children:[0,1,2,3,4,5,6].map(M=>{const k=S.find(E=>E.getDay()===M);if(!k)return a.jsx("div",{style:{width:b,height:b}},M);const T=k.toISOString().split("T")[0],C=l[T]||0,j=T===new Date().toISOString().split("T")[0];return a.jsx("div",{className:`rounded-sm ${u(C)} ${j?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${k.toLocaleDateString()}: ${C} print${C!==1?"s":""}`},M)})},N))]}),a.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:y},children:[a.jsx("span",{children:"Less"}),a.jsxs("div",{className:"flex",style:{gap:p},children:[a.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),a.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),a.jsx("span",{children:"More"})]})]})})}const $S=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function wQe(t){const e=new Date;switch(t){case"7d":return new Date(e.getTime()-10080*60*1e3);case"30d":return new Date(e.getTime()-720*60*60*1e3);case"90d":return new Date(e.getTime()-2160*60*60*1e3);case"365d":return new Date(e.getTime()-365*24*60*60*1e3);case"all":return new Date(0)}}function _Qe({archives:t,currency:e="$"}){const[n,r]=w.useState("30d"),i=w.useMemo(()=>{const p=wQe(n);return t.filter(x=>(Ji(x.completed_at||x.created_at)||new Date(0))>=p)},[t,n]),s=w.useMemo(()=>{const p=new Map;return i.forEach(x=>{const v=Ji(x.completed_at||x.created_at)||new Date,b=`${v.getFullYear()}-${String(v.getMonth()+1).padStart(2,"0")}-${String(v.getDate()).padStart(2,"0")}`,y=p.get(b)||{date:b,filament:0,cost:0,prints:0};y.filament+=x.filament_used_grams||0,y.cost+=x.cost||0,y.prints+=x.quantity||1,p.set(b,y)}),Array.from(p.values()).sort((x,v)=>x.date.localeCompare(v.date)).map(x=>({...x,dateLabel:new Date(x.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=w.useMemo(()=>{if(n==="7d"||n==="30d")return s;const p=new Map;return i.forEach(x=>{const v=Ji(x.completed_at||x.created_at)||new Date,b=new Date(v);b.setDate(v.getDate()-v.getDay());const y=`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`,S=p.get(y)||{week:y,filament:0,cost:0,prints:0};S.filament+=x.filament_used_grams||0,S.cost+=x.cost||0,S.prints+=x.quantity||1,p.set(y,S)}),Array.from(p.values()).sort((x,v)=>x.week.localeCompare(v.week)).map(x=>({date:x.week,dateLabel:`Week of ${new Date(x.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...x}))},[i,s,n]),l=w.useMemo(()=>{const p=new Map;return i.forEach(x=>{const b=(x.filament_type||"Unknown").split(", ");b.forEach(y=>{const S=(x.filament_used_grams||0)/b.length;p.set(y,(p.get(y)||0)+S)})}),Array.from(p.entries()).map(([x,v])=>({name:x,value:Math.round(v)})).sort((x,v)=>v.value-x.value)},[i]),c=w.useMemo(()=>{const p=new Date,x=[];for(let v=5;v>=0;v--){const b=new Date(p.getFullYear(),p.getMonth()-v,1),y=new Date(p.getFullYear(),p.getMonth()-v+1,0),S=b.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(M=>{const k=Ji(M.completed_at||M.created_at)||new Date(0);return k>=b&&k<=y});x.push({month:S,filament:Math.round(N.reduce((M,k)=>M+(k.filament_used_grams||0),0)),cost:N.reduce((M,k)=>M+(k.cost||0),0),prints:N.reduce((M,k)=>M+(k.quantity||1),0)})}return x},[t]),u=n==="7d"||n==="30d"?s:o,d=i.reduce((p,x)=>p+(x.filament_used_grams||0),0),h=i.reduce((p,x)=>p+(x.cost||0),0),f=i.reduce((p,x)=>p+(x.quantity||1),0);return a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),a.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(p=>a.jsx("button",{onClick:()=>r(p),className:`px-3 py-1 text-sm rounded-md transition-colors ${n===p?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:p==="all"?"All":p.replace("d","D")},p))})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Filament"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[(d/1e3).toFixed(2),"kg"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Cost"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[e,h.toFixed(2)]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[f," prints"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Avg per Print"}),a.jsxs("p",{className:"text-2xl font-bold text-white",children:[f>0?(d/f).toFixed(0):0,"g"]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,f>0?(h/f).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),a.jsx(l1,{width:"100%",height:250,children:a.jsxs(fHe,{data:u,children:[a.jsx("defs",{children:a.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[a.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),a.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),a.jsx(ON,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(BN,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),a.jsx(HN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),a.jsx(u1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:p=>[`${Number(p??0).toFixed(0)}g`,"Filament"]}),a.jsx(Rte,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):a.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?a.jsxs("div",{className:"flex items-center gap-4",children:[a.jsx(l1,{width:160,height:160,children:a.jsxs(hHe,{children:[a.jsx(ste,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((p,x)=>a.jsx(Iv,{fill:$S[x%$S.length]},`cell-${x}`))}),a.jsx(u1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:p=>[`${p??0}g`,"Usage"]})]})}),a.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((p,x)=>{const v=l.reduce((y,S)=>y+S.value,0),b=v>0?(p.value/v*100).toFixed(0):0;return a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:$S[x%$S.length]}}),a.jsx("span",{className:"text-white truncate flex-1",children:p.name}),a.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[b,"%"]})]},p.name)})})]}):a.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[a.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),a.jsx(l1,{width:"100%",height:200,children:a.jsxs(eHe,{data:c,children:[a.jsx(ON,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),a.jsx(BN,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),a.jsx(HN,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),a.jsx(u1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(p,x)=>[x==="filament"?`${p??0}g`:x==="cost"?`${e}${Number(p??0).toFixed(2)}`:p??0,x==="filament"?"Filament":x==="cost"?"Cost":"Prints"]}),a.jsx(BL,{}),a.jsx(zte,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function SQe({id:t,title:e,component:n,isHidden:r,size:i,onToggleVisibility:s,onToggleSize:o}){const{attributes:l,listeners:c,setNodeRef:u,transform:d,transition:h,isDragging:f}=Tae({id:t}),p={transform:Ob.Transform.toString(d),transition:h,opacity:f?.5:1};return r?null:a.jsxs("div",{ref:u,style:{...p,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{...l,...c,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),a.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[a.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:`Size: ${i===1?"1/4":i===2?"1/2":"Full"} - Click to cycle`,children:i===4?a.jsx(EF,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):a.jsx(TF,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),a.jsx("button",{onClick:s,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:a.jsx(uv,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),a.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function NQe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:s}){const o=()=>{const M={};return t.forEach(k=>{M[k.id]=k.defaultSize||4}),M},[l,c]=w.useState(()=>{const M=localStorage.getItem(e);if(M)try{const k=JSON.parse(M);return k.sizes||(k.sizes=o()),k}catch{}return{order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:o()}}),[u,d]=w.useState(!1);w.useEffect(()=>{const M=()=>d(k=>!k);return window.addEventListener("toggle-hidden-panel",M),()=>window.removeEventListener("toggle-hidden-panel",M)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),w.useEffect(()=>{const k=t.map(T=>T.id).filter(T=>!l.order.includes(T));k.length>0&&c(T=>({...T,order:[...T.order,...k]}))},[t,l.order]);const h=oae(UC(jM,{activationConstraint:{distance:8}}),UC(PM,{coordinateGetter:Eae})),f=M=>{const{active:k,over:T}=M;T&&k.id!==T.id&&c(C=>{const j=C.order.indexOf(k.id),E=C.order.indexOf(T.id);return{...C,order:FM(C.order,j,E)}})},p=M=>{c(k=>({...k,hidden:k.hidden.includes(M)?k.hidden.filter(T=>T!==M):[...k.hidden,M]}))},x=M=>{c(k=>{const T=k.sizes[M]||4,C=T===1?2:T===2?4:1;return{...k,sizes:{...k.sizes,[M]:C}}})},v=()=>{const M={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:o()};c(M),i?.()},b=l.order.map(M=>t.find(k=>k.id===M)).filter(Boolean),y=b.filter(M=>!l.hidden.includes(M.id)),S=b.filter(M=>l.hidden.includes(M.id)),N=s?.({hiddenCount:S.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:v});return a.jsxs("div",{className:"space-y-4",children:[N,!r&&!s&&a.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.jsxs(Te,{variant:"secondary",size:"sm",onClick:v,children:[a.jsx(Do,{className:"w-4 h-4"}),"Reset Layout"]}),S.length>0&&a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[a.jsx(Xl,{className:"w-4 h-4"}),S.length," Hidden"]})]}),u&&S.length>0&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(M=>a.jsxs("button",{onClick:()=>p(M.id),className:"px-3 py-1.5 bg-bambu-dark-tertiary hover:bg-bambu-green/20 rounded-lg text-sm text-white transition-colors flex items-center gap-2",children:[a.jsx(Xl,{className:"w-3 h-3"}),M.title]},M.id))})]}),a.jsx(Nae,{sensors:h,collisionDetection:dae,onDragEnd:f,children:a.jsx(Mae,{items:y.map(M=>M.id),strategy:dI,children:a.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:y.map(M=>a.jsx(SQe,{id:M.id,title:M.title,component:M.component,isHidden:l.hidden.includes(M.id),size:l.sizes[M.id]||2,onToggleVisibility:()=>p(M.id),onToggleSize:()=>x(M.id)},M.id))})})}),y.length===0&&a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx("p",{children:"All widgets are hidden."}),a.jsx(Te,{className:"mt-4",onClick:v,children:"Reset Layout"})]})]})}const CQe={USD:"$",EUR:"€",GBP:"£",CHF:"Fr.",JPY:"¥",CNY:"¥",CAD:"$",AUD:"$",INR:"₹",HKD:"HK$",KRW:"₩",SEK:"kr",NOK:"kr",DKK:"kr",PLN:"zł",BRL:"R$",TWD:"NT$",SGD:"S$",NZD:"NZ$",MXN:"MX$",CZK:"Kč",THB:"฿",ZAR:"R",TRY:"₺",RUB:"₽"};function ju(t){return CQe[t.toUpperCase()]||t}const kQe=[{code:"USD",label:"USD ($)"},{code:"EUR",label:"EUR (€)"},{code:"GBP",label:"GBP (£)"},{code:"CHF",label:"CHF (Fr.)"},{code:"JPY",label:"JPY (¥)"},{code:"CNY",label:"CNY (¥)"},{code:"CAD",label:"CAD ($)"},{code:"AUD",label:"AUD ($)"},{code:"INR",label:"INR (₹)"},{code:"HKD",label:"HKD (HK$)"},{code:"KRW",label:"KRW (₩)"},{code:"SEK",label:"SEK (kr)"},{code:"NOK",label:"NOK (kr)"},{code:"DKK",label:"DKK (kr)"},{code:"PLN",label:"PLN (zł)"},{code:"BRL",label:"BRL (R$)"},{code:"TWD",label:"TWD (NT$)"},{code:"SGD",label:"SGD (S$)"},{code:"NZD",label:"NZD (NZ$)"},{code:"MXN",label:"MXN (MX$)"},{code:"CZK",label:"CZK (Kč)"},{code:"THB",label:"THB (฿)"},{code:"ZAR",label:"ZAR (R)"},{code:"TRY",label:"TRY (₺)"},{code:"RUB",label:"RUB (₽)"}];function MQe({stats:t,currency:e,t:n}){return a.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:a.jsx(ra,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),a.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:a.jsx(Xn,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:a.jsx(ra,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:a.jsx(o3,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:a.jsx(qh,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(2)||"0.00"," kWh"]})]})]}),a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:a.jsx(o3,{className:"w-5 h-5"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),a.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function AQe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,s=n===1?112:n===2?128:144,o=s/2-8,l=o*2*Math.PI;return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:s,height:s},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:s/2,cy:s/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${i/100*l} ${l}`})]}),a.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i,"%"]})})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gr,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ha,{className:"w-4 h-4 text-status-error flex-shrink-0"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),a.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]})]}),n>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&a.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),a.jsx("div",{className:`grid gap-x-6 gap-y-1 ${n===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([c,u])=>a.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),a.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function TQe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.average_time_accuracy;if(i==null)return a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(v=>v>=95&&v<=105?"#00ae42":v>105?"#3b82f6":"#f97316")(i),u=i-100,d=n===1?112:n===2?128:144,h=d/2-8,f=h*2*Math.PI,p=n===1?3:n===2?6:999,x=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,p):[];return a.jsxs("div",{className:"flex items-center gap-6",children:[a.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[a.jsxs("svg",{className:"w-full h-full -rotate-90",children:[a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),a.jsx("circle",{cx:d/2,cy:d/2,r:h,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*f} ${f}`})]}),a.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[a.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),a.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[a.jsx(dX,{className:"w-3 h-3 flex-shrink-0"}),a.jsx("span",{children:r("stats.perfectEstimate")})]}),x.length>0&&a.jsx("div",{className:`mt-2 ${n===4?"grid grid-cols-3 gap-x-6 gap-y-1":n===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:x.map(([v,b])=>a.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[a.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(v)||`${r("common.printer")} ${v}`}),a.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},v))})]})]})}function EQe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noFilamentData")});const r=Object.entries(t.prints_by_filament_type).sort(([,l],[,c])=>c-l),i=e===1?5:e===2?8:999,s=r.slice(0,i),o=r.length>i;return e===4&&s.length>4?a.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),a.jsx("span",{className:"text-bambu-gray",children:c})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):a.jsxs("div",{className:"space-y-3",children:[s.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return a.jsxs("div",{children:[a.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[a.jsx("span",{className:"text-white",children:l}),a.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),a.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:a.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&a.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-i})})]})}function PQe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return a.jsx(vQe,{printDates:t,months:n})}function jQe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):a.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,i])=>a.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:a.jsx(Cr,{className:"w-4 h-4 text-bambu-green"})}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[i," ",n("common.prints")]})]})]},r))})}function DQe({archives:t,currency:e,t:n}){return!t||t.length===0?a.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):a.jsx(_Qe,{archives:t,currency:e})}function RQe({size:t=1,t:e}){const{data:n,isLoading:r}=et({queryKey:["failureAnalysis"],queryFn:()=>se.getFailureAnalysis({days:30})});if(r)return a.jsx("div",{className:"flex justify-center py-4",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return a.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const i=t===1?5:t===2?8:999,s=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=s.slice(0,i),l=s.length>i;return a.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[a.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[a.jsx("div",{className:"flex items-center gap-4",children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Mn,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),a.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),a.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:e("stats.failedPrintsCount",{failed:n.failed_prints,total:n.total_prints})}),n.trend&&n.trend.length>=2&&a.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx(DF,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate0&&a.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[a.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),a.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),a.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:s.length-i})})]})]})}function FQe(){const{t}=Ut(),{showToast:e}=hn(),{hasPermission:n}=Fr(),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(0),[u,d]=w.useState(0),[h,f]=w.useState(!1);w.useEffect(()=>{const E=()=>{try{const U=localStorage.getItem("bambusy-dashboard-layout");if(U){const L=JSON.parse(U);d(L.hidden?.length||0)}}catch{d(0)}};E(),window.addEventListener("storage",E);const P=setInterval(E,500);return()=>{window.removeEventListener("storage",E),clearInterval(P)}},[l]);const{data:p,isLoading:x,refetch:v}=et({queryKey:["archiveStats"],queryFn:se.getArchiveStats}),{data:b}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:y}=et({queryKey:["archives"],queryFn:()=>se.getArchives(void 0,void 0,1e3,0)}),{data:S}=et({queryKey:["settings"],queryFn:se.getSettings}),N=async E=>{o(!1),i(!0);try{const{blob:P,filename:U}=await se.exportStats({format:E,days:90}),L=URL.createObjectURL(P),B=document.createElement("a");B.href=L,B.download=U,B.click(),URL.revokeObjectURL(L),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{i(!1)}},M=async()=>{f(!0);try{const E=await se.recalculateCosts();await v(),e(t("stats.recalculatedCosts",{count:E.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},k=ju(S?.currency||"USD"),T=new Map(b?.map(E=>[String(E.id),E.name])||[]),C=y?.map(E=>E.created_at)||[];if(x)return a.jsx("div",{className:"p-4 md:p-8",children:a.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const j=[{id:"quick-stats",title:t("stats.quickStats"),component:a.jsx(MQe,{stats:p,currency:k,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:E=>a.jsx(AQe,{stats:p,printerMap:T,size:E,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:E=>a.jsx(TQe,{stats:p,printerMap:T,size:E,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:E=>a.jsx(EQe,{stats:p,size:E,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:E=>a.jsx(RQe,{size:E,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:E=>a.jsx(PQe,{printDates:C,size:E}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:a.jsx(jQe,{stats:p,printerMap:T,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:a.jsx(DQe,{archives:y||[],currency:k,t}),defaultSize:4}];return a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[a.jsxs("div",{children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),a.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&a.jsxs(Te,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[a.jsx(Xl,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),a.jsxs(Te,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(E=>E+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[a.jsx(Do,{className:"w-4 h-4"}),t("stats.resetLayout")]}),a.jsxs(Te,{variant:"secondary",onClick:M,disabled:h||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[h?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Dde,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),a.jsxs("div",{className:"relative",children:[a.jsxs(Te,{variant:"secondary",onClick:()=>o(!s),disabled:r,children:[r?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(M1,{className:"w-4 h-4"}),t("stats.exportStats")]}),s&&a.jsxs("div",{className:"absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20",children:[a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg",onClick:()=>N("csv"),children:[a.jsx(Ps,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),a.jsxs("button",{className:"w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg",onClick:()=>N("xlsx"),children:[a.jsx(M1,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),a.jsx(NQe,{widgets:j,storageKey:"bambusy-dashboard-layout",hideControls:!0},l)]})}function LQe({plug:t,onEdit:e}){const{t:n}=Ut(),r=Zt(),{showToast:i}=hn(),[s,o]=w.useState(!1),[l,c]=w.useState(!1),[u,d]=w.useState(!1),[h,f]=w.useState(!1),{data:p,isLoading:x}=et({queryKey:["smart-plug-status",t.id],queryFn:()=>se.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:v}=et({queryKey:["printers"],queryFn:se.getPrinters}),b=v?.find(P=>P.id===t.printer_id),y=ot({mutationFn:P=>se.controlSmartPlug(t.id,P),onMutate:async P=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const U=r.getQueryData(["smart-plug-status",t.id]),L=P==="on"?"ON":P==="off"||p?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],B=>({...B,state:L})),{previousStatus:U}},onError:(P,U,L)=>{L?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],L.previousStatus),i(`Failed to turn ${U} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),S=ot({mutationFn:P=>se.updateSmartPlug(t.id,P),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=ot({mutationFn:()=>se.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),M=p?.state==="ON",k=t.plug_type==="mqtt"&&p?.energy?.power!==null&&p?.energy?.power!==void 0,T=(p?.reachable??!1)||k,C=y.isPending,E=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const P=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${P}/`:`http://${P}/`})();return a.jsxs(a.Fragment,{children:[a.jsx(_t,{className:"relative",children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[a.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?T?"bg-teal-500/20":"bg-red-500/20":T?M?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?a.jsx(PF,{className:`w-5 h-5 ${T?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?a.jsx(dv,{className:`w-5 h-5 ${T?M?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):a.jsx(dl,{className:`w-5 h-5 ${T?M?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),a.jsxs("div",{className:"min-w-0",children:[a.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray truncate",title:t.plug_type==="mqtt"?t.mqtt_topic??void 0:t.plug_type==="homeassistant"?t.ha_entity_id??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.ip_address})]})]}),a.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[x?a.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?a.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[a.jsx("span",{className:"px-1.5 py-0.5 bg-teal-500/20 text-teal-400 text-[10px] font-medium rounded flex-shrink-0",children:"MQTT"}),T&&a.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),a.jsx("span",{className:T?M?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?p?.state||"?":"Offline"})]}):T?a.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[a.jsx(Wg,{className:"w-4 h-4 text-status-ok"}),a.jsx("span",{className:M?"text-status-ok":"text-bambu-gray",children:p?.state||"Unknown"})]}):a.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[a.jsx(Ff,{className:"w-4 h-4"}),a.jsx("span",{children:n("smartPlugs.offline")})]}),E&&a.jsxs("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 px-2 py-0.5 bg-bambu-dark hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white text-xs rounded-full transition-colors",title:n("smartPlugs.openPlugAdminPage"),children:[a.jsx(Xr,{className:"w-3 h-3"}),n("smartPlugs.admin")]})]})]}),b&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),a.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&a.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded-full",children:[a.jsx(Xl,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded-full",children:[a.jsx(Gg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&a.jsxs("span",{className:"flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded-full",children:[a.jsx(ai,{className:"w-3 h-3"}),t.schedule_on_time&&t.schedule_off_time?`${t.schedule_on_time} - ${t.schedule_off_time}`:t.schedule_on_time?`On ${t.schedule_on_time}`:`Off ${t.schedule_off_time}`]})]}),t.plug_type!=="mqtt"&&a.jsxs("div",{className:"flex gap-2 mb-3",children:[a.jsxs(Te,{size:"sm",variant:M?"primary":"secondary",disabled:!T||C,onClick:()=>c(!0),className:"flex-1",children:[C?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(fd,{className:"w-4 h-4"}),"On"]}),a.jsxs(Te,{size:"sm",variant:M?"secondary":"primary",disabled:!T||C,onClick:()=>d(!0),className:"flex-1",children:[C?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(nk,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&p?.energy&&a.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[p.energy.power!==null&&p.energy.power!==void 0&&a.jsxs("div",{className:"flex-1 text-center",children:[a.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(p.energy.power),"W"]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),p.energy.today!==null&&p.energy.today!==void 0&&a.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-lg font-semibold text-white",children:p.energy.today.toFixed(2)}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),a.jsxs("button",{onClick:()=>f(!h),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(nd,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),a.jsx("span",{children:h?"-":"+"})]}),h&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(hv,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:P=>S.mutate({show_in_switchbar:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.plug_type!=="mqtt"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.enabled,onChange:P=>S.mutate({enabled:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto On"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:P=>S.mutate({auto_on:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:P=>S.mutate({auto_off:P.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),t.auto_off&&a.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(Xn,{className:"w-4 h-4"}),"Time"]}),a.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[a.jsx(ak,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),a.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:P=>S.mutate({off_delay_minutes:parseInt(P.target.value)||5}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"})]}):a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),a.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:P=>S.mutate({off_temp_threshold:parseInt(P.target.value)||70}),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(sf,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),s&&a.jsx(Pn,{title:n("smartPlugs.deleteSmartPlug"),message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&a.jsx(Pn,{title:n("smartPlugs.turnOnSmartPlug"),message:`Are you sure you want to turn on "${t.name}"?`,confirmText:n("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{y.mutate("on"),c(!1)},onCancel:()=>c(!1)}),u&&a.jsx(Pn,{title:n("smartPlugs.turnOffSmartPlug"),message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:n("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{y.mutate("off"),d(!1)},onCancel:()=>d(!1)})]})}function OQe({plug:t,onClose:e}){const{t:n}=Ut(),r=Zt(),i=!!t,[s,o]=w.useState(t?.plug_type||"tasmota"),[l,c]=w.useState(t?.name||""),[u,d]=w.useState(t?.ip_address||""),[h,f]=w.useState(t?.username||""),[p,x]=w.useState(t?.password||""),[v,b]=w.useState(t?.ha_entity_id||""),[y,S]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,M]=w.useState(t?.mqtt_power_path||""),[k,T]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,j]=w.useState(t?.mqtt_energy_topic||""),[E,P]=w.useState(t?.mqtt_energy_path||""),[U,L]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[B,D]=w.useState(t?.mqtt_state_topic||""),[H,G]=w.useState(t?.mqtt_state_path||""),[I,K]=w.useState(t?.mqtt_state_on_value||""),[Q,ae]=w.useState(t?.ha_power_entity||""),[V,Y]=w.useState(t?.ha_energy_today_entity||""),[ne,ee]=w.useState(t?.ha_energy_total_entity||""),[ve,fe]=w.useState(""),[de,Re]=w.useState(""),[ue,le]=w.useState(!1),Ne=w.useRef(null),[J,Le]=w.useState(""),[$,X]=w.useState(!1),ce=w.useRef(null),[q,ie]=w.useState(""),[te,he]=w.useState(!1),ge=w.useRef(null),[Z,z]=w.useState(""),[F,W]=w.useState(!1),me=w.useRef(null),[_e,be]=w.useState(t?.printer_id||null),[He,Se]=w.useState(null),[$e,Qe]=w.useState(null),[ye,we]=w.useState(t?.power_alert_enabled||!1),[Ce,Ue]=w.useState(t?.power_alert_high?.toString()||""),[je,Ve]=w.useState(t?.power_alert_low?.toString()||""),[Ae,Ze]=w.useState(t?.schedule_enabled||!1),[Pe,Xe]=w.useState(t?.schedule_on_time||""),[Fe,Oe]=w.useState(t?.schedule_off_time||""),[Me,Je]=w.useState(t?.show_in_switchbar||!1),[yt,Mt]=w.useState(t?.show_on_printer_card??!0),[an,Pt]=w.useState(!1),[Ie,gt]=w.useState({scanned:0,total:0}),[Qt,tn]=w.useState([]),un=w.useRef(null),{data:hr}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:yr}=et({queryKey:["smart-plugs"],queryFn:se.getSmartPlugs}),{data:sr}=et({queryKey:["settings"],queryFn:se.getSettings}),Xt=!!(sr?.ha_enabled&&sr?.ha_url&&sr?.ha_token);w.useEffect(()=>{const xe=setTimeout(()=>{Re(ve)},300);return()=>clearTimeout(xe)},[ve]),w.useEffect(()=>{const xe=at=>{Ne.current&&!Ne.current.contains(at.target)&&le(!1),ce.current&&!ce.current.contains(at.target)&&X(!1),ge.current&&!ge.current.contains(at.target)&&he(!1),me.current&&!me.current.contains(at.target)&&W(!1)};return document.addEventListener("mousedown",xe),()=>document.removeEventListener("mousedown",xe)},[]);const{data:or,isLoading:yi,error:Ia}=et({queryKey:["ha-entities",de],queryFn:()=>se.getHAEntities(de||void 0),enabled:s==="homeassistant"&&Xt,retry:!1,staleTime:0}),{data:De}=et({queryKey:["ha-sensor-entities"],queryFn:se.getHASensorEntities,enabled:s==="homeassistant"&&Xt,retry:!1,staleTime:0});w.useEffect(()=>{const xe=at=>{at.key==="Escape"&&e()};return window.addEventListener("keydown",xe),()=>{window.removeEventListener("keydown",xe),un.current&&clearInterval(un.current)}},[e]);const nt=async()=>{Pt(!0),tn([]),gt({scanned:0,total:0}),Qe(null);try{await se.startTasmotaScan();const xe=async()=>{try{const at=await se.getTasmotaScanStatus();gt({scanned:at.scanned,total:at.total});const ht=await se.getDiscoveredTasmotaDevices();tn(ht),at.running||(Pt(!1),un.current&&(clearInterval(un.current),un.current=null))}catch(at){console.error("Polling error:",at)}};await xe(),un.current=setInterval(xe,500)}catch(xe){Pt(!1);const at=xe instanceof Error?xe.message:typeof xe=="string"?xe:JSON.stringify(xe);Qe(at||"Failed to start scan")}},dt=async()=>{try{await se.stopTasmotaScan()}catch{}Pt(!1),un.current&&(clearInterval(un.current),un.current=null)},pt=xe=>{d(xe.ip_address),c(xe.name),Se(null)},lt=ot({mutationFn:()=>se.testSmartPlugConnection(u,h||null,p||null),onSuccess:xe=>{Se(xe),Qe(null),!l&&xe.device_name&&c(xe.device_name)},onError:xe=>{Se(null),Qe(xe.message)}}),Ft=ot({mutationFn:xe=>se.createSmartPlug(xe),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:xe=>{Qe(xe.message)}}),pe=ot({mutationFn:xe=>se.updateSmartPlug(t.id,xe),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:xe=>{Qe(xe.message)}}),ze=hr?.filter(xe=>s==="tasmota"?!yr?.some(ht=>ht.printer_id===xe.id&&ht.id!==t?.id&&ht.plug_type==="tasmota"):!0),Ke=xe=>{if(xe.preventDefault(),Qe(null),!l.trim()){Qe("Name is required");return}if(s==="tasmota"&&!u.trim()){Qe("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!v){Qe("Entity is required for Home Assistant plugs");return}if(s==="mqtt"){const ht=y.trim(),rt=C.trim(),At=B.trim();if(!ht&&!rt&&!At){Qe("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const at={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?u.trim():null,ha_entity_id:s==="homeassistant"?v:null,ha_power_entity:s==="homeassistant"&&Q||null,ha_energy_today_entity:s==="homeassistant"&&V||null,ha_energy_total_entity:s==="homeassistant"&&ne||null,mqtt_power_topic:s==="mqtt"&&y.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(k)||1,mqtt_energy_topic:s==="mqtt"&&C.trim()||null,mqtt_energy_path:s==="mqtt"&&E.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(U)||1,mqtt_state_topic:s==="mqtt"&&B.trim()||null,mqtt_state_path:s==="mqtt"&&H.trim()||null,mqtt_state_on_value:s==="mqtt"&&I.trim()||null,username:s==="tasmota"&&h.trim()||null,password:s==="tasmota"&&p.trim()||null,printer_id:_e,power_alert_enabled:ye,power_alert_high:Ce?parseFloat(Ce):null,power_alert_low:je?parseFloat(je):null,schedule_enabled:Ae,schedule_on_time:Pe||null,schedule_off_time:Fe||null,show_in_switchbar:Me,show_on_printer_card:yt};i?pe.mutate(at):Ft.mutate(at)},Ge=Ft.isPending||pe.isPending;return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md max-h-[90vh] flex flex-col",onClick:xe=>xe.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Smart Plug":"Add Smart Plug"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Ke,className:"p-6 space-y-4 overflow-y-auto",children:[$e&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:$e}),!i&&a.jsxs("div",{className:"flex gap-2 mb-2",children:[a.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Se(null),Qe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(dl,{className:"w-4 h-4"}),"Tasmota"]}),a.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Se(null),Qe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(dv,{className:"w-4 h-4"}),"HA"]}),a.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Se(null),Qe(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[a.jsx(PF,{className:"w-4 h-4"}),"MQTT"]})]}),!i&&s==="tasmota"&&a.jsxs("div",{className:"space-y-3",children:[an?a.jsxs(Te,{type:"button",variant:"secondary",onClick:dt,className:"w-full",children:[a.jsx(Rt,{className:"w-4 h-4"}),"Stop Scanning"]}):a.jsxs(Te,{type:"button",variant:"primary",onClick:nt,className:"w-full",children:[a.jsx(Br,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),an&&Ie.total>0&&a.jsxs("div",{className:"space-y-1",children:[a.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[a.jsx("span",{children:n("smartPlugs.addSmartPlug.scanningNetwork")}),a.jsxs("span",{children:[Ie.scanned," / ",Ie.total]})]}),a.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Ie.scanned/Ie.total*100}%`}})})]}),Qt.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",Qt.length," device(s) - click to select:"]}),a.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Qt.map(xe=>a.jsxs("button",{type:"button",onClick:()=>pt(xe),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dl,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:xe.name}),a.jsx("p",{className:"text-xs text-bambu-gray",children:xe.ip_address})]})]}),xe.state&&a.jsxs("span",{className:`flex items-center gap-1 text-xs ${xe.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[a.jsx(fd,{className:"w-3 h-3"}),xe.state]})]},xe.ip_address))})]}),!an&&Qt.length===0&&Ie.total>0&&a.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),s==="homeassistant"&&a.jsxs("div",{className:"space-y-3",children:[!Xt&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["Home Assistant is not configured. Set it up in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),a.jsx("select",{disabled:!0,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray cursor-not-allowed opacity-50",children:a.jsx("option",{children:n("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),Xt&&a.jsxs(a.Fragment,{children:[yi&&a.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[a.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Ia&&a.jsxs("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:["Failed to load entities: ",Ia.message]}),(()=>{const xe=yr?.filter(rt=>rt.ha_entity_id&&rt.id!==t?.id).map(rt=>rt.ha_entity_id)||[],at=(or||[]).filter(rt=>!xe.includes(rt.entity_id)),ht=or?.find(rt=>rt.entity_id===v);return a.jsxs("div",{ref:Ne,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:ue?ve:ht?`${ht.friendly_name} (${ht.entity_id})`:"",onChange:rt=>{fe(rt.target.value),ue||le(!0)},onFocus:()=>{le(!0),fe("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),v&&!ue&&a.jsx("button",{type:"button",onClick:()=>{b(""),fe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),yi&&a.jsx(it,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),ue&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[yi&&a.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!yi&&at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:de?`No entities found matching "${de}"`:"No entities available"}),!yi&&at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{b(rt.entity_id),le(!1),fe(""),l||c(rt.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${rt.entity_id===v?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[a.jsx("span",{children:rt.entity_id}),a.jsx("span",{className:rt.state==="on"?"text-bambu-green":"",children:rt.state})]})]},rt.entity_id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:de?`Searching all entities (${at.length} found)`:`Showing switch, light, input_boolean (${at.length} available)`})]})})(),v&&De&&De.length>0&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const xe=De.filter(rt=>rt.unit_of_measurement==="W"||rt.unit_of_measurement==="kW"||rt.unit_of_measurement==="mW"),at=J?xe.filter(rt=>rt.entity_id.toLowerCase().includes(J.toLowerCase())||rt.friendly_name.toLowerCase().includes(J.toLowerCase())):xe,ht=De.find(rt=>rt.entity_id===Q);return a.jsxs("div",{ref:ce,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:$?J:ht?`${ht.friendly_name} (${ht.state} ${ht.unit_of_measurement})`:"",onChange:rt=>{Le(rt.target.value),$||X(!0)},onFocus:()=>{X(!0),Le("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Q&&!$&&a.jsx("button",{type:"button",onClick:()=>{ae(""),Le("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),$&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{ae(""),X(!1),Le("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{ae(rt.entity_id),X(!1),Le("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===Q?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),at=q?xe.filter(rt=>rt.entity_id.toLowerCase().includes(q.toLowerCase())||rt.friendly_name.toLowerCase().includes(q.toLowerCase())):xe,ht=De.find(rt=>rt.entity_id===V);return a.jsxs("div",{ref:ge,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:te?q:ht?`${ht.friendly_name} (${ht.state} ${ht.unit_of_measurement})`:"",onChange:rt=>{ie(rt.target.value),te||he(!0)},onFocus:()=>{he(!0),ie("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),V&&!te&&a.jsx("button",{type:"button",onClick:()=>{Y(""),ie("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),te&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{Y(""),he(!1),ie("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{Y(rt.entity_id),he(!1),ie("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===V?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=De.filter(rt=>rt.unit_of_measurement==="kWh"||rt.unit_of_measurement==="Wh"||rt.unit_of_measurement==="MWh"),at=Z?xe.filter(rt=>rt.entity_id.toLowerCase().includes(Z.toLowerCase())||rt.friendly_name.toLowerCase().includes(Z.toLowerCase())):xe,ht=De.find(rt=>rt.entity_id===ne);return a.jsxs("div",{ref:me,className:"relative",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),a.jsx("input",{type:"text",value:F?Z:ht?`${ht.friendly_name} (${ht.state} ${ht.unit_of_measurement})`:"",onChange:rt=>{z(rt.target.value),F||W(!0)},onFocus:()=>{W(!0),z("")},placeholder:n("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ne&&!F&&a.jsx("button",{type:"button",onClick:()=>{ee(""),z("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:a.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),F&&a.jsxs("div",{className:"absolute z-50 w-full mt-1 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg shadow-lg max-h-48 overflow-y-auto",children:[a.jsx("button",{type:"button",onClick:()=>{ee(""),W(!1),z("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),at.map(rt=>a.jsxs("button",{type:"button",onClick:()=>{ee(rt.entity_id),W(!1),z("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${rt.entity_id===ne?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[a.jsx("div",{className:"font-medium",children:rt.friendly_name}),a.jsxs("div",{className:"text-xs text-bambu-gray",children:[rt.entity_id," • ",rt.state," ",rt.unit_of_measurement]})]},rt.entity_id)),at.length===0&&a.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),s==="mqtt"&&a.jsxs("div",{className:"space-y-3",children:[!sr?.mqtt_broker&&a.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:["MQTT broker not configured. Set broker address in"," ",a.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),sr?.mqtt_broker&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),a.jsx("p",{className:"text-xs opacity-80",children:"MQTT plugs receive power/energy data via MQTT subscription. On/off control is not available - use your MQTT broker or home automation system."})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:y,onChange:xe=>S(xe.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:N,onChange:xe=>M(xe.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:k,onChange:xe=>T(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:['JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.',a.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:C,onChange:xe=>j(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:E,onChange:xe=>P(xe.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),a.jsx("input",{type:"text",value:U,onChange:xe=>L(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),a.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",a.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),a.jsx("input",{type:"text",value:B,onChange:xe=>D(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),a.jsx("input",{type:"text",value:H,onChange:xe=>G(xe.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),a.jsx("input",{type:"text",value:I,onChange:xe=>K(xe.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",a.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),s==="tasmota"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("input",{type:"text",value:u,onChange:xe=>{d(xe.target.value),Se(null)},placeholder:"192.168.1.100",className:"flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>lt.mutate(),disabled:!u.trim()||lt.isPending,children:[lt.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Wg,{className:"w-4 h-4"}),"Test"]})]})]}),s==="tasmota"&&He&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${He.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:He.success?a.jsxs(a.Fragment,{children:[a.jsx(gr,{className:"w-5 h-5"}),a.jsxs("div",{children:[a.jsx("p",{className:"font-medium",children:"Connected!"}),a.jsxs("p",{className:"text-sm opacity-80",children:[He.device_name&&`Device: ${He.device_name} - `,"State: ",He.state]})]})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ff,{className:"w-5 h-5"}),a.jsx("span",{children:n("smartPlugs.addSmartPlug.connectionFailed")})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:l,onChange:xe=>c(xe.target.value),placeholder:n("smartPlugs.addSmartPlug.placeholders.plugName"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s==="tasmota"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),a.jsx("input",{type:"text",value:h,onChange:xe=>f(xe.target.value),placeholder:"admin",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),a.jsx("input",{type:"password",value:p,onChange:xe=>x(xe.target.value),placeholder:"********",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),s!=="mqtt"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),a.jsxs("select",{value:_e??"",onChange:xe=>be(xe.target.value?Number(xe.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"No printer (manual control only)"}),ze?.map(xe=>a.jsx("option",{value:xe.id,children:xe.name},xe.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Gg,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:ye,onChange:xe=>we(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),ye&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),a.jsx("input",{type:"number",value:Ce,onChange:xe=>Ue(xe.target.value),placeholder:"e.g. 200",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),a.jsx("input",{type:"number",value:je,onChange:xe=>Ve(xe.target.value),placeholder:"e.g. 10",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),s!=="mqtt"&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xn,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ae,onChange:xe=>Ze(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),Ae&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),a.jsx("input",{type:"time",value:Pe,onChange:xe=>Xe(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),a.jsx("input",{type:"time",value:Fe,onChange:xe=>Oe(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Automatically turn the plug on/off at these times daily. Leave empty to skip that action."})]})]}),a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(hv,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Me,onChange:xe=>Je(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&a.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4 text-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white font-medium",children:"Show on Printer Card"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Display button on printer card"})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:yt,onChange:xe=>Mt(xe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Te,{type:"submit",disabled:Ge,className:"flex-1",children:[Ge?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(xs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function $n({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return a.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:n,onClick:r,className:`relative inline-flex w-11 h-7 md:w-9 md:h-5 rounded-full transition-colors flex-shrink-0 focus:outline-none focus:ring-2 focus:ring-bambu-green focus:ring-offset-2 focus:ring-offset-bambu-dark ${n?"bg-bambu-dark-tertiary/50 cursor-not-allowed opacity-50":t?"bg-bambu-green cursor-pointer":"bg-bambu-dark-tertiary cursor-pointer hover:bg-bambu-dark-tertiary/80"}`,children:a.jsx("span",{className:`pointer-events-none absolute top-[3px] md:top-[2px] left-[3px] md:left-[2px] w-5 h-5 md:w-4 md:h-4 bg-white rounded-full shadow transition-transform duration-200 ease-in-out ${t?"translate-x-4":"translate-x-0"}`})})}const IQe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function zQe({provider:t,onEdit:e}){const n=Zt(),[r,i]=w.useState(!1),[s,o]=w.useState(!1),[l,c]=w.useState(null),{data:u}=et({queryKey:["printers"],queryFn:se.getPrinters}),d=u?.find(v=>v.id===t.printer_id),h=ot({mutationFn:v=>se.updateNotificationProvider(t.id,v),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),f=ot({mutationFn:()=>se.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=ot({mutationFn:()=>se.testNotificationProvider(t.id),onSuccess:v=>{c(v),n.invalidateQueries({queryKey:["notification-providers"]})},onError:v=>{c({success:!1,message:v.message})}}),x=v=>v||"";return a.jsxs(a.Fragment,{children:[a.jsx(_t,{className:"relative",children:a.jsxs(Nt,{className:"p-4",children:[a.jsxs("div",{className:"flex items-start justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:a.jsx(Gg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),a.jsxs("div",{children:[a.jsx("h3",{className:"font-medium text-white",children:t.name}),a.jsx("p",{className:"text-sm text-bambu-gray",children:IQe[t.provider_type]||t.provider_type})]})]}),a.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&a.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",hb(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(Ji(t.last_error_at)?.getTime()||0)>(Ji(t.last_success)?.getTime()||0))&&a.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),a.jsx($n,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]})]}),d&&a.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),a.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&a.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),a.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:"Start"}),t.on_plate_not_empty&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:"Plate Check"}),t.on_print_complete&&a.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&a.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&a.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&a.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&a.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:"Low Filament"}),t.on_maintenance_due&&a.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:"Maintenance"}),t.on_ams_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:"AMS Humidity"}),t.on_ams_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:"AMS Temp"}),t.on_ams_ht_humidity_high&&a.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:"AMS-HT Humidity"}),t.on_ams_ht_temperature_high&&a.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:"AMS-HT Temp"}),t.quiet_hours_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[a.jsx(A1,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&a.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[a.jsx(ai,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),a.jsx("div",{className:"mb-3",children:a.jsxs(Te,{size:"sm",variant:"secondary",disabled:p.isPending,onClick:()=>{c(null),p.mutate()},className:"w-full",children:[p.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(rk,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&a.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${l.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[l.success?a.jsx(gr,{className:"w-4 h-4"}):a.jsx(ha,{className:"w-4 h-4"}),a.jsx("span",{children:l.message})]}),a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors border-t border-bambu-dark-tertiary",children:[a.jsxs("span",{className:"flex items-center gap-2",children:[a.jsx(nd,{className:"w-4 h-4"}),"Event Settings"]}),s?a.jsx(Wl,{className:"w-4 h-4"}):a.jsx(Jn,{className:"w-4 h-4"})]}),s&&a.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Enabled"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),a.jsx($n,{checked:t.enabled,onChange:v=>h.mutate({enabled:v})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Started"}),a.jsx($n,{checked:t.on_print_start,onChange:v=>h.mutate({on_print_start:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),a.jsx($n,{checked:t.on_plate_not_empty??!0,onChange:v=>h.mutate({on_plate_not_empty:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),a.jsx($n,{checked:t.on_print_complete,onChange:v=>h.mutate({on_print_complete:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),a.jsx($n,{checked:t.on_print_failed,onChange:v=>h.mutate({on_print_failed:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),a.jsx($n,{checked:t.on_print_stopped,onChange:v=>h.mutate({on_print_stopped:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),a.jsx($n,{checked:t.on_print_progress,onChange:v=>h.mutate({on_print_progress:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),a.jsx($n,{checked:t.on_printer_offline,onChange:v=>h.mutate({on_printer_offline:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),a.jsx($n,{checked:t.on_printer_error,onChange:v=>h.mutate({on_printer_error:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:t.on_filament_low,onChange:v=>h.mutate({on_filament_low:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),a.jsx($n,{checked:t.on_maintenance_due??!1,onChange:v=>h.mutate({on_maintenance_due:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_humidity_high??!1,onChange:v=>h.mutate({on_ams_humidity_high:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_temperature_high??!1,onChange:v=>h.mutate({on_ams_temperature_high:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_humidity_high??!1,onChange:v=>h.mutate({on_ams_ht_humidity_high:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),a.jsx($n,{checked:t.on_ams_ht_temperature_high??!1,onChange:v=>h.mutate({on_ams_ht_temperature_high:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Added"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),a.jsx($n,{checked:t.on_queue_job_added??!1,onChange:v=>h.mutate({on_queue_job_added:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),a.jsx($n,{checked:t.on_queue_job_assigned??!1,onChange:v=>h.mutate({on_queue_job_assigned:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Started"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),a.jsx($n,{checked:t.on_queue_job_started??!1,onChange:v=>h.mutate({on_queue_job_started:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),a.jsx($n,{checked:t.on_queue_job_waiting??!0,onChange:v=>h.mutate({on_queue_job_waiting:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),a.jsx($n,{checked:t.on_queue_job_skipped??!0,onChange:v=>h.mutate({on_queue_job_skipped:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),a.jsx($n,{checked:t.on_queue_job_failed??!0,onChange:v=>h.mutate({on_queue_job_failed:v})})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),a.jsx($n,{checked:t.on_queue_completed??!1,onChange:v=>h.mutate({on_queue_completed:v})})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(A1,{className:"w-4 h-4 text-purple-400"}),a.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),a.jsx($n,{checked:t.quiet_hours_enabled,onChange:v=>h.mutate({quiet_hours_enabled:v})})]}),t.quiet_hours_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xn,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:[x(t.quiet_hours_start)||"22:00"," - ",x(t.quiet_hours_end)||"07:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(ai,{className:"w-4 h-4 text-emerald-400"}),a.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),a.jsx($n,{checked:t.daily_digest_enabled,onChange:v=>h.mutate({daily_digest_enabled:v})})]}),t.daily_digest_enabled&&a.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Xn,{className:"w-4 h-4 text-bambu-gray"}),a.jsxs("span",{className:"text-sm text-white",children:["Send at ",x(t.daily_digest_time)||"08:00"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),a.jsxs("div",{className:"flex gap-2 pt-2",children:[a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[a.jsx(sf,{className:"w-4 h-4"}),"Edit"]}),a.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:a.jsx(en,{className:"w-4 h-4"})})]})]})]})}),r&&a.jsx(Pn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{f.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const ZW=[{value:"email",label:"Email",description:"SMTP email notifications"},{value:"telegram",label:"Telegram",description:"Notifications via Telegram bot"},{value:"discord",label:"Discord",description:"Send to Discord channel via webhook"},{value:"ntfy",label:"ntfy",description:"Free, self-hostable push notifications"},{value:"pushover",label:"Pushover",description:"Simple, reliable push notifications"},{value:"callmebot",label:"CallMeBot/WhatsApp",description:"Free WhatsApp notifications via CallMeBot"},{value:"webhook",label:"Webhook",description:"Generic HTTP POST to any URL"}];function UQe({provider:t,onClose:e}){const n=Zt(),r=!!t,[i,s]=w.useState(t?.name||""),[o,l]=w.useState(t?.provider_type||"email"),[c,u]=w.useState(t?.printer_id||null),[d,h]=w.useState(t?.quiet_hours_enabled||!1),[f,p]=w.useState(t?.quiet_hours_start||"22:00"),[x,v]=w.useState(t?.quiet_hours_end||"07:00"),[b,y]=w.useState(t?.daily_digest_enabled||!1),[S,N]=w.useState(t?.daily_digest_time||"08:00"),[M,k]=w.useState(t?.on_print_start??!1),[T,C]=w.useState(t?.on_print_complete??!0),[j,E]=w.useState(t?.on_print_failed??!0),[P,U]=w.useState(t?.on_print_stopped??!0),[L,B]=w.useState(t?.on_print_progress??!1),[D,H]=w.useState(t?.on_printer_offline??!1),[G,I]=w.useState(t?.on_printer_error??!1),[K,Q]=w.useState(t?.on_filament_low??!1),[ae,V]=w.useState(t?.on_maintenance_due??!1),[Y,ne]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([q,ie])=>[q,String(ie)])):{}),[ee,ve]=w.useState(null),[fe,de]=w.useState(null),{data:Re}=et({queryKey:["printers"],queryFn:se.getPrinters});w.useEffect(()=>{const q=ie=>{ie.key==="Escape"&&e()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[e]);const ue=ot({mutationFn:()=>se.testNotificationConfig({provider_type:o,config:Y}),onSuccess:q=>{ve(q),de(null)},onError:q=>{ve({success:!1,message:q.message})}}),le=ot({mutationFn:q=>se.createNotificationProvider(q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),Ne=ot({mutationFn:q=>se.updateNotificationProvider(t.id,q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),J=q=>{if(q.preventDefault(),de(null),!i.trim()){de("Name is required");return}const ie=X(o);for(const he of ie)if(!Y[he.key]?.trim()){de(`${he.label} is required`);return}const te={name:i.trim(),provider_type:o,config:Y,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?f:null,quiet_hours_end:d?x:null,daily_digest_enabled:b,daily_digest_time:b?S:null,on_print_start:M,on_print_complete:T,on_print_failed:j,on_print_stopped:P,on_print_progress:L,on_printer_offline:D,on_printer_error:G,on_filament_low:K,on_maintenance_due:ae};r?Ne.mutate(te):le.mutate(te)},Le=le.isPending||Ne.isPending,$=q=>{switch(q){case"callmebot":return[{key:"phone",label:"Phone Number",placeholder:"+1234567890",type:"text",required:!0},{key:"apikey",label:"API Key",placeholder:"Your CallMeBot API key",type:"text",required:!0}];case"ntfy":return[{key:"server",label:"Server URL",placeholder:"https://ntfy.sh",type:"text",required:!1},{key:"topic",label:"Topic",placeholder:"my-bambuddy",type:"text",required:!0},{key:"auth_token",label:"Auth Token",placeholder:"Optional authentication",type:"password",required:!1}];case"pushover":return[{key:"user_key",label:"User Key",placeholder:"Your Pushover user key",type:"text",required:!0},{key:"app_token",label:"App Token",placeholder:"Your Pushover app token",type:"text",required:!0},{key:"priority",label:"Priority",placeholder:"0 (normal)",type:"number",required:!1}];case"telegram":return[{key:"bot_token",label:"Bot Token",placeholder:"Bot token from @BotFather",type:"password",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"Your chat or group ID",type:"text",required:!0}];case"email":return[{key:"smtp_server",label:"SMTP Server",placeholder:"smtp.gmail.com",type:"text",required:!0},{key:"smtp_port",label:"SMTP Port",placeholder:"587",type:"number",required:!1},{key:"security",label:"Security",type:"select",required:!1,options:[{value:"starttls",label:"STARTTLS (Port 587)"},{value:"ssl",label:"SSL/TLS (Port 465)"},{value:"none",label:"None (Port 25)"}]},{key:"auth_enabled",label:"Authentication",type:"select",required:!1,options:[{value:"true",label:"Enabled"},{value:"false",label:"Disabled"}]},{key:"username",label:"Username",placeholder:"your@email.com",type:"text",required:!1},{key:"password",label:"Password",placeholder:"App password",type:"password",required:!1},{key:"from_email",label:"From Email",placeholder:"your@email.com",type:"text",required:!0},{key:"to_email",label:"To Email",placeholder:"recipient@email.com",type:"text",required:!0}];case"discord":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://discord.com/api/webhooks/...",type:"text",required:!0}];case"webhook":return[{key:"webhook_url",label:"Webhook URL",placeholder:"https://example.com/webhook",type:"text",required:!0},{key:"payload_format",label:"Payload Format",type:"select",required:!1,options:[{value:"generic",label:"Generic JSON"},{value:"slack",label:"Slack / Mattermost"}]},{key:"auth_header",label:"Authorization",placeholder:"Bearer token (optional)",type:"password",required:!1},{key:"field_title",label:"Title Field Name",placeholder:"title",type:"text",required:!1,showIf:ie=>ie.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:ie=>ie.payload_format!=="slack"}];default:return[]}},X=q=>$(q).filter(ie=>ie.required),ce=$(o);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg my-8 max-h-[90vh] overflow-y-auto",onClick:q=>q.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:J,className:"p-6 space-y-4",children:[fe&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:fe}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:i,onChange:q=>s(q.target.value),placeholder:"My Notifications",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),a.jsx("select",{value:o,onChange:q=>{l(q.target.value),ne({}),ve(null)},disabled:r,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none disabled:opacity-50",children:ZW.map(q=>a.jsx("option",{value:q.value,children:q.label},q.value))}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ZW.find(q=>q.value===o)?.description})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),ce.filter(q=>!("showIf"in q)||q.showIf?.(Y)!==!1).map(q=>a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[q.label," ",q.required&&"*"]}),q.type==="select"&&"options"in q&&q.options?a.jsx("select",{value:Y[q.key]||q.options[0]?.value||"",onChange:ie=>{ne({...Y,[q.key]:ie.target.value}),ve(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:q.options.map(ie=>a.jsx("option",{value:ie.value,children:ie.label},ie.value))}):a.jsx("input",{type:q.type,value:Y[q.key]||"",onChange:ie=>{ne({...Y,[q.key]:ie.target.value}),ve(null)},placeholder:q.placeholder,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]},q.key))]}),a.jsx("div",{className:"flex gap-2",children:a.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>{ve(null),ue.mutate()},disabled:ue.isPending||!Y[X(o)[0]?.key],className:"flex-1",children:[ue.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(rk,{className:"w-4 h-4"}),"Test Configuration"]})}),ee&&a.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${ee.success?"bg-bambu-green/20 border border-bambu-green/50 text-bambu-green":"bg-red-500/20 border border-red-500/50 text-red-400"}`,children:ee.success?a.jsxs(a.Fragment,{children:[a.jsx(gr,{className:"w-5 h-5"}),a.jsx("span",{children:ee.message})]}):a.jsxs(a.Fragment,{children:[a.jsx(ha,{className:"w-5 h-5"}),a.jsx("span",{children:ee.message})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),a.jsxs("select",{value:c??"",onChange:q=>u(q.target.value?Number(q.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"All printers"}),Re?.map(q=>a.jsx("option",{value:q.id,children:q.name},q.id))]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),a.jsx($n,{checked:d,onChange:h})]}),d&&a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),a.jsx("input",{type:"time",value:f,onChange:q=>p(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),a.jsx("input",{type:"time",value:x,onChange:q=>v(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),a.jsx($n,{checked:b,onChange:y})]}),b&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),a.jsx("input",{type:"time",value:S,onChange:q=>N(q.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Start"}),a.jsx($n,{checked:M,onChange:k})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Complete"}),a.jsx($n,{checked:T,onChange:C})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Failed"}),a.jsx($n,{checked:j,onChange:E})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Stopped"}),a.jsx($n,{checked:P,onChange:U})]}),a.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-white",children:"Progress"}),a.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),a.jsx($n,{checked:L,onChange:B})]})]})]}),a.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[a.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),a.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Offline"}),a.jsx($n,{checked:D,onChange:H})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Error"}),a.jsx($n,{checked:G,onChange:I})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),a.jsx($n,{checked:K,onChange:Q})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),a.jsx($n,{checked:ae,onChange:V})]})]})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Te,{type:"submit",disabled:Le,className:"flex-1",children:[Le?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(xs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function BQe({template:t,onClose:e}){const n=Zt(),r=w.useRef(null),[i,s]=w.useState(t.title_template),[o,l]=w.useState(t.body_template),[c,u]=w.useState(null),[d,h]=w.useState(!0),{data:f}=et({queryKey:["template-variables"],queryFn:se.getTemplateVariables}),p=f?.find(k=>k.event_type===t.event_type),{data:x,isLoading:v}=et({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>se.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});w.useEffect(()=>{const k=T=>{T.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[e]);const b=ot({mutationFn:k=>se.updateNotificationTemplate(t.id,k),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:k=>{u(k.message)}}),y=ot({mutationFn:()=>se.resetNotificationTemplate(t.id),onSuccess:k=>{s(k.title_template),l(k.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:k=>{u(k.message)}}),S=k=>{if(k.preventDefault(),u(null),!i.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}b.mutate({title_template:i,body_template:o})},N=k=>{const T=r.current;if(!T)return;const C=T.selectionStart,j=T.selectionEnd,E=o,P=E.substring(0,C),U=E.substring(j),L=P+`{${k}}`+U;l(L),setTimeout(()=>{T.focus();const B=C+k.length+2;T.setSelectionRange(B,B)},0)},M=i!==t.title_template||o!==t.body_template;return a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),a.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:a.jsx(Rt,{className:"w-5 h-5 text-bambu-gray"})})]}),a.jsxs("form",{onSubmit:S,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),a.jsx("input",{type:"text",value:i,onChange:k=>s(k.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green",placeholder:"Notification title..."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),a.jsx("textarea",{ref:r,value:o,onChange:k=>l(k.target.value),rows:4,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white focus:outline-none focus:ring-1 focus:ring-bambu-green font-mono text-sm resize-none",placeholder:"Notification body..."})]}),p&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),a.jsx("div",{className:"flex flex-wrap gap-2",children:p.variables.map(k=>a.jsxs("button",{type:"button",onClick:()=>N(k),className:"inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark hover:bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs text-bambu-gray hover:text-white transition-colors",children:[a.jsx(rr,{className:"w-3 h-3"}),k]},k))}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[a.jsx(Xl,{className:"w-4 h-4"}),"Live Preview"]}),a.jsx("button",{type:"button",onClick:()=>h(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&a.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:v?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):x?a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),a.jsx("div",{className:"text-white font-medium",children:x.title})]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),a.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:x.body})]})]}):a.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),a.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[a.jsxs(Te,{type:"button",variant:"ghost",onClick:()=>y.mutate(),disabled:y.isPending,className:"text-orange-400 hover:text-orange-300",children:[y.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(Do,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),a.jsxs(Te,{onClick:S,disabled:b.isPending||!M,children:[b.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin mr-2"}):a.jsx(xs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const HQe={print_start:"Print Started",print_complete:"Print Complete",print_failed:"Print Failed",print_stopped:"Print Stopped",print_progress:"Progress",printer_offline:"Printer Offline",printer_error:"Printer Error",filament_low:"Low Filament",maintenance_due:"Maintenance Due",test:"Test"},$Qe={print_start:"text-blue-400",print_complete:"text-bambu-green",print_failed:"text-red-400",print_stopped:"text-orange-400",print_progress:"text-yellow-400",printer_offline:"text-gray-400",printer_error:"text-rose-400",filament_low:"text-cyan-400",maintenance_due:"text-purple-400",test:"text-bambu-gray"};function VQe({onClose:t}){const e=Zt(),{showToast:n}=hn(),[r,i]=w.useState(7),[s,o]=w.useState(null),[l,c]=w.useState(!1),{data:u}=et({queryKey:["settings"],queryFn:se.getSettings}),d=u?.time_format||"system",{data:h,isLoading:f,refetch:p,isRefetching:x}=et({queryKey:["notification-logs",r,l],queryFn:()=>se.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:v}=et({queryKey:["notification-log-stats",r],queryFn:()=>se.getNotificationLogStats(r)}),b=ot({mutationFn:()=>se.clearNotificationLogs(30),onSuccess:S=>{n(S.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:S=>{n(`Failed to clear logs: ${S.message}`,"error")}}),y=S=>{const N=Ji(S);if(!N)return"";const k=new Date().getTime()-N.getTime();return k<6e4?"Just now":k<36e5?`${Math.floor(k/6e4)}m ago`:k<864e5?`${Math.floor(k/36e5)}h ago`:N.toLocaleDateString()+" "+Xpe(N,d)};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg w-full max-w-3xl max-h-[85vh] flex flex-col",children:[a.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(x0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),a.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),v&&a.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:a.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[a.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",a.jsx("span",{className:"text-white font-medium",children:v.total})," notifications"]}),a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(gr,{className:"w-4 h-4"}),v.success_count," sent"]}),v.failure_count>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(ha,{className:"w-4 h-4"}),v.failure_count," failed"]})]})}),a.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[a.jsxs("select",{value:r,onChange:S=>i(Number(S.target.value)),className:"px-3 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:[a.jsx("option",{value:1,children:"Last 24 hours"}),a.jsx("option",{value:7,children:"Last 7 days"}),a.jsx("option",{value:30,children:"Last 30 days"}),a.jsx("option",{value:90,children:"Last 90 days"})]}),a.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:l,onChange:S=>c(S.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),"Show failed only"]}),a.jsx("div",{className:"flex-1"}),a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>p(),disabled:x,children:[x?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Ur,{className:"w-4 h-4"}),"Refresh"]}),a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>b.mutate(),disabled:b.isPending,className:"text-red-400 hover:text-red-300",children:[b.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),"Clear Old"]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):h&&h.length>0?a.jsx("div",{className:"space-y-2",children:h.map(S=>a.jsx(GQe,{log:S,isExpanded:s===S.id,onToggle:()=>o(s===S.id?null:S.id),formatDate:y,formatFullDate:N=>mb(N,d)},S.id))}):a.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[a.jsx(x0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function GQe({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){return a.jsxs("div",{className:`border rounded-lg overflow-hidden transition-colors ${t.success?"border-bambu-dark-tertiary bg-bambu-dark/30":"border-red-500/30 bg-red-500/5"}`,children:[a.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:n,children:[t.success?a.jsx(gr,{className:"w-4 h-4 text-bambu-green shrink-0"}):a.jsx(ha,{className:"w-4 h-4 text-red-400 shrink-0"}),a.jsx("span",{className:`text-xs font-medium ${$Qe[t.event_type]||"text-bambu-gray"}`,children:HQe[t.event_type]||t.event_type}),a.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&a.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),a.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?a.jsx(Wl,{className:"w-4 h-4 text-bambu-gray shrink-0"}):a.jsx(Jn,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&a.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),a.jsx("p",{className:"text-sm text-white",children:t.title})]}),a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),a.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&a.jsxs("div",{children:[a.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),a.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),a.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[a.jsxs("span",{children:["Provider: ",t.provider_type]}),a.jsxs("span",{children:["Time: ",i(t.created_at)]})]})]})]})}function qQe({formData:t,setFormData:e,groups:n,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o}){const{t:l}=Ut();w.useEffect(()=>{const u=d=>{d.key==="Escape"&&r()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[r]);const c=u=>{e({...t,group_ids:t.group_ids.includes(u)?t.group_ids.filter(d=>d!==u):[...t.group_ids,u]})};return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:a.jsxs(_t,{className:"w-full max-w-md",onClick:u=>u.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex flex-col gap-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:l("users.modal.createUser")})]}),a.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:l("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:r,children:a.jsx(Rt,{className:"w-5 h-5"})})]})}),a.jsxs(Nt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.username")," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:t.username,onChange:u=>e({...t,username:u.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[l("users.form.email")||"Email"," ",a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"email",value:t.email,onChange:u=>e({...t,email:u.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:l("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),a.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:l("users.form.groups")}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[n.map(u=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:t.group_ids.includes(u.id),onChange:()=>c(u.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:u.name}),u.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",l("users.system"),")"]})]},u.id)),n.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:l("users.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:r,children:l("users.modal.cancel")}),a.jsx(Te,{onClick:i,disabled:o,children:s?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),l("users.modal.creating")]}):a.jsxs(a.Fragment,{children:[a.jsx(rr,{className:"w-4 h-4"}),l("users.modal.createUser")]})})]})]})]})})}function WQe(){const{t}=Ut(),e=Zt(),{showToast:n}=hn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("auto"),[u,d]=w.useState(!1),[h,f]=w.useState(!0),[p,x]=w.useState("all"),[v,b]=w.useState(!1),[y,S]=w.useState(!1),{data:N,isLoading:M}=et({queryKey:["spoolman-settings"],queryFn:se.getSpoolmanSettings}),{data:k,isLoading:T,refetch:C}=et({queryKey:["spoolman-status"],queryFn:se.getSpoolmanStatus,refetchInterval:3e4}),{data:j}=et({queryKey:["printers"],queryFn:se.getPrinters});w.useEffect(()=>{N&&(i(N.spoolman_enabled==="true"),o(N.spoolman_url||""),c(N.spoolman_sync_mode||"auto"),d(N.spoolman_disable_weight_sync==="true"),f(N.spoolman_report_partial_usage!=="false"),b(!0))},[N]),w.useEffect(()=>{if(!v||!N)return;if(N.spoolman_enabled==="true"!==r||(N.spoolman_url||"")!==s||(N.spoolman_sync_mode||"auto")!==l||N.spoolman_disable_weight_sync==="true"!==u||N.spoolman_report_partial_usage!=="false"!==h){const Q=setTimeout(()=>{E.mutate()},500);return()=>clearTimeout(Q)}},[r,s,l,u,h,v]);const E=ot({mutationFn:()=>se.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:u?"true":"false",spoolman_report_partial_usage:h?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),n(t("settings.toast.settingsSaved"))}}),P=ot({mutationFn:se.connectSpoolman,onSuccess:()=>{C()}}),U=ot({mutationFn:se.disconnectSpoolman,onSuccess:()=>{C()}}),L=ot({mutationFn:se.syncAllPrintersAms,onSuccess:K=>{K.success}}),B=ot({mutationFn:K=>se.syncPrinterAms(K),onSuccess:K=>{K.success}}),D=()=>{p==="all"?L.mutate():B.mutate(p)},H=L.isPending||B.isPending,G=p==="all"?L.data:B.data,I=p==="all"?L.isSuccess:B.isSuccess;return M?a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ec,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),a.jsx(Nt,{children:a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ec,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),E.isPending&&a.jsx(it,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(ra,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),a.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[a.jsx(Xr,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),a.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),a.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&a.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[a.jsx(Yr,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&a.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Zs,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsx("div",{className:"text-xs text-bambu-gray",children:a.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[a.jsx("li",{children:t("settings.builtInFeatureRfid")}),a.jsx("li",{children:t("settings.builtInFeatureUsage")}),a.jsx("li",{children:t("settings.builtInFeatureCatalog")}),a.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),r&&a.jsxs("div",{className:"space-y-4",children:[a.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:a.jsxs("div",{className:"flex gap-2",children:[a.jsx(Zs,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-xs text-blue-300",children:[a.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),a.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[a.jsx("li",{children:t("settings.syncInfoRfidOnly")}),a.jsx("li",{children:t("settings.syncInfoAutoCreate")}),a.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),a.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),a.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),a.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:K=>o(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),a.jsxs("select",{value:l,onChange:K=>c(K.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),a.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:u,onChange:K=>d(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),u&&a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:h,onChange:K=>f(K.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),T?a.jsx(it,{className:"w-4 h-4 text-bambu-gray animate-spin"}):k?.connected?a.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[a.jsx(Yr,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):a.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[a.jsx(Rt,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),a.jsx("div",{className:"flex gap-2",children:k?.connected?a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,children:[U.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Cme,{className:"w-4 h-4"}),t("settings.disconnect")]}):a.jsxs(Te,{size:"sm",onClick:()=>P.mutate(),disabled:P.isPending||!s,children:[P.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Dh,{className:"w-4 h-4"}),t("settings.connect")]})})]}),P.isError&&a.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:P.error.message}),k?.connected&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsxs("select",{value:p,onChange:K=>x(K.target.value==="all"?"all":Number(K.target.value)),className:"w-full px-3 py-2 pr-8 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"all",children:t("settings.allPrinters")}),j?.map(K=>a.jsx("option",{value:K.id,children:K.name},K.id))]}),a.jsx(Jn,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:D,disabled:H,children:[H?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Ur,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),I&&G&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:`p-2 rounded text-sm ${G.success?"bg-green-500/20 border border-green-500/50 text-green-400":"bg-yellow-500/20 border border-yellow-500/50 text-yellow-400"}`,children:G.success?`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} successfully`:`Synced ${G.synced_count} spool${G.synced_count!==1?"s":""} with ${G.errors.length} error${G.errors.length!==1?"s":""}`}),G.skipped_count>0&&a.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[a.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[a.jsxs("div",{className:"flex items-center gap-1.5",children:[a.jsx(Mn,{className:"w-3.5 h-3.5"}),a.jsxs("span",{className:"font-medium",children:[G.skipped_count," spool",G.skipped_count!==1?"s":""," skipped"]})]}),G.skipped_count>5&&a.jsx("button",{onClick:()=>S(!y),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:y?"Show less":"Show all"})]}),a.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(y?G.skipped:G.skipped.slice(0,5)).map((K,Q)=>a.jsxs("li",{className:"flex items-center gap-2",children:[K.color&&a.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${K.color}`}}),a.jsx("span",{children:K.location}),a.jsxs("span",{className:"text-amber-300/60",children:["- ",K.reason]})]},Q)),!y&&G.skipped_count>5&&a.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",G.skipped_count-5," more"]})]})]}),G.errors.length>0&&a.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[a.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),a.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:G.errors.map((K,Q)=>a.jsx("li",{children:K},Q))})]})]})]})]})]})]})}function KQe(){const{t}=Ut(),{showToast:e}=hn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),c=w.useRef(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,b]=w.useState(""),[y,S]=w.useState(!1),[N,M]=w.useState(null),[k,T]=w.useState(!1),C=w.useCallback(async()=>{try{const I=await se.getSpoolCatalog();r(I)}catch{e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{C()},[C]);const j=n.filter(I=>I.name.toLowerCase().includes(o.toLowerCase())),E=async()=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const I=await se.addCatalogEntry({name:p.trim(),weight:parseInt(v)});r(K=>[...K,I].sort((Q,ae)=>Q.name.localeCompare(ae.name))),d(!1),x(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch{e(t("settings.catalog.addFailed"),"error")}finally{S(!1)}},P=I=>{f(I.id),x(I.name),b(I.weight.toString())},U=()=>{f(null),x(""),b("")},L=async I=>{if(!p.trim()||!v){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const K=await se.updateCatalogEntry(I,{name:p.trim(),weight:parseInt(v)});r(Q=>Q.map(ae=>ae.id===I?K:ae).sort((ae,V)=>ae.name.localeCompare(V.name))),f(null),x(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch{e(t("settings.catalog.updateFailed"),"error")}finally{S(!1)}},B=async()=>{if(N)try{await se.deleteCatalogEntry(N.id),r(I=>I.filter(K=>K.id!==N.id)),e(t("settings.catalog.entryDeleted"),"success")}catch{e(t("settings.catalog.deleteFailed"),"error")}finally{M(null)}},D=async()=>{T(!1),s(!0);try{await se.resetSpoolCatalog(),await C(),e(t("settings.catalog.resetSuccess"),"success")}catch{e(t("settings.catalog.resetFailed"),"error"),s(!1)}},H=()=>{const I=n.map(({name:V,weight:Y})=>({name:V,weight:Y})),K=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),Q=URL.createObjectURL(K),ae=document.createElement("a");ae.href=Q,ae.download="spool-catalog.json",document.body.appendChild(ae),ae.click(),document.body.removeChild(ae),URL.revokeObjectURL(Q),e(t("settings.catalog.exported",{count:n.length}),"success")},G=async I=>{const K=I.target.files?.[0];if(K){try{const Q=await K.text(),ae=JSON.parse(Q);if(!Array.isArray(ae))throw new Error("Invalid format");let V=0,Y=0;for(const ne of ae){if(!ne.name||typeof ne.weight!="number"){Y++;continue}if(n.some(ve=>ve.name.toLowerCase()===ne.name.toLowerCase())){Y++;continue}try{const ve=await se.addCatalogEntry({name:ne.name,weight:ne.weight});r(fe=>[...fe,ve].sort((de,Re)=>de.name.localeCompare(Re.name))),V++}catch{Y++}}e(t("settings.catalog.imported",{added:V,skipped:Y}),"success")}catch{e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return a.jsxs(_t,{children:[a.jsxs(An,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Ec,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:H,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[a.jsx(ui,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[a.jsx(sa,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:G}),a.jsxs("button",{onClick:()=>T(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[a.jsx(Do,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>d(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:I=>l(I.target.value)})]}),u&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),a.jsxs("div",{className:"flex gap-2 items-center",children:[a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:p,onChange:I=>x(I.target.value)})}),a.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:v,onChange:I=>b(I.target.value)}),a.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),a.jsxs("button",{onClick:E,disabled:y,className:"px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center gap-1 shrink-0",children:[y?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Yr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{d(!1),x(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Rt,{className:"w-4 h-4"})})]})]}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),a.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),a.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),a.jsx("th",{className:"px-4 py-2 w-24"})]})}),a.jsx("tbody",{children:j.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:4,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):j.map(I=>a.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:h===I.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:p,onChange:K=>x(K.target.value)})}),a.jsx("td",{className:"px-4 py-2",children:a.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:v,onChange:K=>b(K.target.value)})}),a.jsx("td",{className:"px-4 py-2 text-center",children:a.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>L(I.id),disabled:y,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:y?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Yr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:U,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Rt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-4 py-2 text-white",children:I.name}),a.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[I.weight,"g"]}),a.jsx("td",{className:"px-4 py-2 text-center",children:I.is_default?a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),a.jsx("td",{className:"px-4 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>P(I),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>M(I),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(en,{className:"w-4 h-4"})})]})})]})},I.id))})]})})]}),N&&a.jsx(Pn,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:N.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:B,onCancel:()=>M(null)}),k&&a.jsx(Pn,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:D,onCancel:()=>T(!1)})]})}function XQe(){const{t}=Ut(),{showToast:e}=hn(),[n,r]=w.useState([]),[i,s]=w.useState(!0),[o,l]=w.useState(""),[c,u]=w.useState("Bambu Lab"),d=w.useRef(null),[h,f]=w.useState(!1),[p,x]=w.useState(null),[v,b]=w.useState(""),[y,S]=w.useState(""),[N,M]=w.useState("#FFFFFF"),[k,T]=w.useState(""),[C,j]=w.useState(!1),[E,P]=w.useState(!1),[U,L]=w.useState(null),[B,D]=w.useState(null),[H,G]=w.useState(!1),I=w.useCallback(async()=>{try{const le=await se.getColorCatalog();r(le)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);w.useEffect(()=>{I()},[I]);const K=[...new Set(n.map(le=>le.manufacturer))].sort(),Q=n.filter(le=>{const Ne=o===""||le.manufacturer.toLowerCase().includes(o.toLowerCase())||le.color_name.toLowerCase().includes(o.toLowerCase())||(le.material?.toLowerCase().includes(o.toLowerCase())??!1),J=c===""||le.manufacturer===c;return Ne&&J}),ae=()=>{b(""),S(""),M("#FFFFFF"),T("")},V=async()=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const le=await se.addColorEntry({manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:k.trim()||null});r(Ne=>[...Ne,le].sort((J,Le)=>J.manufacturer.localeCompare(Le.manufacturer)||(J.material||"").localeCompare(Le.material||"")||J.color_name.localeCompare(Le.color_name))),f(!1),ae(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{j(!1)}},Y=le=>{x(le.id),b(le.manufacturer),S(le.color_name),M(le.hex_color),T(le.material||"")},ne=()=>{x(null),ae()},ee=async le=>{if(!v.trim()||!y.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}j(!0);try{const Ne=await se.updateColorEntry(le,{manufacturer:v.trim(),color_name:y.trim(),hex_color:N,material:k.trim()||null});r(J=>J.map(Le=>Le.id===le?Ne:Le).sort((Le,$)=>Le.manufacturer.localeCompare($.manufacturer)||(Le.material||"").localeCompare($.material||"")||Le.color_name.localeCompare($.color_name))),x(null),ae(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{j(!1)}},ve=async()=>{if(B)try{await se.deleteColorEntry(B.id),r(le=>le.filter(Ne=>Ne.id!==B.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{D(null)}},fe=async()=>{G(!1),s(!0);try{await se.resetColorCatalog(),await I(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},de=async()=>{P(!0),L(null);try{const le={},Ne=id();Ne&&(le.Authorization=`Bearer ${Ne}`);const J=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:le});if(!J.ok)throw new Error("Failed to start sync");const Le=J.body?.getReader();if(!Le)throw new Error("No response body");const $=new TextDecoder;let X="";for(;;){const{done:ce,value:q}=await Le.read();if(ce)break;X+=$.decode(q,{stream:!0});const ie=X.split(` `);X=ie.pop()||"";for(const te of ie)if(te.startsWith("data: "))try{const he=JSON.parse(te.slice(6));he.type==="progress"?L({fetched:he.total_fetched,total:he.total_available}):he.type==="complete"?he.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:he.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:he.added,skipped:he.skipped}),"success"):he.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${he.error}`,"error")}catch{}}await I()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{P(!1),L(null)}},Re=()=>{const le=n.map(({manufacturer:$,color_name:X,hex_color:ce,material:q})=>({manufacturer:$,color_name:X,hex_color:ce,material:q})),Ne=new Blob([JSON.stringify(le,null,2)],{type:"application/json"}),J=URL.createObjectURL(Ne),Le=document.createElement("a");Le.href=J,Le.download="color-catalog.json",document.body.appendChild(Le),Le.click(),document.body.removeChild(Le),URL.revokeObjectURL(J),e(t("settings.colorCatalog.exported",{count:n.length}),"success")},ue=async le=>{const Ne=le.target.files?.[0];if(Ne){try{const J=await Ne.text(),Le=JSON.parse(J);if(!Array.isArray(Le))throw new Error("Invalid format");let $=0,X=0;for(const ce of Le){if(!ce.manufacturer||!ce.color_name||!ce.hex_color){X++;continue}if(n.some(ie=>ie.manufacturer.toLowerCase()===ce.manufacturer.toLowerCase()&&ie.color_name.toLowerCase()===ce.color_name.toLowerCase()&&(ie.material||"").toLowerCase()===(ce.material||"").toLowerCase())){X++;continue}try{const ie=await se.addColorEntry({manufacturer:ce.manufacturer,color_name:ce.color_name,hex_color:ce.hex_color,material:ce.material||null});r(te=>[...te,ie].sort((he,ge)=>he.manufacturer.localeCompare(ge.manufacturer)||(he.material||"").localeCompare(ge.material||"")||he.color_name.localeCompare(ge.color_name))),$++}catch{X++}}e(t("settings.colorCatalog.imported",{added:$,skipped:X}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}d.current&&(d.current.value="")}};return a.jsxs(_t,{children:[a.jsxs(An,{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(ek,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),a.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",n.length,")"]})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[a.jsxs("button",{onClick:Re,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(ui,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),a.jsxs("button",{onClick:()=>d.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(sa,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),a.jsx("input",{ref:d,type:"file",accept:".json",className:"hidden",onChange:ue}),a.jsxs("button",{onClick:de,disabled:E,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.colorCatalog.syncTooltip"),children:[E?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Hb,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:E?U?`${Math.min(U.fetched,U.total)} / ${U.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),a.jsxs("button",{onClick:()=>G(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[a.jsx(Do,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),a.jsxs("button",{onClick:()=>f(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[a.jsx(rr,{className:"w-4 h-4"}),a.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]})]}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),a.jsxs("div",{className:"flex gap-2 flex-wrap",children:[a.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.searchColors"),value:o,onChange:le=>l(le.target.value)})]}),a.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:le=>u(le.target.value),children:[a.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),K.map(le=>a.jsx("option",{value:le,children:le},le))]})]}),h&&a.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[a.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.manufacturer"),value:v,onChange:le=>b(le.target.value)}),a.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.colorName"),value:y,onChange:le=>S(le.target.value)}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"color",className:"w-10 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:le=>M(le.target.value)}),a.jsx("input",{type:"text",className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:"#FFFFFF",value:N,onChange:le=>M(le.target.value)})]}),a.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.materialOptional"),value:k,onChange:le=>T(le.target.value)}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("button",{onClick:V,disabled:C,className:"flex-1 px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center justify-center gap-1",children:[C?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Yr,{className:"w-4 h-4"}),t("common.add")]}),a.jsx("button",{onClick:()=>{f(!1),ae()},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:a.jsx(Rt,{className:"w-4 h-4"})})]})]})]}),(o||c)&&a.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:Q.length,total:n.length})}),i?a.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[a.jsx(it,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):a.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:a.jsxs("tr",{children:[a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),a.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),a.jsx("th",{className:"px-3 py-2 w-16"})]})}),a.jsx("tbody",{children:Q.length===0?a.jsx("tr",{children:a.jsx("td",{colSpan:6,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):Q.map(le=>a.jsx("tr",{className:"border-t border-bambu-dark-tertiary hover:bg-bambu-dark",children:p===le.id?a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:Ne=>M(Ne.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:v,onChange:Ne=>b(Ne.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:k,onChange:Ne=>T(Ne.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:y,onChange:Ne=>S(Ne.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:N,onChange:Ne=>M(Ne.target.value)})}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>ee(le.id),disabled:C,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:C?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Yr,{className:"w-4 h-4"})}),a.jsx("button",{onClick:ne,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(Rt,{className:"w-4 h-4"})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsx("td",{className:"px-3 py-2",children:a.jsx("div",{className:"w-8 h-8 rounded border border-bambu-dark-tertiary",style:{backgroundColor:le.hex_color},title:le.hex_color})}),a.jsx("td",{className:"px-3 py-2 text-white",children:le.manufacturer}),a.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:le.material||"-"}),a.jsx("td",{className:"px-3 py-2 text-white",children:le.color_name}),a.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:le.hex_color}),a.jsx("td",{className:"px-3 py-2",children:a.jsxs("div",{className:"flex justify-end gap-1",children:[a.jsx("button",{onClick:()=>Y(le),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>D(le),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:a.jsx(en,{className:"w-4 h-4"})})]})})]})},le.id))})]})})]}),B&&a.jsx(Pn,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${B.manufacturer} - ${B.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:ve,onCancel:()=>D(null)}),H&&a.jsx(Pn,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:fe,onCancel:()=>G(!1)})]})}function YQe({link:t,onClose:e}){const{t:n}=Ut(),r=Zt(),i=!!t,s=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.url||""),[d,h]=w.useState(t?.icon||"link"),[f,p]=w.useState(t?.open_in_new_tab||!1),[x,v]=w.useState(!!t?.custom_icon),[b,y]=w.useState(t?.custom_icon?se.getExternalLinkIconUrl(t.id):null),[S,N]=w.useState(null),[M,k]=w.useState(null);w.useEffect(()=>{const B=D=>{D.key==="Escape"&&e()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[e]);const T=ot({mutationFn:async B=>{const D=await se.createExternalLink(B);return S?await se.uploadExternalLinkIcon(D.id,S):D},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:B=>{k(B.message)}}),C=ot({mutationFn:async B=>{let D=await se.updateExternalLink(t.id,B);return S?D=await se.uploadExternalLinkIcon(t.id,S):!x&&t?.custom_icon&&(D=await se.deleteExternalLinkIcon(t.id)),D},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:B=>{k(B.message)}}),j=B=>{const D=B.target.files?.[0];if(D){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(D.type)){k("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(D.size>1024*1024){k("Image file must be less than 1MB");return}N(D),v(!0);const G=new FileReader;G.onload=I=>{y(I.target?.result)},G.readAsDataURL(D)}},E=()=>{N(null),y(null),v(!1),s.current&&(s.current.value="")},P=B=>{if(B.preventDefault(),k(null),!o.trim()){k("Name is required");return}if(!c.trim()){k("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){k("URL must start with http:// or https://");return}const D={name:o.trim(),url:c.trim(),icon:d,open_in_new_tab:f};i?C.mutate(D):T.mutate(D)},U=T.isPending||C.isPending,L=ok(d);return a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:B=>B.stopPropagation(),children:[a.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:x&&b?a.jsx("img",{src:b,alt:"",className:"w-5 h-5 rounded"}):a.jsx(L,{className:"w-5 h-5"})}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),a.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:P,className:"p-6 space-y-4",children:[M&&a.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:M}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),a.jsx("input",{type:"text",value:o,onChange:B=>l(B.target.value),placeholder:"My Link",maxLength:50,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),a.jsx("input",{type:"text",value:c,onChange:B=>u(B.target.value),placeholder:"https://example.com",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("label",{className:"text-sm text-bambu-gray",children:n("externalLinks.openInNewTab")}),a.jsx("button",{type:"button",onClick:()=>p(!f),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${f?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:a.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${f?"translate-x-6":"translate-x-1"}`})})]}),a.jsxs("div",{className:"space-y-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),a.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),a.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:j}),x&&b?a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("img",{src:b,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),a.jsx("button",{type:"button",onClick:E,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:a.jsx(en,{className:"w-4 h-4"})})]}):a.jsxs(Te,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[a.jsx(sa,{className:"w-4 h-4"}),"Upload"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!x&&a.jsxs("div",{children:[a.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),a.jsx(Lpe,{value:d,onChange:h})]})]}),a.jsxs("div",{className:"flex gap-3 pt-2",children:[a.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),a.jsxs(Te,{type:"submit",disabled:U,className:"flex-1",children:[U?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(xs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function QQe(){const{t}=Ut(),e=Zt(),[n,r]=w.useState(!1),[i,s]=w.useState(null),[o,l]=w.useState(null),[c,u]=w.useState(null),{data:d,isLoading:h}=et({queryKey:["external-links"],queryFn:se.getExternalLinks}),f=ot({mutationFn:N=>se.deleteExternalLink(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),p=ot({mutationFn:N=>se.reorderExternalLinks(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),x=(N,M)=>{u(M),N.dataTransfer.effectAllowed="move"},v=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},b=(N,M)=>{if(N.preventDefault(),c===null||c===M||!d)return;const k=d.map(E=>E.id),T=k.indexOf(c),C=k.indexOf(M);if(T===-1||C===-1)return;const j=[...k];j.splice(T,1),j.splice(C,0,c),p.mutate(j),u(null)},y=N=>{l(N)},S=()=>{o&&(f.mutate(o.id),l(null))};return a.jsxs(a.Fragment,{children:[a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Dh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),a.jsxs(Te,{size:"sm",onClick:()=>r(!0),children:[a.jsx(rr,{className:"w-4 h-4"}),"Add Link"]})]})}),a.jsxs(Nt,{children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),h?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):d&&d.length>0?a.jsx("div",{className:"space-y-2",children:d.map(N=>{const M=ok(N.icon);return a.jsxs("div",{draggable:!0,onDragStart:k=>x(k,N.id),onDragOver:v,onDrop:k=>b(k,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===N.id?"opacity-50":""}`,children:[a.jsx(jh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),a.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:a.jsx(M,{className:"w-4 h-4"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-white font-medium truncate",children:N.name}),a.jsx(Xr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),a.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[a.jsx("button",{onClick:()=>s(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:a.jsx($i,{className:"w-4 h-4"})}),a.jsx("button",{onClick:()=>y(N),disabled:f.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:t("externalLinks.deleteLink"),children:a.jsx(en,{className:"w-4 h-4"})})]})]},N.id)})}):a.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[a.jsx(Dh,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),a.jsx("p",{children:t("externalLinks.noLinksConfigured")}),a.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(n||i)&&a.jsx(YQe,{link:i,onClose:()=>{r(!1),s(null)}}),o&&a.jsx(Pn,{title:"Delete Link",message:`Are you sure you want to delete "${o.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:S,onCancel:()=>l(null)})]})}function ZQe(){const{t}=Ut(),e=Zt(),{showToast:n}=hn(),[r,i]=w.useState(!1),[s,o]=w.useState(""),[l,c]=w.useState("immediate"),[u,d]=w.useState("3DPrinter-X1-Carbon"),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,b]=w.useState(!1),[y,S]=w.useState(null),{data:N,isLoading:M}=et({queryKey:["virtual-printer-settings"],queryFn:KS.getSettings,refetchInterval:1e4}),{data:k}=et({queryKey:["virtual-printer-models"],queryFn:KS.getModels}),{data:T}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:C}=et({queryKey:["network-interfaces"],queryFn:()=>se.getNetworkInterfaces().then(I=>I.interfaces),enabled:r});w.useEffect(()=>{if(N){i(N.enabled);let I=N.mode==="queue"?"review":N.mode;I!=="immediate"&&I!=="review"&&I!=="print_queue"&&I!=="proxy"&&(I="immediate"),c(I),d(N.model),f(N.target_printer_id),x(N.remote_interface_ip||"")}},[N]);const j=ot({mutationFn:I=>KS.updateSettings(I),onSuccess:()=>{e.invalidateQueries({queryKey:["virtual-printer-settings"]}),n(t("virtualPrinter.toast.updated")),S(null)},onError:I=>{if(n(I.message||t("virtualPrinter.toast.failedToUpdate"),"error"),N){i(N.enabled);const K=N.mode==="queue"?"review":N.mode;c(["immediate","review","print_queue","proxy"].includes(K)?K:"immediate"),d(N.model),f(N.target_printer_id)}S(null)}}),E=()=>{const I=!r;if(I){if(l==="proxy"){if(!h){n(t("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!s&&!N?.access_code_set){n(t("virtualPrinter.toast.accessCodeRequired"),"error");return}}i(I),S("toggle"),j.mutate({enabled:I,access_code:l!=="proxy"&&s||void 0,mode:l,target_printer_id:l==="proxy"?h??void 0:void 0})},P=()=>{if(!s){n(t("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(s.length!==8){n(t("virtualPrinter.toast.accessCodeLength"),"error");return}S("accessCode"),j.mutate({access_code:s}),o("")},U=I=>{c(I),S("mode"),j.mutate({mode:I})},L=I=>{f(I),S("targetPrinter"),j.mutate({target_printer_id:I})},B=I=>{d(I),S("model"),j.mutate({model:I})},D=I=>{x(I),S("remoteInterface"),j.mutate({remote_interface_ip:I})};if(M)return a.jsx(_t,{children:a.jsx(Nt,{className:"py-8 flex justify-center",children:a.jsx(it,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const H=N?.status,G=H?.running||!1;return a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsx("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Cr,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.title")})]}),H&&a.jsxs("div",{className:`flex items-center gap-2 text-sm ${G?"text-green-400":"text-bambu-gray"}`,children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${G?"bg-green-400 animate-pulse":"bg-gray-500"}`}),t(G?"virtualPrinter.running":"virtualPrinter.stopped")]})]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:t(l==="proxy"?"virtualPrinter.description.proxy":"virtualPrinter.description.default")}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.enable.title")}),a.jsx("div",{className:"text-sm text-bambu-gray",children:G?l==="proxy"?t("virtualPrinter.enable.proxyingTo",{name:T?.find(I=>I.id===h)?.name||"printer"}):t("virtualPrinter.enable.visibleInSlicer"):t("virtualPrinter.enable.notActive")})]}),a.jsx("button",{onClick:E,disabled:y==="toggle",className:`relative w-12 h-6 rounded-full transition-colors ${r?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${y==="toggle"?"opacity-50":""}`,children:a.jsx("span",{className:`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${r?"translate-x-6":""}`})})]}),l!=="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.model.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:t("virtualPrinter.model.description")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:u,onChange:I=>B(I.target.value),disabled:y==="model",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:k?.models&&Object.entries(k.models).sort(([,I],[,K])=>I.localeCompare(K)).map(([I,K])=>a.jsx("option",{value:I,children:K},I))}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),r&&G&&a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[a.jsx(Zs,{className:"w-3 h-3 inline mr-1"}),t("virtualPrinter.model.restartWarning")]})]}),l!=="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.accessCode.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:N?.access_code_set?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(Yr,{className:"w-4 h-4"}),t("virtualPrinter.accessCode.isSet")]}):a.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[a.jsx(Mn,{className:"w-4 h-4"}),t("virtualPrinter.accessCode.notSet")]})}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("div",{className:"relative flex-1",children:[a.jsx("input",{type:v?"text":"password",value:s,onChange:I=>o(I.target.value),placeholder:N?.access_code_set?t("virtualPrinter.accessCode.placeholderChange"):t("virtualPrinter.accessCode.placeholder"),maxLength:8,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white placeholder-bambu-gray pr-10 font-mono"}),a.jsx("button",{onClick:()=>b(!v),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:v?a.jsx(uv,{className:"w-4 h-4"}):a.jsx(Xl,{className:"w-4 h-4"})})]}),a.jsx(Te,{onClick:P,disabled:!s||y==="accessCode",variant:"primary",children:y==="accessCode"?a.jsx(it,{className:"w-4 h-4 animate-spin"}):t("common.save")})]}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[t("virtualPrinter.accessCode.hint"),s&&a.jsxs("span",{className:s.length===8?"text-green-400":"text-yellow-400",children:[" ",t("virtualPrinter.accessCode.charCount",{count:s.length})]})]})]}),l==="proxy"&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.targetPrinter.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:h?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(Yr,{className:"w-4 h-4"}),t("virtualPrinter.targetPrinter.configured")]}):a.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[a.jsx(Mn,{className:"w-4 h-4"}),t("virtualPrinter.targetPrinter.notConfigured")]})}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:h??"",onChange:I=>{const K=parseInt(I.target.value,10);isNaN(K)||L(K)},disabled:y==="targetPrinter",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:[a.jsx("option",{value:"",children:t("virtualPrinter.targetPrinter.placeholder")}),T?.map(I=>a.jsxs("option",{value:I.id,children:[I.name," (",I.ip_address,")"]},I.id))]}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:t("virtualPrinter.targetPrinter.hint")}),!T?.length&&a.jsxs("p",{className:"text-xs text-yellow-400 mt-2",children:[a.jsx(Mn,{className:"w-3 h-3 inline mr-1"}),t("virtualPrinter.targetPrinter.noPrinters")]})]}),r&&a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.remoteInterface.title")}),a.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:p?a.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[a.jsx(Yr,{className:"w-4 h-4"}),t("virtualPrinter.remoteInterface.configured")]}):a.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[a.jsx(Zs,{className:"w-4 h-4"}),t("virtualPrinter.remoteInterface.optional")]})}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:p,onChange:I=>D(I.target.value),disabled:y==="remoteInterface",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white appearance-none cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed pr-10",children:[a.jsx("option",{value:"",children:t("virtualPrinter.remoteInterface.placeholder")}),C?.map(I=>a.jsxs("option",{value:I.ip,children:[I.name," (",I.ip,") - ",I.subnet]},I.ip))]}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:t("virtualPrinter.remoteInterface.hint")})]}),a.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[a.jsx("div",{className:"text-white font-medium mb-2",children:t("virtualPrinter.mode.title")}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("button",{onClick:()=>U("immediate"),disabled:y==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="immediate"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.archive")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.archiveDesc")})]}),a.jsxs("button",{onClick:()=>U("review"),disabled:y==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="review"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.review")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.reviewDesc")})]}),a.jsxs("button",{onClick:()=>U("print_queue"),disabled:y==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="print_queue"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("div",{className:"text-white font-medium",children:t("virtualPrinter.mode.queue")}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.queueDesc")})]}),a.jsxs("button",{onClick:()=>U("proxy"),disabled:y==="mode",className:`p-3 rounded-lg border text-left transition-colors ${l==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsxs("div",{className:"flex items-center gap-1.5 text-white font-medium",children:[a.jsx(FB,{className:"w-4 h-4"}),t("virtualPrinter.mode.proxy")]}),a.jsx("div",{className:"text-xs text-bambu-gray",children:t("virtualPrinter.mode.proxyDesc")})]})]})]})]})]})}),a.jsxs("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:[a.jsx(_t,{className:"border-l-4 border-l-yellow-500",children:a.jsx(Nt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Mn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-white font-medium mb-2",children:t("virtualPrinter.setupRequired.title")}),a.jsx("p",{className:"text-bambu-gray mb-3",children:t("virtualPrinter.setupRequired.description")}),a.jsxs("a",{href:"https://wiki.bambuddy.cool/features/virtual-printer/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-yellow-500/20 border border-yellow-500/50 rounded-md text-yellow-400 hover:bg-yellow-500/30 transition-colors",children:[a.jsx(Xr,{className:"w-4 h-4"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),a.jsx(_t,{children:a.jsx(Nt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Zs,{className:"w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm text-bambu-gray",children:[a.jsx("p",{className:"mb-2",children:a.jsxs("strong",{className:"text-white",children:[t(l==="proxy"?"virtualPrinter.howItWorks.titleProxy":"virtualPrinter.howItWorks.title"),":"]})}),l==="proxy"?a.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep3")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep4")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.proxyStep5")})]}):a.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[a.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step3")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step4")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step5")}),a.jsx("li",{children:t("virtualPrinter.howItWorks.step6")})]})]})]})})}),H&&G&&a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h3",{className:"text-md font-semibold text-white",children:t("virtualPrinter.status.title")})}),a.jsx(Nt,{children:H.mode==="proxy"&&H.proxy?a.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.targetPrinter")}),a.jsx("div",{className:"text-white",children:T?.find(I=>I.id===h)?.name||H.proxy.target_host}),a.jsx("div",{className:"text-xs text-bambu-gray font-mono",children:H.proxy.target_host})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mode")}),a.jsxs("div",{className:"text-white flex items-center gap-1.5",children:[a.jsx(FB,{className:"w-4 h-4"}),t("virtualPrinter.mode.proxy")]})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.ftpPort")}),a.jsx("div",{className:"text-white font-mono",children:H.proxy.ftp_port})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mqttPort")}),a.jsx("div",{className:"text-white font-mono",children:H.proxy.mqtt_port})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.ftpConnections")}),a.jsx("div",{className:"text-white",children:H.proxy.ftp_connections??0})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mqttConnections")}),a.jsx("div",{className:"text-white",children:H.proxy.mqtt_connections??0})]})]}):a.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.printerName")}),a.jsx("div",{className:"text-white",children:H.name})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.model")}),a.jsx("div",{className:"text-white",children:H.model_name||H.model})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.serialNumber")}),a.jsx("div",{className:"text-white font-mono",children:H.serial})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.mode")}),a.jsx("div",{className:"text-white capitalize",children:H.mode})]}),a.jsxs("div",{children:[a.jsx("div",{className:"text-bambu-gray",children:t("virtualPrinter.status.pendingFiles")}),a.jsx("div",{className:"text-white",children:H.pending_files})]})]})})]})]})]})}function JW({status:t}){if(!t)return null;const e={success:"bg-green-500/20 text-green-400",failed:"bg-red-500/20 text-red-400",skipped:"bg-yellow-500/20 text-yellow-400",running:"bg-blue-500/20 text-blue-400"},n={success:a.jsx(gr,{className:"w-3 h-3"}),failed:a.jsx(ha,{className:"w-3 h-3"}),skipped:a.jsx(jF,{className:"w-3 h-3"}),running:a.jsx(it,{className:"w-3 h-3 animate-spin"})};return a.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium ${e[t]||"bg-gray-500/20 text-gray-400"}`,children:[n[t],t.charAt(0).toUpperCase()+t.slice(1)]})}function JQe(t){return t?new Date(t).toLocaleString():"-"}function eK(t){if(!t)return"-";const e=new Date(t),n=new Date,r=e.getTime()-n.getTime(),i=Math.round(r/6e4);if(i<0){const s=Math.abs(i);if(s<60)return`${s}m ago`;const o=Math.floor(s/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}else{if(i<60)return`in ${i}m`;const s=Math.floor(i/60);return s<24?`in ${s}h`:`in ${Math.floor(s/24)}d`}}function eZe(){const t=Zt(),{showToast:e}=hn(),{t:n}=Ut(),[r,i]=w.useState(""),[s,o]=w.useState(""),[l,c]=w.useState("main"),[u,d]=w.useState(!1),[h,f]=w.useState("daily"),[p,x]=w.useState(!0),[v,b]=w.useState(!0),[y,S]=w.useState(!1),[N,M]=w.useState(!0),[k,T]=w.useState(!1),[C,j]=w.useState(!1),[E,P]=w.useState(""),[U,L]=w.useState(!1),[B,D]=w.useState(null),[H,G]=w.useState(null),I=w.useRef(null);w.useEffect(()=>{if(k||C){const z=F=>(F.preventDefault(),F.returnValue="A backup operation is in progress. Are you sure you want to leave?",F.returnValue);return window.addEventListener("beforeunload",z),()=>window.removeEventListener("beforeunload",z)}},[k,C]);const[K,Q]=w.useState(!1),[ae,V]=w.useState(null),Y=w.useRef(null),ne=w.useRef(!1),{data:ee,isLoading:ve}=et({queryKey:["github-backup-config"],queryFn:se.getGitHubBackupConfig}),{data:fe}=et({queryKey:["github-backup-status"],queryFn:se.getGitHubBackupStatus,refetchInterval:Z=>Z.state.data?.is_running?500:1e4}),{data:de}=et({queryKey:["github-backup-logs"],queryFn:()=>se.getGitHubBackupLogs(20)}),{data:Re}=et({queryKey:["cloud-status"],queryFn:se.getCloudStatus}),{data:ue}=et({queryKey:["printers"],queryFn:se.getPrinters}),le=kF({queries:(ue??[]).map(Z=>({queryKey:["printerStatus",Z.id],queryFn:()=>se.getPrinterStatus(Z.id),staleTime:1e4,refetchInterval:3e4}))}),Ne=(ue??[]).map((Z,z)=>({printer:Z,connected:le[z]?.data?.connected??!1})),J=Ne.length,Le=Ne.filter(Z=>Z.connected).length,$=J>0&&Le===0,X=Le>0&&Le{ee&&(i(ee.repository_url),c(ee.branch),d(ee.schedule_enabled),f(ee.schedule_type),x(ee.backup_kprofiles),b(ee.backup_cloud_profiles),S(ee.backup_settings),M(ee.enabled),o(""),setTimeout(()=>{ne.current=!0},100))},[ee]);const ce=w.useCallback(async(Z=!1)=>{if(ee?.has_token)try{Z&&s?(await se.saveGitHubBackupConfig({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),o(""),e("Token updated")):(await se.updateGitHubBackupConfig({repository_url:r,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(z){e(`Failed to save: ${z.message}`,"error")}},[ee?.has_token,r,s,l,u,h,p,v,y,N,t,e]);w.useEffect(()=>{if(!(!ne.current||!ee?.has_token))return Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>{ce(!1)},500),()=>{Y.current&&clearTimeout(Y.current)}},[r,l,u,h,p,v,y,N,ce,ee?.has_token]),w.useEffect(()=>{if(!(!ne.current||!ee?.has_token||!s))return Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>{ce(!0)},1e3),()=>{Y.current&&clearTimeout(Y.current)}},[s,ce,ee?.has_token]);const q=ot({mutationFn:Z=>se.saveGitHubBackupConfig(Z),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),o(""),ne.current=!0},onError:Z=>{e(`Failed to save: ${Z.message}`,"error")}}),ie=ot({mutationFn:se.triggerGitHubBackup,onSuccess:Z=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),Z.success?Z.files_changed>0?e(`Backup complete - ${Z.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${Z.message}`,"error")},onError:Z=>{e(`Backup failed: ${Z.message}`,"error")}}),te=ot({mutationFn:()=>se.clearGitHubBackupLogs(0),onSuccess:Z=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${Z.deleted} logs`)},onError:Z=>{e(`Failed to clear logs: ${Z.message}`,"error")}}),he=async()=>{Q(!0),V(null);try{let Z;if(s){if(!r){e("Enter repository URL","error"),Q(!1);return}Z=await se.testGitHubConnection(r,s)}else if(ee?.has_token)Z=await se.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),Q(!1);return}V({success:Z.success,message:Z.message})}catch(Z){V({success:!1,message:Z.message})}finally{Q(!1)}},ge=()=>{if(!r){e("Repository URL is required","error");return}if(!s){e("Access token is required","error");return}q.mutate({repository_url:r,access_token:s,branch:l,schedule_enabled:u,schedule_type:h,backup_kprofiles:p,backup_cloud_profiles:v,backup_settings:y,enabled:N})};return ve?a.jsx("div",{className:"flex items-center justify-center py-12",children:a.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(l3,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),ee&&Re?.is_authenticated&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),a.jsx($n,{checked:N,onChange:M})]})]})}),a.jsx(Nt,{className:"space-y-4",children:Re?.is_authenticated?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),a.jsx("input",{type:"text",value:r,onChange:Z=>{i(Z.target.value),V(null)},placeholder:"https://github.com/username/bambuddy-backup",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",ee?.has_token&&a.jsx("span",{className:"text-green-400",children:"(saved)"})]}),a.jsx("input",{type:"password",value:s,onChange:Z=>{o(Z.target.value),V(null)},placeholder:ee?.has_token?"Enter new token to update":"ghp_xxxxxxxxxxxx",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),a.jsx("input",{type:"text",value:l,onChange:Z=>c(Z.target.value),placeholder:"main",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),a.jsxs("select",{value:u?h:"disabled",onChange:Z=>{Z.target.value==="disabled"?d(!1):(d(!0),f(Z.target.value))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"disabled",children:"Manual only"}),a.jsx("option",{value:"hourly",children:"Hourly"}),a.jsx("option",{value:"daily",children:"Daily"}),a.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:`flex items-start gap-2 ${$?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[a.jsx("input",{type:"checkbox",checked:p,onChange:Z=>x(Z.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:$}),a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`text-sm ${$?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),$&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Mn,{className:"w-3 h-3"}),"No printers connected"]}),X&&a.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:[a.jsx(Mn,{className:"w-3 h-3"}),Le,"/",J," connected"]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:v,onChange:Z=>b(Z.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green",disabled:!Re?.is_authenticated}),a.jsxs("div",{children:[a.jsx("span",{className:`text-sm ${Re?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),a.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:y,onChange:Z=>S(Z.target.checked),className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white text-sm",children:"App Settings"}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (complete database)"})]})]})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[fe?.configured&&a.jsxs("div",{className:"flex items-center justify-between text-sm",children:[a.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:fe.last_backup_at?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:["Last backup: ",eK(fe.last_backup_at)]}),a.jsx(JW,{status:fe.last_backup_status})]}):a.jsx("span",{children:"No backups yet"})}),fe.next_scheduled_run&&a.jsxs("span",{className:"text-bambu-gray",children:[a.jsx(Xn,{className:"w-3 h-3 inline mr-1"}),"Next: ",eK(fe.next_scheduled_run)]})]}),ae&&a.jsxs("div",{className:`text-sm flex items-center gap-1 ${ae.success?"text-green-400":"text-red-400"}`,children:[ae.success?a.jsx(gr,{className:"w-4 h-4"}):a.jsx(ha,{className:"w-4 h-4"}),ae.message]}),a.jsx("div",{className:"flex flex-wrap items-center gap-2",children:fe?.configured?a.jsx(a.Fragment,{children:ie.isPending||fe.is_running?a.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{className:"text-sm",children:fe.progress||"Starting backup..."})]}):a.jsxs(a.Fragment,{children:[a.jsxs(Te,{variant:"primary",size:"sm",onClick:()=>ie.mutate(),disabled:!ee?.enabled,children:[a.jsx(jo,{className:"w-4 h-4"}),"Backup Now"]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:he,disabled:K,children:[K?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Ur,{className:"w-4 h-4"}),"Test"]})]})}):a.jsxs(a.Fragment,{children:[a.jsxs(Te,{variant:"primary",size:"sm",onClick:ge,disabled:q.isPending||!r||!s,children:[q.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(gr,{className:"w-4 h-4"}),"Enable Backup"]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:he,disabled:K||!r||!s,children:[K?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Ur,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(Mn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),de&&de.length>0&&a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(x0,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),a.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>te.mutate(),disabled:te.isPending,children:[a.jsx(en,{className:"w-4 h-4"}),"Clear"]})]})}),a.jsx(Nt,{children:a.jsx("div",{className:"overflow-x-auto",children:a.jsxs("table",{className:"w-full text-sm",children:[a.jsx("thead",{children:a.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[a.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),a.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),a.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),a.jsx("tbody",{children:de.slice(0,10).map(Z=>a.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[a.jsx("td",{className:"py-2 px-2 text-white",children:JQe(Z.started_at)}),a.jsx("td",{className:"py-2 px-2",children:a.jsx(JW,{status:Z.status})}),a.jsx("td",{className:"py-2 px-2",children:Z.commit_sha?a.jsxs("a",{href:`${ee?.repository_url}/commit/${Z.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[Z.commit_sha.substring(0,7),a.jsx(Xr,{className:"w-3 h-3"})]}):a.jsx("span",{className:"text-bambu-gray",children:"-"})})]},Z.id))})]})})})]})]}),a.jsx("div",{className:"space-y-6",children:a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Ec,{className:"w-5 h-5 text-gray-400"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Create a complete backup of your Bambuddy data including the database, archives, uploads, and all files."}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Download Backup"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),a.jsxs(Te,{variant:"secondary",size:"sm",disabled:k||C,onClick:async()=>{T(!0),P("Preparing backup...");try{P("Creating backup archive... This may take a while for large archives.");const{blob:Z,filename:z}=await se.exportBackup();P("Downloading backup file...");const F=URL.createObjectURL(Z),W=document.createElement("a");W.href=F,W.download=z,W.click(),URL.revokeObjectURL(F),e("Backup downloaded successfully")}catch(Z){e(`Failed to create backup: ${Z instanceof Error?Z.message:"Unknown error"}`,"error")}finally{T(!1),P("")}},children:[a.jsx(ui,{className:"w-4 h-4"}),"Download"]})]}),a.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:n("backup.restoreBackup")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.restoreDescription")}),a.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:n("backup.restoreNote")})]}),a.jsx("input",{ref:I,type:"file",accept:".zip",className:"hidden",onChange:Z=>{const z=Z.target.files?.[0];z&&(D(z),L(!0)),Z.target.value=""}}),a.jsxs(Te,{variant:"secondary",size:"sm",disabled:C||k,onClick:()=>I.current?.click(),children:[a.jsx(sa,{className:"w-4 h-4"}),"Restore"]})]}),H&&a.jsx("div",{className:`p-3 rounded-lg ${H.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[H.success?a.jsx(gr,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):a.jsx(ha,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:H.success?"text-green-200":"text-red-200",children:[H.message,H.success&&a.jsx("div",{className:"mt-2",children:a.jsxs(Te,{size:"sm",onClick:()=>window.location.reload(),children:[a.jsx(Do,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Mn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"text-yellow-200",children:[a.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",a.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),U&&B&&a.jsx(Pn,{title:"Restore Backup",message:`Are you sure you want to restore from "${B.name}"? This will completely replace your current database and all files. The application will need to be restarted after restore.`,confirmText:"Restore Backup",variant:"danger",onConfirm:async()=>{L(!1),j(!0),G(null);try{P("Uploading backup file...");const Z=await se.importBackup(B);G(Z),Z.success?e("Backup restored. Please restart Bambuddy.","success"):e(Z.message,"error")}catch(Z){const z=Z instanceof Error?Z.message:"Failed to restore backup";G({success:!1,message:z}),e(z,"error")}finally{j(!1),P(""),D(null)}},onCancel:()=>{L(!1),D(null)}}),(k||C)&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center",children:[a.jsx("div",{className:"flex justify-center mb-4",children:a.jsxs("div",{className:"relative",children:[a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),a.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),a.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:k?"Creating Backup":"Restoring Backup"}),a.jsx("p",{className:"text-bambu-gray mb-4",children:E||(k?"Preparing...":"Processing...")}),a.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:a.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[a.jsx(Mn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}function tZe(){const{t}=Ut(),{showToast:e}=hn(),n=Zt(),[r,i]=w.useState({smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",smtp_security:"starttls",smtp_auth_enabled:!0,smtp_from_email:"",smtp_from_name:"BamBuddy"}),[s,o]=w.useState(""),{data:l,isLoading:c}=et({queryKey:["smtpSettings"],queryFn:()=>se.getSMTPSettings()}),{data:u}=et({queryKey:["advancedAuthStatus"],queryFn:()=>se.getAdvancedAuthStatus()});w.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const d=ot({mutationFn:b=>se.saveSMTPSettings(b),onSuccess:()=>{n.invalidateQueries({queryKey:["smtpSettings"]}),n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:b=>{e(b.message,"error")}}),h=ot({mutationFn:b=>se.testSMTP(b),onSuccess:b=>{e(b.message,b.success?"success":"error")},onError:b=>{e(b.message,"error")}}),f=ot({mutationFn:b=>b?se.enableAdvancedAuth():se.disableAdvancedAuth(),onSuccess:b=>{n.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(b.message,"success")},onError:b=>{e(b.message,"error")}}),p=()=>{if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(r.smtp_auth_enabled&&!r.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}d.mutate(r)},x=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.smtpServerAndEmail"),"error");return}if(r.smtp_auth_enabled&&(!r.smtp_username||!r.smtp_password)){e(t("settings.email.errors.usernamePasswordRequired"),"error");return}h.mutate({smtp_host:r.smtp_host,smtp_port:r.smtp_port,smtp_username:r.smtp_username,smtp_password:r.smtp_password,smtp_security:r.smtp_security,smtp_auth_enabled:r.smtp_auth_enabled,smtp_from_email:r.smtp_from_email,test_recipient:s})},v=()=>{if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}f.mutate(!u?.advanced_auth_enabled)};return c?a.jsx("div",{className:"flex items-center justify-center p-12",children:a.jsx(it,{className:"w-8 h-8 animate-spin text-bambu-green"})}):a.jsxs("div",{className:"space-y-6",children:[u?.smtp_configured&&a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(y0,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),a.jsx(Te,{onClick:v,disabled:f.isPending,variant:u?.advanced_auth_enabled?"danger":"primary",children:u?.advanced_auth_enabled?a.jsxs(a.Fragment,{children:[a.jsx(WS,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):a.jsxs(a.Fragment,{children:[a.jsx(Vm,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),a.jsx(Nt,{children:a.jsx("div",{className:"space-y-4",children:u?.advanced_auth_enabled?a.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(gr,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),a.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[a.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),a.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),a.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),a.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):a.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(Mn,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),a.jsxs("div",{className:"space-y-2",children:[a.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),a.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),a.jsx(Nt,{children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),a.jsx("input",{type:"text",value:r.smtp_host,onChange:b=>i({...r,smtp_host:b.target.value}),placeholder:"smtp.gmail.com",className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.smtpPort")||"SMTP Port"}),a.jsx("input",{type:"number",value:r.smtp_port,onChange:b=>i({...r,smtp_port:parseInt(b.target.value)||587}),placeholder:"587",className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.security")||"Security"}),a.jsxs("select",{value:r.smtp_security,onChange:b=>i({...r,smtp_security:b.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",children:[a.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),a.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),a.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.authentication")||"Authentication"}),a.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:b=>i({...r,smtp_auth_enabled:b.target.value==="true"}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",children:[a.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),a.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]})]}),r.smtp_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.username")||"Username"}),a.jsx("input",{type:"text",value:r.smtp_username||"",onChange:b=>i({...r,smtp_username:b.target.value}),placeholder:"your.email@gmail.com",className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.password")||"Password"}),a.jsx("input",{type:"password",value:r.smtp_password||"",onChange:b=>i({...r,smtp_password:b.target.value}),placeholder:l?"••••••••":"App password",className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"})]})]}),a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[t("settings.email.fromEmail")||"From Email"," *"]}),a.jsx("input",{type:"email",value:r.smtp_from_email,onChange:b=>i({...r,smtp_from_email:b.target.value}),placeholder:"your@email.com",className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.fromName")||"From Name"}),a.jsx("input",{type:"text",value:r.smtp_from_name,onChange:b=>i({...r,smtp_from_name:b.target.value}),placeholder:"BamBuddy",className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"})]})]}),a.jsx("div",{className:"flex gap-2",children:a.jsx(Te,{onClick:p,disabled:d.isPending,className:"flex-1",children:d.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),a.jsx(Nt,{children:a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:t("settings.email.testRecipient")||"Test Recipient Email"}),a.jsx("input",{type:"email",value:s,onChange:b=>o(b.target.value),placeholder:"test@example.com",className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors"})]}),a.jsx(Te,{onClick:x,disabled:h.isPending,variant:"secondary",children:h.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):a.jsxs(a.Fragment,{children:[a.jsx(rk,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})]})}const nZe={get:"bg-blue-500/20 text-blue-400 border-blue-500/30",post:"bg-green-500/20 text-green-400 border-green-500/30",put:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",patch:"bg-orange-500/20 text-orange-400 border-orange-500/30",delete:"bg-red-500/20 text-red-400 border-red-500/30"};function rZe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function By(t,e,n=0){if(n>5)return"...";if(e.$ref)return By(t,rZe(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const s=By(t,i,n+1);typeof s=="object"&&s!==null&&Object.assign(r,s)}return r}if(e.example!==void 0)return e.example;if(e.default!==void 0)return e.default;switch(e.type){case"string":return e.enum?e.enum[0]:"string";case"integer":case"number":return 0;case"boolean":return!1;case"array":return e.items?[By(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,s]of Object.entries(e.properties))r[i]=By(t,s,n+1);return r}return{};default:return null}}function iZe({path:t,method:e,spec:n,schema:r,apiKey:i}){const[s,o]=w.useState(!1),[l,c]=w.useState({}),[u,d]=w.useState(""),[h,f]=w.useState(null),[p,x]=w.useState(!1),[v,b]=w.useState(!1);w.useEffect(()=>{if(s&&n.parameters){const j={};for(const E of n.parameters)E.schema?.default!==void 0&&(j[E.name]=String(E.schema.default));c(E=>({...j,...E}))}},[s,n.parameters]),w.useEffect(()=>{if(s&&n.requestBody?.content?.["application/json"]?.schema&&!u){const j=n.requestBody.content["application/json"].schema,E=By(r,j);d(JSON.stringify(E,null,2))}},[s,n.requestBody,r,u]);const S=(()=>{const j=[];for(const E of n.parameters||[])if(E.in==="path"||E.required){const P=l[E.name];(P===void 0||P==="")&&j.push(E.name)}return j})(),N=async()=>{if(S.length>0){f({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${S.join(", ")}`,duration:0});return}x(!0),f(null);try{let j=t;const E=new URLSearchParams;for(const ae of n.parameters||[]){const V=l[ae.name];V!==void 0&&V!==""&&(ae.in==="path"?j=j.replace(`{${ae.name}}`,encodeURIComponent(V)):ae.in==="query"&&E.append(ae.name,V))}const P=E.toString(),U=`${j}${P?`?${P}`:""}`,L={"Content-Type":"application/json"};i&&(L["X-API-Key"]=i);const B={method:e.toUpperCase(),headers:L};["post","put","patch"].includes(e)&&u&&(B.body=u);const D=performance.now(),H=await fetch(U,B),G=Math.round(performance.now()-D),I={};H.headers.forEach((ae,V)=>{I[V]=ae});let K;H.headers.get("content-type")?.includes("application/json")?K=await H.json():K=await H.text(),f({status:H.status,statusText:H.statusText,headers:I,body:K,duration:G})}catch(j){f({status:0,statusText:"Network Error",headers:{},body:j instanceof Error?j.message:"Unknown error",duration:0})}finally{x(!1)}},M=async()=>{if(h){const j=typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2);try{await navigator.clipboard.writeText(j),b(!0),setTimeout(()=>b(!1),2e3)}catch{const E=document.createElement("textarea");E.value=j,E.style.position="fixed",E.style.left="-999999px",document.body.appendChild(E),E.select(),document.execCommand("copy"),document.body.removeChild(E),b(!0),setTimeout(()=>b(!1),2e3)}}},k=(n.parameters||[]).filter(j=>j.in==="path"),T=(n.parameters||[]).filter(j=>j.in==="query"),C=["post","put","patch"].includes(e)&&n.requestBody;return a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("button",{onClick:()=>o(!s),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[s?a.jsx(Jn,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):a.jsx(Fa,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),a.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${nZe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),a.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&a.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),s&&a.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&a.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),k.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),a.jsx("div",{className:"space-y-2",children:k.map(j=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),a.jsx("input",{type:"text",value:l[j.name]||"",onChange:E=>c(P=>({...P,[j.name]:E.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),T.length>0&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),a.jsx("div",{className:"space-y-2",children:T.map(j=>a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[j.name,j.required&&a.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),j.schema?.enum?a.jsxs("select",{value:l[j.name]||"",onChange:E=>c(P=>({...P,[j.name]:E.target.value})),className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"",children:"-- Select --"}),j.schema.enum.map(E=>a.jsx("option",{value:E,children:E},E))]}):a.jsx("input",{type:"text",value:l[j.name]||"",onChange:E=>c(P=>({...P,[j.name]:E.target.value})),placeholder:j.description||j.schema?.type||"value",className:"flex-1 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none"})]},j.name))})]}),C&&a.jsxs("div",{className:"space-y-2",children:[a.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),a.jsx("textarea",{value:u,onChange:j=>d(j.target.value),rows:8,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono focus:border-bambu-green focus:outline-none resize-y",placeholder:"JSON request body..."})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Te,{onClick:N,disabled:p,children:[p?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(jo,{className:"w-4 h-4"}),"Execute"]}),S.length>0&&a.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[a.jsx(Bi,{className:"w-3 h-3"}),"Fill in: ",S.join(", ")]})]}),h&&a.jsxs("div",{className:"space-y-2",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",a.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${h.status>=200&&h.status<300?"bg-green-500/20 text-green-400":h.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[h.status," ",h.statusText]}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:[h.duration,"ms"]})]}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:M,children:v?a.jsx(gr,{className:"w-3 h-3 text-green-400"}):a.jsx(Kl,{className:"w-3 h-3"})})]}),a.jsx("pre",{className:"p-3 bg-bambu-dark rounded-lg text-sm font-mono text-white overflow-auto max-h-96 border border-bambu-dark-tertiary",children:typeof h.body=="string"?h.body:JSON.stringify(h.body,null,2)})]})]})]})}function aZe({apiKey:t=""}){const[e,n]=w.useState(null),[r,i]=w.useState(!0),[s,o]=w.useState(null),[l,c]=w.useState(new Set),[u,d]=w.useState("");if(w.useEffect(()=>{async function b(){try{const y=await fetch("/openapi.json");if(!y.ok)throw new Error("Failed to fetch OpenAPI schema");const S=await y.json();n(S)}catch(y){o(y instanceof Error?y.message:"Unknown error")}finally{i(!1)}}b()},[]),r)return a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(s||!e)return a.jsx(_t,{children:a.jsx(Nt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-red-400",children:[a.jsx(Bi,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),a.jsx("p",{children:"Failed to load API schema"}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:s})]})})});const h={};for(const[b,y]of Object.entries(e.paths))for(const[S,N]of Object.entries(y)){if(S==="parameters")continue;const M=N.tags||["Other"];for(const k of M)h[k]||(h[k]=[]),h[k].push({path:b,method:S,spec:N})}const f=Object.entries(h).map(([b,y])=>{if(!u)return{tag:b,endpoints:y};const S=y.filter(({path:N,method:M,spec:k})=>{const T=u.toLowerCase();return N.toLowerCase().includes(T)||M.toLowerCase().includes(T)||(k.summary?.toLowerCase()||"").includes(T)||(k.description?.toLowerCase()||"").includes(T)});return{tag:b,endpoints:S}}).filter(({endpoints:b})=>b.length>0).sort((b,y)=>b.tag.localeCompare(y.tag)),p=b=>{c(y=>{const S=new Set(y);return S.has(b)?S.delete(b):S.add(b),S})},x=()=>{c(new Set(f.map(b=>b.tag)))},v=()=>{c(new Set)};return a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between gap-4",children:[a.jsx("div",{className:"flex-1",children:a.jsx("input",{type:"text",value:u,onChange:b=>d(b.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(Te,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:v,children:"Collapse All"}),a.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[a.jsx(Xr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:[f.reduce((b,y)=>b+y.endpoints.length,0)," endpoints in ",f.length," categories"]}),a.jsx("div",{className:"space-y-3",children:f.map(({tag:b,endpoints:y})=>a.jsxs(_t,{children:[a.jsx("button",{onClick:()=>p(b),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:a.jsxs("div",{className:"flex items-center gap-2",children:[l.has(b)?a.jsx(Jn,{className:"w-5 h-5 text-bambu-gray"}):a.jsx(Fa,{className:"w-5 h-5 text-bambu-gray"}),a.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:b.replace(/-/g," ")}),a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:y.length})]})}),l.has(b)&&a.jsx(Nt,{className:"pt-0 space-y-2",children:y.map(({path:S,method:N,spec:M})=>a.jsx(iZe,{path:S,method:N,spec:M,schema:e,apiKey:t},`${N}-${S}`))})]},b))})]})}const sZe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"];function oZe(){const t=Zt(),e=Gc(),[n,r]=xF(),{t:i,i18n:s}=Ut(),{showToast:o}=hn(),{authEnabled:l,user:c,refreshAuth:u}=Fr(),{mode:d,darkStyle:h,darkBackground:f,darkAccent:p,lightStyle:x,lightBackground:v,lightAccent:b,setDarkStyle:y,setDarkBackground:S,setDarkAccent:N,setLightStyle:M,setLightBackground:k,setLightAccent:T}=rp(),[C,j]=w.useState(null),[E,P]=w.useState(!1),[U,L]=w.useState(null),[B,D]=w.useState(!1),[H,G]=w.useState(null),[I,K]=w.useState(null),[Q,ae]=w.useState(!1),[V,Y]=w.useState(xX()),ne=n.get("tab"),ee=ne==="email",ve=ee?"users":ne&&sZe.includes(ne)?ne:"general",[fe,de]=w.useState(ve),[Re,ue]=w.useState(ee?"email":"users"),le=oe=>{de(oe),oe==="users"&&ue("users"),oe==="general"?n.delete("tab"):n.set("tab",oe),r(n,{replace:!0})},[Ne,J]=w.useState(!1),[Le,$]=w.useState(""),[X,ce]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[q,ie]=w.useState(null),[te,he]=w.useState(null),[ge,Z]=w.useState(""),[z,F]=w.useState(!1),[W,me]=w.useState(!1),[_e,be]=w.useState(null),[He,Se]=w.useState(!1),[$e,Qe]=w.useState(!1),[ye,we]=w.useState(!1),[Ce,Ue]=w.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[je,Ve]=w.useState(!1),[Ae,Ze]=w.useState(!1),[Pe,Xe]=w.useState(!1),[Fe,Oe]=w.useState(null),[Me,Je]=w.useState(null),[yt,Mt]=w.useState(null),[an,Pt]=w.useState(!1),[Ie,gt]=w.useState({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),[Qt,tn]=w.useState(!1),[un,hr]=w.useState(null),[yr,sr]=w.useState(null),[Xt,or]=w.useState({name:"",description:"",permissions:[]}),[yi,Ia]=w.useState(new Set),[De,nt]=w.useState(null),[dt,pt]=w.useState(!1),[lt,Ft]=w.useState({}),[pe,ze]=w.useState({}),Ke=oe=>{Y(oe),$pe(oe),o(i("settings.toast.settingsSaved"),"success")},Ge=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:xe,isLoading:at}=et({queryKey:["settings"],queryFn:se.getSettings}),{data:ht,isLoading:rt}=et({queryKey:["smart-plugs"],queryFn:se.getSmartPlugs}),{data:At,isLoading:$t}=et({queryKey:["smart-plugs-energy",ht?.map(oe=>oe.id)],queryFn:async()=>{if(!ht||ht.length===0)return null;const oe=await Promise.all(ht.filter(Cs=>Cs.enabled).map(async Cs=>{try{const ss=await se.getSmartPlugStatus(Cs.id);return{plug:Cs,status:ss}}catch{return{plug:Cs,status:null}}}));let kt=0,Hn=0,er=0,Oo=0,_d=0;for(const{plug:Cs,status:ss}of oe){const OM=Cs.plug_type==="mqtt"&&ss?.energy?.power!=null;(ss?.reachable||OM)&&ss?.energy&&(_d++,ss.energy?.power!=null&&(kt+=ss.energy.power),ss.energy?.today!=null&&(Hn+=ss.energy.today),ss.energy?.yesterday!=null&&(er+=ss.energy.yesterday),ss.energy?.total!=null&&(Oo+=ss.energy.total))}return{totalPower:kt,totalToday:Hn,totalYesterday:er,totalLifetime:Oo,reachableCount:_d,totalPlugs:ht.filter(Cs=>Cs.enabled).length}},enabled:fe==="plugs"&&!!ht&&ht.length>0,refetchInterval:fe==="plugs"?1e4:!1}),{data:Dt,isLoading:Et}=et({queryKey:["notification-providers"],queryFn:se.getNotificationProviders}),{data:Jt,isLoading:Kt}=et({queryKey:["api-keys"],queryFn:se.getAPIKeys}),mn=ot({mutationFn:oe=>se.createAPIKey(oe),onSuccess:oe=>{ie(oe.key||null),J(!1),$(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:oe=>{o(`Failed to create API key: ${oe.message}`,"error")}}),Tn=ot({mutationFn:oe=>se.deleteAPIKey(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyDeleted"))},onError:oe=>{o(`Failed to delete API key: ${oe.message}`,"error")}}),{data:bn}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:Vt,isLoading:fn}=et({queryKey:["notification-templates"],queryFn:se.getNotificationTemplates}),{data:pn}=et({queryKey:["virtual-printer-settings"],queryFn:KS.getSettings,refetchInterval:1e4}),Gr=pn?.status?.running??!1,{data:qr}=et({queryKey:["ffmpeg-status"],queryFn:se.checkFfmpeg}),{data:Dn}=et({queryKey:["version"],queryFn:se.getVersion}),{data:_n,refetch:Gn,isRefetching:hi}=et({queryKey:["updateCheck"],queryFn:se.checkForUpdates,staleTime:300*1e3}),{data:mr,refetch:vi}=et({queryKey:["updateStatus"],queryFn:se.getUpdateStatus,refetchInterval:oe=>{const kt=oe.state.data;return kt?.status==="downloading"||kt?.status==="installing"?1e3:!1}}),{data:bt}=et({queryKey:["mqtt-status"],queryFn:se.getMQTTStatus,refetchInterval:fe==="network"?5e3:!1}),{data:Ot}=et({queryKey:["github-backup-status"],queryFn:se.getGitHubBackupStatus}),{data:zn}=et({queryKey:["cloud-status"],queryFn:se.getCloudStatus}),{data:vt={advanced_auth_enabled:!1,smtp_configured:!1}}=et({queryKey:["advancedAuthStatus"],queryFn:()=>se.getAdvancedAuthStatus()}),{hasPermission:Cn}=Fr(),{data:Zr=[],isLoading:fr}=et({queryKey:["users"],queryFn:()=>se.getUsers(),enabled:l&&Cn("users:read")}),{data:mi=[],isLoading:_a}=et({queryKey:["groups"],queryFn:()=>se.getGroups(),enabled:l&&Cn("groups:read")}),{data:Gt}=et({queryKey:["permissions"],queryFn:()=>se.getPermissions(),enabled:l&&Cn("groups:read")}),gn=ot({mutationFn:oe=>se.createUser(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Ze(!1),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:oe=>{o(oe.message,"error")}}),za=ot({mutationFn:({id:oe,data:kt})=>se.updateUser(oe,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Xe(!1),Oe(null),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:oe=>{o(oe.message,"error")}}),Jr=ot({mutationFn:({id:oe,deleteItems:kt})=>se.deleteUser(oe,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),Je(null),Mt(null)},onError:oe=>{o(oe.message,"error")}}),Ua=ot({mutationFn:oe=>se.resetUserPassword({user_id:oe}),onSuccess:oe=>{o(oe.message,"success")},onError:oe=>{o(oe.message,"error")}}),Nl=async oe=>{Je(oe),Pt(!0);try{const kt=await se.getUserItemsCount(oe);Mt(kt)}catch{Mt({archives:0,queue_items:0,library_files:0})}finally{Pt(!1)}},Sa=ot({mutationFn:oe=>se.createGroup(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),tn(!1),wi(),o(i("settings.toast.groupCreated"))},onError:oe=>{o(oe.message,"error")}}),Vi=ot({mutationFn:({id:oe,data:kt})=>se.updateGroup(oe,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),hr(null),wi(),o(i("settings.toast.groupUpdated"))},onError:oe=>{o(oe.message,"error")}}),Gi=ot({mutationFn:oe=>se.deleteGroup(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:oe=>{o(oe.message,"error")}}),Li=()=>{const oe=vt?.advanced_auth_enabled||!1;if(!Ie.username){o(i("settings.toast.fillRequiredFields"),"error");return}if(oe&&!Ie.email){o("Email is required when advanced authentication is enabled","error");return}if(!oe){if(!Ie.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(Ie.password!==Ie.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ie.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}gn.mutate({username:Ie.username,password:oe?void 0:Ie.password,email:Ie.email||void 0,role:Ie.role,group_ids:Ie.group_ids.length>0?Ie.group_ids:void 0})},Or=oe=>{if(Ie.password){if(Ie.password!==Ie.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ie.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}const kt={username:Ie.username||void 0,password:Ie.password||void 0,role:Ie.role,group_ids:Ie.group_ids};kt.password||delete kt.password,za.mutate({id:oe,data:kt})},Cl=oe=>{Oe(oe.id),gt({username:oe.username,password:"",email:oe.email||"",confirmPassword:"",role:oe.role,group_ids:oe.groups?.map(kt=>kt.id)||[]}),Xe(!0)},Ba=oe=>{gt(kt=>({...kt,group_ids:kt.group_ids.includes(oe)?kt.group_ids.filter(Hn=>Hn!==oe):[...kt.group_ids,oe]}))},wi=()=>{or({name:"",description:"",permissions:[]}),Ia(new Set)},ic=()=>{if(!Xt.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}Sa.mutate({name:Xt.name,description:Xt.description||void 0,permissions:Xt.permissions})},Wr=()=>{if(un){if(!Xt.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}Vi.mutate({id:un.id,data:{name:Xt.name!==un.name?Xt.name:void 0,description:Xt.description,permissions:Xt.permissions}})}},_i=oe=>{hr(oe),or({name:oe.name,description:oe.description||"",permissions:oe.permissions});const kt=new Set;Gt?.categories.forEach(Hn=>{Hn.permissions.some(er=>oe.permissions.includes(er.value))&&kt.add(Hn.name)}),Ia(kt)},co=oe=>{Ia(kt=>{const Hn=new Set(kt);return Hn.has(oe)?Hn.delete(oe):Hn.add(oe),Hn})},vr=oe=>{or(kt=>{const Hn=kt.permissions.includes(oe)?kt.permissions.filter(er=>er!==oe):[...kt.permissions,oe];return{...kt,permissions:Hn}})},Yn=(oe,kt)=>{or(Hn=>{const er=oe.permissions.map(Cs=>Cs.value),Oo=Hn.permissions.filter(Cs=>!er.includes(Cs)),_d=kt?[...Oo,...er]:Oo;return{...Hn,permissions:_d}})},kl=oe=>oe.permissions.every(kt=>Xt.permissions.includes(kt.value)),hm=oe=>{const kt=oe.permissions.filter(Hn=>Xt.permissions.includes(Hn.value));return kt.length>0&&kt.length{oe.is_docker?o(oe.message,"error"):vi()}}),[wd,mm]=w.useState(null),fm=ot({mutationFn:se.testAllNotificationProviders,onSuccess:oe=>{mm(oe),t.invalidateQueries({queryKey:["notification-providers"]}),oe.failed===0?o(`All ${oe.tested} providers tested successfully!`,"success"):o(`${oe.success}/${oe.tested} providers succeeded`,oe.failed>0?"error":"success")},onError:oe=>{o(`Failed to test providers: ${oe.message}`,"error")}}),Ml=ot({mutationFn:async oe=>{if(!ht)return{success:0,failed:0};const kt=ht.filter(er=>er.enabled),Hn=await Promise.all(kt.map(async er=>{try{return await se.controlSmartPlug(er.id,oe),{success:!0}}catch{return{success:!1}}}));return{success:Hn.filter(er=>er.success).length,failed:Hn.filter(er=>!er.success).length}},onSuccess:(oe,kt)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),oe.failed===0?o(`All ${oe.success} plugs turned ${kt}`,"success"):o(`${oe.success} plugs turned ${kt}, ${oe.failed} failed`,"error")},onError:oe=>{o(`Failed: ${oe.message}`,"error")}}),ac=w.useRef(null),pm=w.useRef(!1),Kv=w.useRef(!0);w.useEffect(()=>{if(xe&&!C){const oe={...xe,external_url:xe.external_url||window.location.origin};j(oe),setTimeout(()=>{Kv.current=!1},100)}},[xe,C]);const Xv=ot({mutationFn:se.updateSettings,onSuccess:oe=>{t.setQueryData(["settings"],oe),j(oe),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:oe=>{o(`Failed to save: ${oe.message}`,"error")},onSettled:()=>{pm.current=!1}}),Yv=ot({mutationFn:({id:oe,data:kt})=>se.updatePrinter(oe,kt),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:oe=>{o(`Failed to update printer: ${oe.message}`,"error")}});w.useEffect(()=>{if(!(Kv.current||!C||!xe||!(xe.auto_archive!==C.auto_archive||xe.save_thumbnails!==C.save_thumbnails||xe.capture_finish_photo!==C.capture_finish_photo||xe.default_filament_cost!==C.default_filament_cost||xe.currency!==C.currency||xe.energy_cost_per_kwh!==C.energy_cost_per_kwh||xe.energy_tracking_mode!==C.energy_tracking_mode||xe.check_updates!==C.check_updates||(xe.check_printer_firmware??!0)!==(C.check_printer_firmware??!0)||xe.notification_language!==C.notification_language||xe.ams_humidity_good!==C.ams_humidity_good||xe.ams_humidity_fair!==C.ams_humidity_fair||xe.ams_temp_good!==C.ams_temp_good||xe.ams_temp_fair!==C.ams_temp_fair||xe.ams_history_retention_days!==C.ams_history_retention_days||xe.per_printer_mapping_expanded!==C.per_printer_mapping_expanded||xe.date_format!==C.date_format||xe.time_format!==C.time_format||xe.default_printer_id!==C.default_printer_id||xe.ftp_retry_enabled!==C.ftp_retry_enabled||xe.ftp_retry_count!==C.ftp_retry_count||xe.ftp_retry_delay!==C.ftp_retry_delay||xe.ftp_timeout!==C.ftp_timeout||xe.mqtt_enabled!==C.mqtt_enabled||xe.mqtt_broker!==C.mqtt_broker||xe.mqtt_port!==C.mqtt_port||xe.mqtt_username!==C.mqtt_username||xe.mqtt_password!==C.mqtt_password||xe.mqtt_topic_prefix!==C.mqtt_topic_prefix||xe.mqtt_use_tls!==C.mqtt_use_tls||xe.external_url!==C.external_url||xe.ha_enabled!==C.ha_enabled||xe.ha_url!==C.ha_url||xe.ha_token!==C.ha_token||(xe.library_archive_mode??"ask")!==(C.library_archive_mode??"ask")||Number(xe.library_disk_warning_gb??5)!==Number(C.library_disk_warning_gb??5)||(xe.camera_view_mode??"window")!==(C.camera_view_mode??"window")||(xe.preferred_slicer??"bambu_studio")!==(C.preferred_slicer??"bambu_studio")||xe.prometheus_enabled!==C.prometheus_enabled||xe.prometheus_token!==C.prometheus_token))&&!pm.current)return ac.current&&clearTimeout(ac.current),ac.current=setTimeout(()=>{if(pm.current)return;pm.current=!0;const kt={auto_archive:C.auto_archive,save_thumbnails:C.save_thumbnails,capture_finish_photo:C.capture_finish_photo,default_filament_cost:C.default_filament_cost,currency:C.currency,energy_cost_per_kwh:C.energy_cost_per_kwh,energy_tracking_mode:C.energy_tracking_mode,check_updates:C.check_updates,check_printer_firmware:C.check_printer_firmware,notification_language:C.notification_language,ams_humidity_good:C.ams_humidity_good,ams_humidity_fair:C.ams_humidity_fair,ams_temp_good:C.ams_temp_good,ams_temp_fair:C.ams_temp_fair,ams_history_retention_days:C.ams_history_retention_days,per_printer_mapping_expanded:C.per_printer_mapping_expanded,date_format:C.date_format,time_format:C.time_format,default_printer_id:C.default_printer_id,ftp_retry_enabled:C.ftp_retry_enabled,ftp_retry_count:C.ftp_retry_count,ftp_retry_delay:C.ftp_retry_delay,ftp_timeout:C.ftp_timeout,mqtt_enabled:C.mqtt_enabled,mqtt_broker:C.mqtt_broker,mqtt_port:C.mqtt_port,mqtt_username:C.mqtt_username,mqtt_password:C.mqtt_password,mqtt_topic_prefix:C.mqtt_topic_prefix,mqtt_use_tls:C.mqtt_use_tls,external_url:C.external_url,ha_enabled:C.ha_enabled,ha_url:C.ha_url,ha_token:C.ha_token,library_archive_mode:C.library_archive_mode,library_disk_warning_gb:C.library_disk_warning_gb,camera_view_mode:C.camera_view_mode,preferred_slicer:C.preferred_slicer,prometheus_enabled:C.prometheus_enabled,prometheus_token:C.prometheus_token};Xv.mutate(kt)},500),()=>{ac.current&&clearTimeout(ac.current)}},[C,xe,Xv]);const xn=w.useCallback((oe,kt)=>{j(Hn=>Hn?{...Hn,[oe]:kt}:null)},[]),LM=async(oe,kt,Hn)=>{if(!kt){o(i("settings.toast.enterCameraUrl"),"error");return}ze(er=>({...er,[oe]:!0})),Ft(er=>({...er,[oe]:null}));try{const er=await se.testExternalCamera(oe,kt,Hn);Ft(Oo=>({...Oo,[oe]:er})),er.success?o(i("settings.toast.cameraConnected",{resolution:er.resolution||""}),"success"):o(er.error||i("settings.toast.connectionFailed"),"error")}catch(er){const Oo=er instanceof Error?er.message:i("settings.toast.testFailed");Ft(_d=>({..._d,[oe]:{success:!1,error:Oo}})),o(Oo,"error")}finally{ze(er=>({...er,[oe]:!1}))}},[dx,Qv]=w.useState({}),hx=w.useRef({}),Zv=w.useRef(new Set);w.useEffect(()=>{if(bn){const oe={};bn.forEach(kt=>{kt.external_camera_url&&!Zv.current.has(kt.id)&&(oe[kt.id]=kt.external_camera_url,Zv.current.add(kt.id))}),Object.keys(oe).length>0&&Qv(kt=>({...kt,...oe}))}},[bn]);const Jv=(oe,kt)=>{Qv(Hn=>({...Hn,[oe]:kt})),hx.current[oe]&&clearTimeout(hx.current[oe]),hx.current[oe]=setTimeout(()=>{Yv.mutate({id:oe,data:{external_camera_url:kt||null}})},800)},ew=(oe,kt)=>{const Hn={};kt.type!==void 0&&(Hn.external_camera_type=kt.type||null),kt.enabled!==void 0&&(Hn.external_camera_enabled=kt.enabled),Yv.mutate({id:oe,data:Hn})};return at||!C?a.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"p-4 md:p-8",children:[a.jsxs("div",{className:"mb-8",children:[a.jsx("h1",{className:"text-2xl font-bold text-white",children:i("settings.title")}),a.jsx("p",{className:"text-bambu-gray",children:i("settings.configureBambuddy")})]}),a.jsxs("div",{className:"flex flex-wrap gap-1 mb-6 border-b border-bambu-dark-tertiary",children:[a.jsx("button",{onClick:()=>le("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${fe==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:i("settings.tabs.general")}),a.jsxs("button",{onClick:()=>le("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(dl,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),ht&&ht.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:ht.length})]}),a.jsxs("button",{onClick:()=>le("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Gg,{className:"w-4 h-4"}),i("settings.tabs.notifications"),Dt&&Dt.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Dt.length})]}),a.jsxs("button",{onClick:()=>le("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(whe,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),a.jsxs("button",{onClick:()=>le("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Wg,{className:"w-4 h-4"}),i("settings.tabs.network"),a.jsx("span",{className:`w-2 h-2 rounded-full ${bt?.enabled?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>le("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(tl,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),Jt&&Jt.length>0&&a.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Jt.length})]}),a.jsxs("button",{onClick:()=>le("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Cr,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),a.jsx("span",{className:`w-2 h-2 rounded-full ${Gr?"bg-green-400":"bg-gray-500"}`})]}),a.jsxs("button",{onClick:()=>le("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(gh,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]}),a.jsxs("button",{onClick:()=>le("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${fe==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(Ec,{className:"w-4 h-4"}),i("settings.tabs.backup"),a.jsx("span",{className:`w-2 h-2 rounded-full ${zn?.is_authenticated&&Ot?.configured&&Ot?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),fe==="general"&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a.jsx(Ph,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:s.language,onChange:oe=>{s.changeLanguage(oe.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:gB.map(oe=>a.jsxs("option",{value:oe.code,children:[oe.nativeName," (",oe.name,")"]},oe.code))}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),a.jsxs("div",{className:"relative",children:[a.jsx("select",{value:V,onChange:oe=>Ke(oe.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:v0.map(oe=>a.jsx("option",{value:oe.to,children:i(oe.labelKey)},oe.id))}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:C.date_format||"system",onChange:oe=>xn("date_format",oe.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),a.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),a.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:C.time_format||"system",onChange:oe=>xn("time_format",oe.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"system",children:i("settings.systemDefault")}),a.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),a.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:C.default_printer_id??"",onChange:oe=>xn("default_printer_id",oe.target.value?Number(oe.target.value):null),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),bn?.map(oe=>a.jsx("option",{value:oe.id,children:oe.name},oe.id))]}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.preferredSlicer")}),a.jsxs("div",{className:"relative",children:[a.jsxs("select",{value:C.preferred_slicer??"bambu_studio",onChange:oe=>xn("preferred_slicer",oe.target.value),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[a.jsx("option",{value:"bambu_studio",children:"Bambu Studio"}),a.jsx("option",{value:"orcaslicer",children:"OrcaSlicer"})]}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.preferredSlicerDescription")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:Ge,children:[a.jsx(Do,{className:"w-4 h-4"}),"Reset"]})]})]})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(ek,{className:"w-5 h-5"}),"Appearance"]})}),a.jsxs(Nt,{className:"space-y-6",children:[a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="dark"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&a.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),a.jsxs("select",{value:f,onChange:oe=>{S(oe.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:"Neutral"}),a.jsx("option",{value:"warm",children:"Warm"}),a.jsx("option",{value:"cool",children:"Cool"}),a.jsx("option",{value:"oled",children:"OLED Black"}),a.jsx("option",{value:"slate",children:"Slate Blue"}),a.jsx("option",{value:"forest",children:"Forest Green"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),a.jsxs("select",{value:p,onChange:oe=>{N(oe.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:"Green"}),a.jsx("option",{value:"teal",children:"Teal"}),a.jsx("option",{value:"blue",children:"Blue"}),a.jsx("option",{value:"orange",children:"Orange"}),a.jsx("option",{value:"purple",children:"Purple"}),a.jsx("option",{value:"red",children:"Red"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),a.jsxs("select",{value:h,onChange:oe=>{y(oe.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:"Classic"}),a.jsx("option",{value:"glow",children:"Glow"}),a.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),a.jsxs("div",{className:`space-y-3 p-4 rounded-lg border ${d==="light"?"border-bambu-green bg-bambu-green/5":"border-bambu-dark-tertiary"}`,children:[a.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&a.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),a.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),a.jsxs("select",{value:v,onChange:oe=>{k(oe.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"neutral",children:"Neutral"}),a.jsx("option",{value:"warm",children:"Warm"}),a.jsx("option",{value:"cool",children:"Cool"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),a.jsxs("select",{value:b,onChange:oe=>{T(oe.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"green",children:"Green"}),a.jsx("option",{value:"teal",children:"Teal"}),a.jsx("option",{value:"blue",children:"Blue"}),a.jsx("option",{value:"orange",children:"Orange"}),a.jsx("option",{value:"purple",children:"Purple"}),a.jsx("option",{value:"red",children:"Red"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),a.jsxs("select",{value:x,onChange:oe=>{M(oe.target.value),o(i("settings.toast.settingsSaved"),"success")},className:"w-full px-2 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"classic",children:"Classic"}),a.jsx("option",{value:"glow",children:"Glow"}),a.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Auto-archive prints"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.auto_archive,onChange:oe=>xn("auto_archive",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.save_thumbnails,onChange:oe=>xn("save_thumbnails",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.capture_finish_photo,onChange:oe=>xn("capture_finish_photo",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.capture_finish_photo&&qr&&!qr.installed&&a.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[a.jsx(Mn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"text-sm",children:[a.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),a.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",a.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",a.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(RF,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),a.jsxs("select",{value:C.camera_view_mode??"window",onChange:oe=>xn("camera_view_mode",oe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"window",children:i("settings.newWindow")}),a.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[a.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Configure external cameras to replace the built-in printer camera. Supports MJPEG streams, RTSP, HTTP snapshots, and USB cameras (V4L2). When enabled, the external camera is used for live view and finish photos."}),bn&&bn.length>0?a.jsx("div",{className:"space-y-3",children:bn.map(oe=>a.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-white font-medium text-sm",children:oe.name}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:oe.external_camera_enabled,onChange:kt=>ew(oe.id,{enabled:kt.target.checked}),className:"sr-only peer"}),a.jsx("div",{className:"w-9 h-5 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-bambu-green"})]})]}),oe.external_camera_enabled&&a.jsxs("div",{className:"space-y-2 mt-2",children:[a.jsx("input",{type:"text",placeholder:oe.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:dx[oe.id]??oe.external_camera_url??"",onChange:kt=>Jv(oe.id,kt.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs("select",{value:oe.external_camera_type||"mjpeg",onChange:kt=>ew(oe.id,{type:kt.target.value}),className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),a.jsx("option",{value:"rtsp",children:"RTSP Stream"}),a.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),a.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),a.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>LM(oe.id,dx[oe.id]??oe.external_camera_url??"",oe.external_camera_type||"mjpeg"),disabled:pe[oe.id]||!(dx[oe.id]??oe.external_camera_url),children:pe[oe.id]?a.jsx(it,{className:"w-4 h-4 animate-spin"}):"Test"})]}),lt[oe.id]&&a.jsx("div",{className:`text-xs flex items-center gap-1 ${lt[oe.id]?.success?"text-green-500":"text-red-500"}`,children:lt[oe.id]?.success?a.jsxs(a.Fragment,{children:[a.jsx(gr,{className:"w-3 h-3"}),"Connected",lt[oe.id]?.resolution&&` (${lt[oe.id]?.resolution})`]}):a.jsxs(a.Fragment,{children:[a.jsx(ha,{className:"w-3 h-3"}),lt[oe.id]?.error||i("settings.toast.connectionFailed")]})})]})]},oe.id))}):a.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),a.jsx("select",{value:C.currency,onChange:oe=>xn("currency",oe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:kQe.map(oe=>a.jsx("option",{value:oe.code,children:oe.label},oe.code))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:ju(C.currency)}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:C.default_filament_cost,onChange:oe=>xn("default_filament_cost",parseFloat(oe.target.value)||0),style:{paddingLeft:`${Math.max(2,ju(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),a.jsxs("div",{className:"relative",children:[a.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-bambu-gray text-sm pointer-events-none",children:ju(C.currency)}),a.jsx("input",{type:"number",step:"0.01",min:"0",value:C.energy_cost_per_kwh,onChange:oe=>xn("energy_cost_per_kwh",parseFloat(oe.target.value)||0),style:{paddingLeft:`${Math.max(2,ju(C.currency).length*.6+1)}rem`},className:"w-full pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),a.jsxs("select",{value:C.energy_tracking_mode||"total",onChange:oe=>xn("energy_tracking_mode",oe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"print",children:i("settings.printsOnly")}),a.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:C.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ps,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),a.jsxs("select",{value:C.library_archive_mode??"ask",onChange:oe=>xn("library_archive_mode",oe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),a.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),a.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:C.library_disk_warning_gb??5,onChange:oe=>xn("library_disk_warning_gb",parseFloat(oe.target.value)||5),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),a.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[a.jsx(QQe,{}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.check_updates,onChange:oe=>xn("check_updates",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.check_printer_firmware??!0,onChange:oe=>xn("check_printer_firmware",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),a.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),a.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",Dn?.version||"..."]})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>Gn(),disabled:hi,children:[hi?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Ur,{className:"w-4 h-4"}),"Check now"]})]}),_n?.update_available?a.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{children:[a.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",_n.latest_version]}),_n.release_name&&_n.release_name!==_n.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:_n.release_name})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[_n.release_notes&&a.jsx("button",{onClick:()=>Se(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),_n.release_url&&a.jsx("a",{href:_n.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:a.jsx(Xr,{className:"w-4 h-4"})})]})]}),mr?.status==="downloading"||mr?.status==="installing"?a.jsxs("div",{className:"mt-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),a.jsx("span",{children:mr.message})]}),a.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:a.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${mr.progress}%`}})})]}):mr?.status==="complete"?a.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:mr.message}):mr?.status==="error"?a.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:mr.error||mr.message}):_n?.is_docker?a.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),a.jsx("code",{className:"block text-xs bg-bambu-dark p-2 rounded text-bambu-green font-mono",children:"docker compose pull && docker compose up -d"})]}):a.jsxs(Te,{className:"mt-3",onClick:()=>Yc.mutate(),disabled:Yc.isPending,children:[Yc.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(ui,{className:"w-4 h-4"}),"Install Update"]})]}):_n?.error?a.jsxs("div",{className:"mt-2 p-2 bg-red-500/10 border border-red-500/30 rounded text-sm text-red-400",children:["Failed to check for updates: ",_n.error]}):_n&&!_n.update_available?a.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>F(!0),children:[a.jsx(en,{className:"w-4 h-4"}),i("common.clear")]})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>me(!0),children:[a.jsx(en,{className:"w-4 h-4"}),"Reset"]})]}),a.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:"Backup & Restore"}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),a.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>le("backup"),children:[a.jsx(Ec,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),fe==="network"&&C&&a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ph,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),a.jsx("input",{type:"text",value:C.external_url??"",onChange:oe=>xn("external_url",oe.target.value),placeholder:"http://192.168.1.100:8000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ur,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Retry FTP operations when printer WiFi is unreliable. Applies to 3MF downloads, print uploads, timelapse downloads, and firmware updates."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.ftp_retry_enabled??!0,onChange:oe=>xn("ftp_retry_enabled",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.ftp_retry_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:C.ftp_retry_count??3,onChange:oe=>xn("ftp_retry_count",parseInt(oe.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,4,5,6,7,8,9,10].map(oe=>a.jsxs("option",{value:oe,children:[oe," ",oe===1?"time":"times"]},oe))}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:C.ftp_retry_delay??2,onChange:oe=>xn("ftp_retry_delay",parseInt(oe.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[1,2,3,5,10,15,20,30].map(oe=>a.jsxs("option",{value:oe,children:[oe," ",oe===1?"second":"seconds"]},oe))}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),a.jsxs("div",{className:"relative w-44",children:[a.jsx("select",{value:C.ftp_timeout??30,onChange:oe=>xn("ftp_timeout",parseInt(oe.target.value)),className:"w-full px-3 py-2 pr-10 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none appearance-none cursor-pointer",children:[10,15,20,30,45,60,90,120].map(oe=>a.jsxs("option",{value:oe,children:[oe," seconds"]},oe))}),a.jsx(Jn,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Increase for printers with weak WiFi"})]})]})]})]})]}),a.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(dv,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),C.ha_enabled&&De&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${De.success?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${De.success?"text-green-400":"text-red-400"}`,children:De.success?"Connected":"Disconnected"})]})]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Home Assistant to control smart plugs via HA's REST API. Supports switch, light, input_boolean, and script entities."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")}),C.ha_env_managed&&a.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[a.jsx(Vm,{className:"w-3 h-3 text-bambu-green"}),a.jsx("span",{className:"text-xs text-bambu-green",children:i("settings.autoEnabledViaEnv")})]})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.ha_enabled??!1,onChange:oe=>xn("ha_enabled",oe.target.checked),disabled:C.ha_env_managed,className:"sr-only peer"}),a.jsx("div",{className:`w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green ${C.ha_env_managed?"opacity-60 cursor-not-allowed":""}`})]})]}),C.ha_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Home Assistant URL",C.ha_url_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"text",value:C.ha_url??"",onChange:oe=>xn("ha_url",oe.target.value),placeholder:"http://192.168.1.100:8123",disabled:C.ha_url_from_env,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${C.ha_url_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_url_from_env&&a.jsx(Vm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_url_from_env&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.urlFromEnvReadOnly")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Long-Lived Access Token",C.ha_token_from_env&&a.jsx("span",{className:"ml-2 text-xs text-bambu-green",children:i("settings.environmentManagedLabel")})]}),a.jsxs("div",{className:"relative",children:[a.jsx("input",{type:"password",value:C.ha_token??"",onChange:oe=>xn("ha_token",oe.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",disabled:C.ha_token_from_env,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${C.ha_token_from_env?"opacity-60 cursor-not-allowed":""}`}),C.ha_token_from_env&&a.jsx(Vm,{className:"absolute right-3 top-2.5 w-4 h-4 text-bambu-gray"})]}),C.ha_token_from_env?a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.tokenFromEnvReadOnly")}):a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),C.ha_url&&C.ha_token&&a.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:a.jsxs(Te,{variant:"secondary",size:"sm",disabled:dt,onClick:async()=>{pt(!0),nt(null);try{const oe=await se.testHAConnection(C.ha_url,C.ha_token);nt(oe)}catch(oe){nt({success:!1,message:null,error:oe instanceof Error?oe.message:i("common.unknownError")})}finally{pt(!1)}},children:[dt?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(Wg,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Wg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),bt?.enabled&&a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${bt.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:`text-sm ${bt.connected?"text-green-400":"text-red-400"}`,children:bt.connected?"Connected":"Disconnected"})]})]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish BamBuddy events to an external MQTT broker for integration with Node-RED, Home Assistant, and other automation systems."}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.mqtt_enabled??!1,onChange:oe=>xn("mqtt_enabled",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.mqtt_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),a.jsx("input",{type:"text",value:C.mqtt_broker??"",onChange:oe=>xn("mqtt_broker",oe.target.value),placeholder:"mqtt.example.com or 192.168.1.100",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-end gap-4",children:[a.jsxs("div",{className:"flex-1",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),a.jsx("input",{type:"number",min:"1",max:"65535",value:C.mqtt_port??1883,onChange:oe=>xn("mqtt_port",Math.min(65535,Math.max(1,parseInt(oe.target.value)||1883))),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.mqtt_use_tls??!1,onChange:oe=>{const kt=oe.target.checked;xn("mqtt_use_tls",kt);const Hn=C.mqtt_port??1883;kt&&Hn===1883?xn("mqtt_port",8883):!kt&&Hn===8883&&xn("mqtt_port",1883)},className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]}),a.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),a.jsx("input",{type:"text",value:C.mqtt_username??"",onChange:oe=>xn("mqtt_username",oe.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),a.jsx("input",{type:"password",value:C.mqtt_password??"",onChange:oe=>xn("mqtt_password",oe.target.value),placeholder:i("settings.leaveEmptyForAnonymous"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),a.jsx("input",{type:"text",value:C.mqtt_topic_prefix??"bambuddy",onChange:oe=>xn("mqtt_topic_prefix",oe.target.value),placeholder:"bambuddy",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",C.mqtt_topic_prefix||"bambuddy","/printers//status, etc."]})]}),bt&&a.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:a.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[a.jsx("span",{className:`w-2 h-2 rounded-full ${bt.connected?"bg-green-400":"bg-red-400"}`}),a.jsx("span",{className:"text-bambu-gray",children:bt.connected?a.jsxs(a.Fragment,{children:[i("settings.mqttConnectedTo")," ",a.jsxs("span",{className:"text-white",children:[bt.broker,":",bt.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),a.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(f3,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",a.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.prometheus_enabled??!1,onChange:oe=>xn("prometheus_enabled",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]}),C.prometheus_enabled&&a.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),a.jsx("input",{type:"password",value:C.prometheus_token??"",onChange:oe=>xn("prometheus_token",oe.target.value),placeholder:i("settings.leaveEmptyForNoAuth"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",a.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer "})]})]}),a.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[a.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),a.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),a.jsxs("p",{children:[a.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),a.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),De&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[De.success?a.jsx(gr,{className:"w-8 h-8 text-green-400"}):a.jsx(ha,{className:"w-8 h-8 text-red-400"}),a.jsx("h3",{className:"text-lg font-medium text-white",children:De.success?"Connection Successful":"Connection Failed"})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:De.success?De.message||"Successfully connected to Home Assistant.":De.error||"Failed to connect to Home Assistant."}),a.jsx("div",{className:"flex justify-end",children:a.jsx(Te,{variant:"primary",onClick:()=>nt(null),children:"OK"})})]})}),fe==="plugs"&&a.jsxs("div",{className:"max-w-4xl",children:[a.jsxs("div",{className:"flex items-start justify-between mb-6",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(dl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Connect smart plugs (Tasmota or Home Assistant) to automate power control and track energy usage for your printers."})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[ht&&ht.filter(oe=>oe.enabled).length>1&&a.jsxs(a.Fragment,{children:[a.jsxs(Te,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>be("on"),disabled:Ml.isPending,title:i("settings.turnAllPlugsOn"),children:[Ml.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(fd,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),a.jsxs(Te,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>be("off"),disabled:Ml.isPending,title:i("settings.turnAllPlugsOff"),children:[Ml.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(nk,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),a.jsxs(Te,{className:"whitespace-nowrap",onClick:()=>{L(null),P(!0)},children:[a.jsx(rr,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),ht&&ht.length>0&&a.jsxs(_t,{className:"mb-6",children:[a.jsx(An,{children:a.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[a.jsx(qh,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",$t&&a.jsx(it,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),a.jsx(Nt,{children:At?a.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(qh,{className:"w-3 h-3"}),"Current Power"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[At.totalPower.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[At.reachableCount,"/",At.totalPlugs," plugs online"]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(ai,{className:"w-3 h-3"}),"Today"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[At.totalToday.toFixed(2),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(At.totalToday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",ju(C?.currency||"USD")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(f3,{className:"w-3 h-3"}),"Yesterday"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[At.totalYesterday.toFixed(2),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(At.totalYesterday*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",ju(C?.currency||"USD")]})]}),a.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[a.jsx(o3,{className:"w-3 h-3"}),"Total"]}),a.jsxs("div",{className:"text-xl font-bold text-white",children:[At.totalLifetime.toFixed(1),a.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),(C?.energy_cost_per_kwh??0)>0&&a.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(At.totalLifetime*(C?.energy_cost_per_kwh??0)).toFixed(2)," ",ju(C?.currency||"USD")]})]})]}):$t?null:a.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),rt?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):ht&&ht.length>0?a.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:ht.map(oe=>a.jsx(LQe,{plug:oe,onEdit:kt=>{L(kt),P(!0)}},oe.id))}):a.jsx(_t,{children:a.jsx(Nt,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(dl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),a.jsxs(Te,{onClick:()=>{L(null),P(!0)},children:[a.jsx(rr,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),fe==="notifications"&&a.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Gg,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>ae(!0),children:[a.jsx(x0,{className:"w-4 h-4"}),i("settings.log")]}),Dt&&Dt.length>0&&a.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>{mm(null),fm.mutate()},disabled:fm.isPending,children:[fm.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(rk,{className:"w-4 h-4"}),i("settings.testAll")]}),a.jsxs(Te,{size:"sm",onClick:()=>{G(null),D(!0)},children:[a.jsx(rr,{className:"w-4 h-4"}),"Add"]})]})]}),a.jsx(_t,{className:"mb-4",children:a.jsx(Nt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),a.jsx("select",{value:C.notification_language||"en",onChange:oe=>xn("notification_language",oe.target.value),className:"px-2 py-1.5 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm focus:outline-none focus:ring-1 focus:ring-bambu-green",children:gB.map(oe=>a.jsx("option",{value:oe.code,children:oe.nativeName},oe.code))})]})})}),wd&&a.jsx(_t,{className:"mb-4",children:a.jsxs(Nt,{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),a.jsx("button",{onClick:()=>mm(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),a.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[a.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[a.jsx(gr,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:wd.success})]}),wd.failed>0&&a.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[a.jsx(ha,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:wd.failed})]})]}),wd.results.filter(oe=>!oe.success).length>0&&a.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:wd.results.filter(oe=>!oe.success).map(oe=>a.jsxs("div",{className:"text-xs text-red-400",children:[a.jsxs("span",{className:"font-medium",children:[oe.provider_name,":"]})," ",oe.message]},oe.provider_id))})]})}),Et?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Dt&&Dt.length>0?a.jsx("div",{className:"space-y-3",children:Dt.map(oe=>a.jsx(zQe,{provider:oe,onEdit:kt=>{G(kt),D(!0)}},oe.id))}):a.jsx(_t,{children:a.jsx(Nt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Gg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),a.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),a.jsxs(Te,{size:"sm",onClick:()=>{G(null),D(!0)},children:[a.jsx(rr,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[a.jsx(Ps,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:i("settings.messageTemplatesDescription")}),fn?a.jsx("div",{className:"flex justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Vt&&Vt.length>0?a.jsx("div",{className:"space-y-2",children:Vt.map(oe=>a.jsx(_t,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>K(oe),children:a.jsx(Nt,{className:"py-2.5 px-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("p",{className:"text-white font-medium text-sm truncate",children:oe.name}),a.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:oe.title_template})]}),a.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:kt=>{kt.stopPropagation(),K(oe)},children:a.jsx(sf,{className:"w-4 h-4 text-bambu-gray"})})]})})},oe.id))}):a.jsx(_t,{children:a.jsx(Nt,{className:"py-8",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(Ps,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),a.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),fe==="apikeys"&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(tl,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),a.jsxs(Te,{size:"sm",onClick:()=>J(!0),className:"flex-shrink-0",children:[a.jsx(rr,{className:"w-4 h-4"}),i("settings.createKey")]})]}),q&&a.jsx(_t,{className:"mb-6 border-bambu-green",children:a.jsx(Nt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx(gr,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),a.jsxs("div",{className:"flex-1",children:[a.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),a.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[a.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:q}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(q);else{const oe=document.createElement("textarea");oe.value=q,oe.style.position="fixed",oe.style.left="-999999px",document.body.appendChild(oe),oe.select(),document.execCommand("copy"),document.body.removeChild(oe)}o(i("settings.toast.keyCopied"))}catch{o(i("settings.toast.copyFailed"),"error")}},children:a.jsx(Kl,{className:"w-4 h-4"})})]}),a.jsxs("div",{className:"flex gap-2 mt-3",children:[a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>{Z(q),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>ie(null),children:i("common.dismiss")})]})]})]})})}),Ne&&a.jsxs(_t,{className:"mb-6",children:[a.jsx(An,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),a.jsx("input",{type:"text",value:Le,onChange:oe=>$(oe.target.value),placeholder:i("settings.keyNamePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:X.can_read_status,onChange:oe=>ce(kt=>({...kt,can_read_status:oe.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.readStatus")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:X.can_queue,onChange:oe=>ce(kt=>({...kt,can_queue:oe.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),a.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:X.can_control_printer,onChange:oe=>ce(kt=>({...kt,can_control_printer:oe.target.checked})),className:"w-4 h-4 text-bambu-green rounded border-bambu-dark-tertiary bg-bambu-dark focus:ring-bambu-green"}),a.jsxs("div",{children:[a.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]})]})]}),a.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[a.jsxs(Te,{onClick:()=>mn.mutate({name:Le||i("settings.unnamedKey"),...X}),disabled:mn.isPending,children:[mn.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(rr,{className:"w-4 h-4"}),i("settings.createKey")]}),a.jsx(Te,{variant:"secondary",onClick:()=>J(!1),children:i("common.cancel")})]})]})]}),Kt?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Jt&&Jt.length>0?a.jsx("div",{className:"space-y-3",children:Jt.map(oe=>a.jsx(_t,{children:a.jsx(Nt,{className:"py-3",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx(tl,{className:`w-5 h-5 ${oe.enabled?"text-bambu-green":"text-bambu-gray"}`}),a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium",children:oe.name}),a.jsxs("p",{className:"text-xs text-bambu-gray",children:[oe.key_prefix,"••••••••",oe.last_used&&` · ${i("settings.lastUsed")}: ${hb(oe.last_used)}`]})]})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsxs("div",{className:"flex gap-1 text-xs",children:[oe.can_read_status&&a.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),oe.can_queue&&a.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:i("queue.title")}),oe.can_control_printer&&a.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")})]}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>he(oe.id),children:a.jsx(en,{className:"w-4 h-4 text-red-400"})})]})]})})},oe.id))}):a.jsx(_t,{children:a.jsx(Nt,{className:"py-12",children:a.jsxs("div",{className:"text-center text-bambu-gray",children:[a.jsx(tl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),a.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),a.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),a.jsxs(Te,{onClick:()=>J(!0),children:[a.jsx(rr,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),a.jsxs(_t,{className:"mt-6",children:[a.jsx(An,{children:a.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.webhookEndpoints")})}),a.jsxs(Nt,{className:"space-y-3 text-sm",children:[a.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),a.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-blue-400",children:"GET"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-green-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-orange-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),a.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[a.jsx("span",{className:"text-red-400",children:"POST"})," ",a.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),a.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),a.jsxs("div",{children:[a.jsxs("div",{className:"mb-6",children:[a.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(Ph,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),a.jsx(_t,{className:"mb-4",children:a.jsxs(Nt,{className:"py-3",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),a.jsx("input",{type:"text",value:ge,onChange:oe=>Z(oe.target.value),placeholder:i("settings.apiKeyPlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white font-mono text-sm focus:border-bambu-green focus:outline-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),a.jsx(aZe,{apiKey:ge})]})]}),fe==="virtual-printer"&&a.jsx(ZQe,{}),fe==="filament"&&C&&a.jsx(a.Fragment,{children:a.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[a.jsxs("div",{className:"lg:w-1/3 space-y-6",children:[a.jsx(WQe,{}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),a.jsxs(Nt,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(AF,{className:"w-4 h-4 text-blue-400"}),a.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_good??40,onChange:oe=>xn("ams_humidity_good",parseInt(oe.target.value)||40),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"0",max:"100",value:C.ams_humidity_fair??60,onChange:oe=>xn("ams_humidity_fair",parseInt(oe.target.value)||60),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")})]}),a.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(ak,{className:"w-4 h-4 text-orange-400"}),a.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_good??28,onChange:oe=>xn("ams_temp_good",parseFloat(oe.target.value)||28),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:C.ams_temp_fair??35,onChange:oe=>xn("ams_temp_fair",parseFloat(oe.target.value)||35),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Ec,{className:"w-4 h-4 text-purple-400"}),a.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"number",min:"1",max:"365",value:C.ams_history_retention_days??30,onChange:oe=>xn("ams_history_retention_days",parseInt(oe.target.value)||30),className:"w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),a.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),a.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]}),a.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[a.jsxs("div",{className:"flex items-center gap-2 text-white",children:[a.jsx(Cr,{className:"w-4 h-4 text-bambu-green"}),a.jsx("span",{className:"font-medium",children:i("settings.printModal")})]}),a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-white",children:i("settings.expandCustomMapping")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.expandCustomMappingDescription")})]}),a.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:C.per_printer_mapping_expanded??!1,onChange:oe=>xn("per_printer_mapping_expanded",oe.target.checked),className:"sr-only peer"}),a.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})]})]})]})]}),a.jsxs("div",{className:"lg:w-2/3 space-y-6",children:[a.jsx(KQe,{}),a.jsx(XQe,{})]})]})}),te!==null&&a.jsx(Pn,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{Tn.mutate(te),he(null)},onCancel:()=>he(null)}),E&&a.jsx(OQe,{plug:U,onClose:()=>{P(!1),L(null)}}),B&&a.jsx(UQe,{provider:H,onClose:()=>{D(!1),G(null)}}),I&&a.jsx(BQe,{template:I,onClose:()=>K(null)}),Q&&a.jsx(VQe,{onClose:()=>ae(!1)}),z&&a.jsx(Pn,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{F(!1);try{const oe=await se.clearNotificationLogs(30);o(oe.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>F(!1)}),W&&a.jsx(Pn,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{me(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>me(!1)}),_e&&a.jsx(Pn,{title:`Turn All Plugs ${_e==="on"?"On":"Off"}`,message:`This will turn ${_e==="on"?"ON":"OFF"} all ${ht?.filter(oe=>oe.enabled).length||0} enabled smart plugs. ${_e==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${_e==="on"?"On":"Off"}`,variant:_e==="off"?"danger":"warning",onConfirm:()=>{const oe=_e;be(null),Ml.mutate(oe)},onCancel:()=>be(null)}),He&&_n?.release_notes&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>Se(!1),children:a.jsxs(_t,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:oe=>oe.stopPropagation(),children:[a.jsxs(An,{className:"flex flex-row items-center justify-between shrink-0",children:[a.jsxs("div",{children:[a.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",_n.latest_version]}),_n.release_name&&_n.release_name!==_n.latest_version&&a.jsx("p",{className:"text-sm text-bambu-gray",children:_n.release_name})]}),a.jsx("button",{onClick:()=>Se(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsx(Nt,{className:"overflow-y-auto flex-1",children:a.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:_n.release_notes})}),a.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[_n.release_url&&a.jsx("a",{href:_n.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:a.jsxs(Te,{variant:"secondary",className:"w-full",children:[a.jsx(Xr,{className:"w-4 h-4"}),"View on GitHub"]})}),a.jsx(Te,{onClick:()=>Se(!1),className:"flex-1",children:"Close"})]})]})}),fe==="users"&&a.jsxs("div",{className:"space-y-6",children:[a.jsxs("div",{className:"flex gap-1 border-b border-bambu-dark-tertiary",children:[a.jsxs("button",{onClick:()=>ue("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${Re==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(gh,{className:"w-4 h-4"}),i("settings.tabs.users")]}),a.jsxs("button",{onClick:()=>ue("email"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${Re==="email"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[a.jsx(y0,{className:"w-4 h-4"}),i("settings.tabs.emailAuth")||"Email Authentication",vt?.advanced_auth_enabled&&a.jsx("span",{className:"w-2 h-2 rounded-full bg-green-400"})]})]}),Re==="users"&&a.jsxs(a.Fragment,{children:[a.jsx(_t,{children:a.jsx(Nt,{className:"py-4",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("div",{className:`w-10 h-10 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?a.jsx(Vm,{className:"w-5 h-5 text-green-400"}):a.jsx(WS,{className:"w-5 h-5 text-gray-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&a.jsxs(Te,{variant:"secondary",onClick:()=>Qe(!0),children:[a.jsx(WS,{className:"w-4 h-4"}),i("common.disable")]}):a.jsxs(Te,{onClick:()=>e("/setup"),children:[a.jsx(Vm,{className:"w-4 h-4"}),i("common.enable")]})]})})}),vt?.advanced_auth_enabled&&a.jsx(_t,{className:"border-blue-500/30 bg-blue-500/5",children:a.jsx(Nt,{className:"py-4",children:a.jsxs("div",{className:"flex items-start gap-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full flex items-center justify-center bg-blue-500/20 flex-shrink-0",children:a.jsx(y0,{className:"w-5 h-5 text-blue-400"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-white font-medium",children:i("settings.email.advancedAuthEnabled")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.email.advancedAuthEnabledDesc")})]})]})})}),l&&a.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[a.jsxs("div",{className:"space-y-6",children:[c&&a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),a.jsxs(Te,{size:"sm",variant:"ghost",onClick:()=>we(!0),children:[a.jsx(tl,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),a.jsx(Nt,{children:a.jsx("div",{className:"flex items-center justify-between",children:a.jsxs("div",{children:[a.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),c.groups?.map(oe=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${oe.name==="Administrators"?"bg-purple-500/20 text-purple-300":oe.name==="Operators"?"bg-blue-500/20 text-blue-300":oe.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:oe.name},oe.id))]})]})})})]}),a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),Cn("users:create")&&a.jsxs(Te,{size:"sm",onClick:()=>{Ze(!0),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:[a.jsx(rr,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),a.jsx(Nt,{children:fr?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Zr.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Zr.map(oe=>a.jsxs("div",{className:"py-3 flex items-center justify-between",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsx("p",{className:"text-white font-medium truncate",children:oe.username}),a.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[oe.is_admin&&a.jsx("span",{className:"px-2 py-0.5 rounded-full text-xs font-medium bg-purple-500/20 text-purple-300",children:i("settings.admin")}),oe.groups?.map(kt=>a.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${kt.name==="Administrators"?"bg-purple-500/20 text-purple-300":kt.name==="Operators"?"bg-blue-500/20 text-blue-300":kt.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:kt.name},kt.id))]})]}),a.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[Cn("users:update")&&a.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>Cl(oe),children:a.jsx(sf,{className:"w-4 h-4"})}),Cn("users:delete")&&oe.id!==c?.id&&a.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>Nl(oe.id),children:a.jsx(en,{className:"w-4 h-4"})})]})]},oe.id))})})]})]}),a.jsx("div",{children:a.jsxs(_t,{children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[a.jsx(WT,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),Cn("groups:create")&&a.jsxs(Te,{size:"sm",onClick:()=>{tn(!0),wi()},children:[a.jsx(rr,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),a.jsx(Nt,{children:_a?a.jsx("div",{className:"flex items-center justify-center py-8",children:a.jsx(it,{className:"w-6 h-6 text-bambu-green animate-spin"})}):mi.length===0?a.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):a.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:mi.map(oe=>a.jsxs("div",{className:"py-3",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(WT,{className:`w-4 h-4 ${oe.name==="Administrators"?"text-purple-400":oe.name==="Operators"?"text-blue-400":oe.name==="Viewers"?"text-green-400":"text-bambu-gray"}`}),a.jsx("span",{className:"text-white font-medium",children:oe.name}),oe.is_system&&a.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),a.jsxs("div",{className:"flex items-center gap-1",children:[Cn("groups:update")&&a.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>_i(oe),children:a.jsx(sf,{className:"w-4 h-4"})}),Cn("groups:delete")&&!oe.is_system&&a.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>sr(oe.id),children:a.jsx(en,{className:"w-4 h-4"})})]})]}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:oe.description||i("settings.noDescription")}),a.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[a.jsx("span",{children:i("settings.userCount",{count:oe.user_count})}),a.jsx("span",{children:i("settings.permissionCount",{count:oe.permissions.length})})]})]},oe.id))})})]})})]}),!l&&a.jsx(_t,{children:a.jsx(Nt,{className:"py-6",children:a.jsxs("div",{className:"text-center",children:[a.jsx(WS,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),a.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(gr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature1")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(gr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature2")})]}),a.jsxs("li",{className:"flex items-start gap-2",children:[a.jsx(gr,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),a.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),a.jsxs(Te,{onClick:()=>e("/setup"),children:[a.jsx(Vm,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),Re==="email"&&a.jsx("div",{className:"max-w-2xl",children:a.jsx(tZe,{})})]}),Ae&&!vt?.advanced_auth_enabled&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Ze(!1),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(gh,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{Ze(!1),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Rt,{className:"w-5 h-5"})})]})}),a.jsxs(Nt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),a.jsx("input",{type:"text",value:Ie.username,onChange:oe=>gt({...Ie,username:oe.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),a.jsx("input",{type:"password",value:Ie.password,onChange:oe=>gt({...Ie,password:oe.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("settings.enterPassword"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:Ie.confirmPassword,onChange:oe=>gt({...Ie,confirmPassword:oe.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${Ie.confirmPassword&&Ie.password!==Ie.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),Ie.confirmPassword&&Ie.password!==Ie.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[mi.map(oe=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ie.group_ids.includes(oe.id),onChange:()=>Ba(oe.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:oe.name}),oe.is_system&&a.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},oe.id)),mi.length===0&&a.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:()=>{Ze(!1),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),a.jsx(Te,{onClick:Li,disabled:gn.isPending||!Ie.username||!Ie.password||Ie.password!==Ie.confirmPassword||Ie.password.length<6,children:gn.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):a.jsxs(a.Fragment,{children:[a.jsx(rr,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),Ae&&vt?.advanced_auth_enabled&&a.jsx(qQe,{formData:Ie,setFormData:gt,groups:mi,onClose:()=>{Ze(!1),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},onCreate:Li,isCreating:gn.isPending,isCreateButtonDisabled:gn.isPending||!Ie.username||!Ie.email}),Pe&&Fe!==null&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Xe(!1),Oe(null),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(sf,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{Xe(!1),Oe(null),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:a.jsx(Rt,{className:"w-5 h-5"})})]})}),a.jsxs(Nt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("settings.username")," ",vt?.advanced_auth_enabled&&a.jsx("span",{className:"text-red-400",children:"*"})]}),a.jsx("input",{type:"text",value:Ie.username,onChange:oe=>gt({...Ie,username:oe.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("settings.enterUsername"),autoComplete:"username"})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.email")||"Email"," ",vt?.advanced_auth_enabled?a.jsx("span",{className:"text-red-400",children:"*"}):a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.optional")||"optional",")"]})]}),a.jsx("input",{type:"email",value:Ie.email,onChange:oe=>gt({...Ie,email:oe.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("users.form.emailPlaceholder")||"user@example.com",required:vt?.advanced_auth_enabled})]}),!vt?.advanced_auth_enabled&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[i("users.form.password")||"Password"," ",a.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",i("users.form.leaveBlankToKeep")||"leave blank to keep current",")"]})]}),a.jsx("input",{type:"password",value:Ie.password,onChange:oe=>gt({...Ie,password:oe.target.value,confirmPassword:""}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("settings.enterNewPassword"),autoComplete:"new-password",minLength:6})]}),Ie.password&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),a.jsx("input",{type:"password",value:Ie.confirmPassword,onChange:oe=>gt({...Ie,confirmPassword:oe.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${Ie.confirmPassword&&Ie.password!==Ie.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Ie.confirmPassword&&Ie.password!==Ie.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),vt?.advanced_auth_enabled&&a.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-3",children:[a.jsx("p",{className:"text-sm text-bambu-gray",children:i("users.form.passwordManagedByAdvancedAuth")||'Password is managed by Advanced Authentication. Use "Reset Password" to send a new password to the user via email.'}),a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>Fe&&Ua.mutate(Fe),disabled:Ua.isPending||!Ie.email,className:"w-full",children:Ua.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),i("users.form.resettingPassword")||"Resetting Password..."]}):a.jsxs(a.Fragment,{children:[a.jsx(Do,{className:"w-4 h-4"}),i("users.form.resetPassword")||"Reset Password"]})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("users.form.groups")||"Groups"}),a.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:mi.map(oe=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Ie.group_ids.includes(oe.id),onChange:()=>Ba(oe.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),a.jsx("span",{className:"text-sm text-white",children:oe.name}),oe.is_system&&a.jsxs("span",{className:"text-xs text-yellow-400",children:["(",i("users.system")||"System",")"]})]},oe.id))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:()=>{Xe(!1),Oe(null),gt({username:"",password:"",email:"",confirmPassword:"",role:"user",group_ids:[]})},children:i("users.modal.cancel")||"Cancel"}),a.jsx(Te,{onClick:()=>Or(Fe),disabled:za.isPending||!Ie.username||vt?.advanced_auth_enabled&&!Ie.email||!!(!vt?.advanced_auth_enabled&&Ie.password&&(Ie.password!==Ie.confirmPassword||Ie.password.length<6)),children:za.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),i("users.modal.saving")||"Saving..."]}):a.jsxs(a.Fragment,{children:[a.jsx(xs,{className:"w-4 h-4"}),i("users.modal.saveChanges")||"Save Changes"]})})]})]})]})}),Me!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{Je(null),Mt(null)},children:a.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[a.jsx(en,{className:"w-5 h-5"}),a.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),a.jsx(Nt,{className:"space-y-4",children:an?a.jsx("div",{className:"flex items-center justify-center py-4",children:a.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):yt&&yt.archives+yt.queue_items+yt.library_files>0?a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),a.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[yt.archives>0&&a.jsxs("li",{children:[yt.archives," archive",yt.archives!==1?"s":""]}),yt.queue_items>0&&a.jsxs("li",{children:[yt.queue_items," queue item",yt.queue_items!==1?"s":""]}),yt.library_files>0&&a.jsxs("li",{children:[yt.library_files," library file",yt.library_files!==1?"s":""]})]}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),a.jsxs("div",{className:"flex flex-col gap-2",children:[a.jsx(Te,{variant:"danger",onClick:()=>Jr.mutate({id:Me,deleteItems:!0}),disabled:Jr.isPending,className:"justify-center",children:"Delete user AND their items"}),a.jsx(Te,{variant:"secondary",onClick:()=>Jr.mutate({id:Me,deleteItems:!1}),disabled:Jr.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),a.jsx(Te,{variant:"ghost",onClick:()=>{Je(null),Mt(null)},disabled:Jr.isPending,className:"justify-center",children:"Cancel"})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),a.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),a.jsxs("div",{className:"flex gap-2 justify-end",children:[a.jsx(Te,{variant:"ghost",onClick:()=>{Je(null),Mt(null)},disabled:Jr.isPending,children:"Cancel"}),a.jsx(Te,{variant:"danger",onClick:()=>Jr.mutate({id:Me,deleteItems:!1}),disabled:Jr.isPending,children:"Delete User"})]})]})})]})}),(Qt||un)&&a.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{tn(!1),hr(null),wi()},children:a.jsxs(_t,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:oe=>oe.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(WT,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:un?"Edit Group":"Create Group"})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{tn(!1),hr(null),wi()},children:a.jsx(Rt,{className:"w-5 h-5"})})]})}),a.jsxs(Nt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groupName")}),a.jsx("input",{type:"text",value:Xt.name,onChange:oe=>or({...Xt,name:oe.target.value}),disabled:un?.is_system,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors disabled:opacity-50",placeholder:i("settings.enterGroupName")}),un?.is_system&&a.jsx("p",{className:"text-xs text-yellow-400 mt-1",children:i("settings.systemGroupWarning")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Description"}),a.jsx("textarea",{value:Xt.description,onChange:oe=>or({...Xt,description:oe.target.value}),rows:2,className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors resize-none",placeholder:i("settings.enterDescriptionOptional")})]}),a.jsxs("div",{children:[a.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:["Permissions (",Xt.permissions.length," selected)"]}),a.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:Gt?.categories.map(oe=>a.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-bambu-dark-secondary cursor-pointer hover:bg-bambu-dark-tertiary transition-colors",onClick:()=>co(oe.name),children:[a.jsxs("div",{className:"flex items-center gap-3",children:[a.jsx("button",{type:"button",onClick:kt=>{kt.stopPropagation(),Yn(oe,!kl(oe))},className:`w-5 h-5 rounded border flex items-center justify-center transition-colors ${kl(oe)?"bg-bambu-green border-bambu-green":hm(oe)?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:(kl(oe)||hm(oe))&&a.jsx(Yr,{className:"w-3 h-3 text-white"})}),a.jsx("span",{className:"text-white font-medium",children:oe.name}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",oe.permissions.filter(kt=>Xt.permissions.includes(kt.value)).length,"/",oe.permissions.length,")"]})]}),yi.has(oe.name)?a.jsx(Jn,{className:"w-4 h-4 text-bambu-gray"}):a.jsx(Fa,{className:"w-4 h-4 text-bambu-gray"})]}),yi.has(oe.name)&&a.jsx("div",{className:"p-3 bg-bambu-dark space-y-2",children:oe.permissions.map(kt=>a.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:Xt.permissions.includes(kt.value),onChange:()=>vr(kt.value),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark-secondary"}),a.jsx("span",{className:"text-sm text-bambu-gray",children:kt.label})]},kt.value))})]},oe.name))})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:()=>{tn(!1),hr(null),wi()},children:"Cancel"}),a.jsx(Te,{onClick:un?Wr:ic,disabled:Sa.isPending||Vi.isPending||!Xt.name.trim(),children:Sa.isPending||Vi.isPending?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),un?"Saving...":"Creating..."]}):a.jsxs(a.Fragment,{children:[a.jsx(xs,{className:"w-4 h-4"}),un?"Save Changes":"Create Group"]})})]})]})]})}),yr!==null&&a.jsx(Pn,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{Gi.mutate(yr),sr(null)},onCancel:()=>sr(null)}),fe==="backup"&&a.jsx(eZe,{}),$e&&a.jsx(Pn,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await se.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await u(),Qe(!1),window.location.href="/"}catch(oe){const kt=oe instanceof Error?oe.message:i("settings.toast.authDisableFailed");o(kt,"error")}},onCancel:()=>Qe(!1)}),ye&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{we(!1),Ue({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[a.jsx(An,{children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(tl,{className:"w-5 h-5 text-bambu-green"}),a.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),a.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{we(!1),Ue({currentPassword:"",newPassword:"",confirmPassword:""})},children:a.jsx(Rt,{className:"w-5 h-5"})})]})}),a.jsxs(Nt,{children:[a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),a.jsx("input",{type:"password",value:Ce.currentPassword,onChange:oe=>Ue({...Ce,currentPassword:oe.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("settings.enterCurrentPassword"),autoComplete:"current-password"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),a.jsx("input",{type:"password",value:Ce.newPassword,onChange:oe=>Ue({...Ce,newPassword:oe.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:i("settings.enterNewPasswordMin6"),autoComplete:"new-password",minLength:6})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),a.jsx("input",{type:"password",value:Ce.confirmPassword,onChange:oe=>Ue({...Ce,confirmPassword:oe.target.value}),className:`w-full px-4 py-3 bg-bambu-dark-secondary border rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors ${Ce.confirmPassword&&Ce.newPassword!==Ce.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Ce.confirmPassword&&Ce.newPassword!==Ce.confirmPassword&&a.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),a.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:()=>{we(!1),Ue({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),a.jsx(Te,{onClick:async()=>{if(Ce.newPassword!==Ce.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ce.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}Ve(!0);try{await se.changePassword(Ce.currentPassword,Ce.newPassword),o(i("settings.toast.passwordChanged"),"success"),we(!1),Ue({currentPassword:"",newPassword:"",confirmPassword:""})}catch(oe){const kt=oe instanceof Error?oe.message:"Failed to change password";o(kt,"error")}finally{Ve(!1)}},disabled:je||!Ce.currentPassword||!Ce.newPassword||Ce.newPassword!==Ce.confirmPassword||Ce.newPassword.length<6,children:je?a.jsxs(a.Fragment,{children:[a.jsx(it,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(tl,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const Dae=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},lZe=t=>t.startsWith("HH")?"HF":"S",cZe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},Rae=t=>{const e=["High Flow_","High Flow ","Standard_","Standard ","HF_","HF ","S_","S "];for(const r of e)if(t.startsWith(r))return t.slice(r.length);const n=t.indexOf("_");return n>0?t.slice(n+1):t};function Rj({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:s,note:o}){const l=lZe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&s?s():e()};return a.jsxs("div",{className:"flex items-center gap-2",children:[r&&a.jsx("button",{onClick:s,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?a.jsx(ao,{className:"w-4 h-4 text-bambu-green"}):a.jsx(gl,{className:"w-4 h-4"})}),a.jsxs("button",{onClick:u,className:`flex-1 text-left px-3 py-2 bg-bambu-dark rounded hover:bg-bambu-dark-tertiary transition-colors ${i?"ring-1 ring-bambu-green":""}`,children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:Dae(t.k_value)}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&a.jsx("span",{title:"Has note",children:a.jsx(uX,{className:"w-3 h-3 text-yellow-500"})}),a.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&a.jsxs("div",{className:"text-xs mt-0.5 truncate text-yellow-500/70",title:o,children:["Note: ",o.length>50?o.substring(0,50)+"...":o]})]}),!r&&n&&a.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:a.jsx(Kl,{className:"w-4 h-4"})})]})}function Fj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],builtinFilaments:i=[],isDualNozzle:s=!1,initialNote:o="",initialNoteKey:l=null,onClose:c,onSave:u,onSaveNote:d,hasPermission:h}){const{t:f}=Ut(),{showToast:p}=hn(),[x,v]=w.useState(t?.name||""),[b,y]=w.useState(t?.k_value?Dae(t.k_value):"0.020"),[S,N]=w.useState(t?.filament_id||""),[M,k]=w.useState(t?.nozzle_id?cZe(t.nozzle_id):"HH00"),[T,C]=w.useState(t?.nozzle_diameter||n),[j,E]=w.useState(t?[t.extruder_id]:s?[0,1]:[0]),[P,U]=w.useState(!1),[L,B]=w.useState({current:0,total:0}),[D,H]=w.useState(o),G=zr.useMemo(()=>{const ne=new Map;for(const ve of i)ne.set(ve.filament_id,ve.name);const ee=new Map;for(const ve of r)if(ve.filament_id&&!ee.has(ve.filament_id)){const de=ne.get(ve.filament_id)||Rae(ve.name||"");ee.set(ve.filament_id,{id:ve.filament_id,name:de||ve.filament_id})}return Array.from(ee.values()).sort((ve,fe)=>ve.name.localeCompare(fe.name))},[r,i]),I=ot({mutationFn:ne=>(console.log("[KProfile] Calling API..."),se.setKProfile(e,ne)),onSuccess:ne=>{if(console.log("[KProfile] Save success:",ne),p(f("kProfiles.toast.profileSaved")),d&&D!==o){let ee;D===""&&l?ee=l:t&&t.slot_id>0?ee=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:ee=`name_${x}_${S}`,d(ee,D)}U(!0),setTimeout(()=>{U(!1),u()},2500)},onError:ne=>{console.error("[KProfile] Save error:",ne),p(ne.message,"error"),U(!1)}}),K=ot({mutationFn:ne=>(console.log("[KProfile] Deleting profile..."),se.deleteKProfile(e,ne)),onSuccess:ne=>{console.log("[KProfile] Delete success:",ne),p(f("kProfiles.toast.profileDeleted")),U(!0),setTimeout(()=>{U(!1),c()},4e3)},onError:ne=>{console.error("[KProfile] Delete error:",ne),p(ne.message,"error"),U(!1)}}),[Q,ae]=w.useState(!1),V=()=>{t&&K.mutate({slot_id:t.slot_id,extruder_id:t.extruder_id,nozzle_id:t.nozzle_id,nozzle_diameter:t.nozzle_diameter,filament_id:t.filament_id,setting_id:t.setting_id})},Y=async ne=>{if(ne.preventDefault(),s&&!t&&j.length===0){p(f("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const ee=parseFloat(b).toFixed(6),ve=`${M}-${T}`;if(t||j.length===1){const de={name:x,k_value:ee,filament_id:S,nozzle_id:ve,nozzle_diameter:T,extruder_id:t?t.extruder_id:j[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",de),I.mutate(de);return}U(!0),B({current:1,total:j.length});const fe=j.map(de=>({name:x,k_value:ee,filament_id:S,nozzle_id:ve,nozzle_diameter:T,extruder_id:de,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${fe.length} profiles in batch:`,fe);try{if(await se.setKProfilesBatch(e,fe),p(f("kProfiles.toast.profilesSaved",{count:j.length})),d&&D){const de=`name_${x}_${S}`;d(de,D)}}catch(de){console.error("[KProfile] Failed to save batch:",de),p(f("kProfiles.toast.failedToSaveBatch"),"error"),U(!1),B({current:0,total:0});return}B({current:j.length,total:j.length}),setTimeout(()=>{U(!1),B({current:0,total:0}),u()},3e3)};return a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[a.jsxs(_t,{className:"w-full max-w-md relative",children:[P&&a.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:L.total>1?f("kProfiles.modal.savingExtruder",{current:L.current,total:L.total}):f("kProfiles.modal.syncing")}),a.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:f("kProfiles.modal.pleaseWait")})]}),a.jsxs(Nt,{className:"p-0",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[a.jsx("h2",{className:"text-xl font-semibold text-white",children:f(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),a.jsx("button",{onClick:c,className:"text-bambu-gray hover:text-white transition-colors",disabled:P,children:a.jsx(Rt,{className:"w-5 h-5"})})]}),a.jsxs("form",{onSubmit:Y,className:"p-4 space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.profileName")}),a.jsx("input",{type:"text",value:x,onChange:ne=>v(ne.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:f("kProfiles.modal.profileNamePlaceholder"),required:!t})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.kValue")}),a.jsx("input",{type:"text",inputMode:"decimal",value:b,onChange:ne=>{const ee=ne.target.value;(ee===""||/^\d*\.?\d*$/.test(ee))&&y(ee)},onBlur:ne=>{const ee=parseFloat(ne.target.value);isNaN(ee)||y((Math.trunc(ee*1e3)/1e3).toFixed(3))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none font-mono",placeholder:f("kProfiles.modal.kValuePlaceholder"),required:!0}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.kValueHelp")})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.filament")}),a.jsxs("select",{value:S,onChange:ne=>{const ee=ne.target.value;if(N(ee),!t&&ee&&!x){const ve=G.find(fe=>fe.id===ee);ve&&v(`${M==="HH00"?"HF":"S"} ${ve.name}`)}},disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,required:!t,children:[a.jsx("option",{value:"",children:f("kProfiles.modal.selectFilament")}),t?.filament_id&&a.jsx("option",{value:t.filament_id,children:G.find(ne=>ne.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&G.map(ne=>a.jsx("option",{value:ne.id,children:ne.name},ne.id))]}),!t&&G.length===0&&a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.noFilamentsHelp")})]}),a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.flowType")}),a.jsxs("select",{value:M,onChange:ne=>{const ee=ne.target.value;if(k(ee),!t&&S&&!x){const ve=G.find(fe=>fe.id===S);ve&&v(`${ee==="HS00"?"HF":"S"} ${ve.name}`)}},disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"HH00",children:f("kProfiles.modal.highFlow")}),a.jsx("option",{value:"HS00",children:f("kProfiles.modal.standard")})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.nozzleSize")}),a.jsxs("select",{value:T,onChange:ne=>C(ne.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),s&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?a.jsx("div",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white opacity-60",children:t.extruder_id===1?f("kProfiles.modal.left"):f("kProfiles.modal.right")}):a.jsxs("div",{className:"flex gap-4",children:[a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:j.includes(1),onChange:ne=>{ne.target.checked?E([...j,1]):E(j.filter(ee=>ee!==1))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:f("kProfiles.modal.left")})]}),a.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[a.jsx("input",{type:"checkbox",checked:j.includes(0),onChange:ne=>{ne.target.checked?E([...j,0]):E(j.filter(ee=>ee!==0))},className:"w-4 h-4 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0 accent-bambu-green"}),a.jsx("span",{className:"text-white",children:f("kProfiles.modal.right")})]})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.notes")}),a.jsx("textarea",{value:D,onChange:ne=>H(ne.target.value),placeholder:f("kProfiles.modal.notesPlaceholder"),rows:2,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none resize-none"}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.notesHelp")})]}),a.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&a.jsx(Te,{type:"button",variant:"secondary",onClick:()=>ae(!0),disabled:K.isPending||P||!h("kprofiles:delete"),title:h("kprofiles:delete")?void 0:f("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:K.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"})}),a.jsx(Te,{type:"button",variant:"secondary",onClick:c,disabled:P,className:"flex-1",children:f("common.cancel")}),a.jsxs(Te,{type:"submit",disabled:I.isPending||P||!h(t?"kprofiles:update":"kprofiles:create"),title:h(t?"kprofiles:update":"kprofiles:create")?void 0:f(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[I.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(ZC,{className:"w-4 h-4"}),f("common.save")]})]})]})]})]}),Q&&a.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:a.jsx(_t,{className:"w-full max-w-sm",children:a.jsxs(Nt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(en,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:f("kProfiles.deleteConfirm.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:f("kProfiles.deleteConfirm.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:f("kProfiles.deleteConfirm.message",{name:t?.name})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:()=>ae(!1),className:"flex-1",children:f("common.cancel")}),a.jsxs(Te,{onClick:()=>{ae(!1),V()},disabled:K.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[K.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),f("common.delete")]})]})]})})})]})}const VS={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function uZe(){const{t}=Ut(),{showToast:e}=hn(),{hasPermission:n}=Fr(),[r,i]=w.useState(null),[s,o]=w.useState(()=>localStorage.getItem(VS.NOZZLE_DIAMETER)||"0.4"),[l,c]=w.useState(null),[u,d]=w.useState(!1),[h,f]=w.useState(null),[p,x]=w.useState(""),[v,b]=w.useState("all"),[y,S]=w.useState("all"),[N,M]=w.useState(()=>localStorage.getItem(VS.SORT_OPTION)||"name"),[k,T]=w.useState(!1),[C,j]=w.useState(new Set),[E,P]=w.useState(!1),[U,L]=w.useState(!1),B=w.useCallback(F=>`${F.slot_id}_${F.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(VS.NOZZLE_DIAMETER,s)},[s]),w.useEffect(()=>{localStorage.setItem(VS.SORT_OPTION,N)},[N]);const{data:D,isLoading:H}=et({queryKey:["printers"],queryFn:se.getPrinters}),{data:G,isLoading:I,isFetching:K,error:Q,refetch:ae}=et({queryKey:["kprofiles",r,s],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",s);const F=await se.getKProfiles(r,s);return console.log("[KProfiles] Received profiles:",F?.profiles?.length||0,"profiles"),F},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:V}=et({queryKey:["kprofiles",r,"0.4"],queryFn:()=>se.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:Y}=et({queryKey:["builtinFilaments"],queryFn:()=>se.getBuiltinFilaments(),staleTime:3e5}),{data:ne}=et({queryKey:["filamentIdMap"],queryFn:()=>se.getFilamentIdMap(),staleTime:3e5}),{data:ee,refetch:ve}=et({queryKey:["kprofile-notes",r],queryFn:()=>se.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),fe=Q?.message?.includes("not connected");w.useEffect(()=>{if(!r&&D&&D.length>0){const F=D.find(W=>W.is_active);F&&i(F.id)}},[r,D]),w.useEffect(()=>{if(r){const F=setTimeout(()=>{ae()},150);return()=>clearTimeout(F)}},[r,s]);const de=D?.filter(F=>F.is_active)||[],Re=zr.useMemo(()=>{const F=new Map;if(Y)for(const W of Y)F.set(W.filament_id,W.name);if(ne)for(const[W,me]of Object.entries(ne))F.has(W)||F.set(W,me);return F},[Y,ne]),ue=zr.useMemo(()=>Array.from(Re.entries()).map(([F,W])=>({filament_id:F,name:W})),[Re]),le=zr.useCallback(F=>Re.get(F.filament_id)||Rae(F.name),[Re]),Ne=zr.useMemo(()=>G?.profiles?G.profiles.filter(W=>{const me=p.toLowerCase(),_e=!me||W.name.toLowerCase().includes(me)||W.filament_id.toLowerCase().includes(me),be=v==="all"||v==="left"&&W.extruder_id===1||v==="right"&&W.extruder_id===0,He=y==="all"||y==="hf"&&W.nozzle_id.startsWith("HH")||y==="s"&&W.nozzle_id.startsWith("HS");return _e&&be&&He}).sort((W,me)=>{switch(N){case"k_value":return parseFloat(W.k_value)-parseFloat(me.k_value);case"filament":return le(W).localeCompare(le(me));default:return W.name.localeCompare(me.name)}}):[],[G?.profiles,p,v,y,N,le]),J=D?.find(F=>F.id===r),Le=J?.nozzle_count===2;w.useEffect(()=>{const F=W=>{W.target instanceof HTMLInputElement||W.target instanceof HTMLTextAreaElement||W.target instanceof HTMLSelectElement||l||u||h||(W.key==="r"||W.key==="R"?(W.preventDefault(),ae()):W.key==="n"||W.key==="N"?(W.preventDefault(),d(!0)):W.key==="Escape"&&k&&(W.preventDefault(),T(!1),j(new Set)))};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[l,u,h,k,ae]);const $=w.useCallback(()=>{if(!G?.profiles||G.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const F={version:1,exported_at:new Date().toISOString(),printer:J?.name||"Unknown",nozzle_diameter:s,profiles:G.profiles.map(be=>({name:be.name,k_value:be.k_value,filament_id:be.filament_id,nozzle_id:be.nozzle_id,nozzle_diameter:be.nozzle_diameter,extruder_id:be.extruder_id}))},W=new Blob([JSON.stringify(F,null,2)],{type:"application/json"}),me=URL.createObjectURL(W),_e=document.createElement("a");_e.href=me,_e.download=`kprofiles_${J?.name||"printer"}_${s}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(_e),_e.click(),document.body.removeChild(_e),URL.revokeObjectURL(me),e(t("kProfiles.toast.exportedProfiles",{count:G.profiles.length}))},[G?.profiles,J,s,e,t]),X=w.useCallback(()=>{const F=document.createElement("input");F.type="file",F.accept=".json",F.onchange=async W=>{const me=W.target.files?.[0];if(me)try{const _e=await me.text(),be=JSON.parse(_e);if(!be.profiles||!Array.isArray(be.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let He=0;for(const Se of be.profiles)if(!(!Se.name||!Se.k_value||!Se.filament_id))try{await se.setKProfile(r,{name:Se.name,k_value:parseFloat(Se.k_value).toFixed(6),filament_id:Se.filament_id,nozzle_id:Se.nozzle_id||`HH00-${s}`,nozzle_diameter:Se.nozzle_diameter||s,extruder_id:Se.extruder_id??0,slot_id:0}),He++,await new Promise($e=>setTimeout($e,500))}catch($e){console.error("Failed to import profile:",Se.name,$e)}e(t("kProfiles.toast.importedProfiles",{count:He,total:be.profiles.length})),ae()}catch(_e){console.error("Import error:",_e),e(t("kProfiles.toast.failedToParseImport"),"error")}},F.click()},[r,s,e,ae,t]),ce=w.useCallback(F=>{j(W=>{const me=new Set(W);return me.has(F)?me.delete(F):me.add(F),me})},[]),q=w.useCallback(()=>{j(new Set(Ne.map(F=>B(F))))},[Ne,B]),ie=w.useCallback(()=>{C.size!==0&&P(!0)},[C.size]),te=w.useCallback(async()=>{const F=Ne.filter(me=>C.has(B(me)));L(!0);let W=0;for(const me of F)try{await se.deleteKProfile(r,{slot_id:me.slot_id,extruder_id:me.extruder_id,nozzle_id:me.nozzle_id,nozzle_diameter:me.nozzle_diameter,filament_id:me.filament_id,setting_id:me.setting_id}),W++,await new Promise(_e=>setTimeout(_e,300))}catch(_e){console.error("Failed to delete profile:",me.name,_e)}e(t("kProfiles.toast.profilesDeleted",{count:W})),L(!1),P(!1),T(!1),j(new Set),ae()},[r,C,Ne,e,ae,B,t]),he=w.useCallback(F=>{const W=[];return F.setting_id&&W.push(F.setting_id),W.push(`slot_${F.slot_id}_${F.filament_id}_${F.extruder_id}`),W.push(`name_${F.name}_${F.filament_id}`),W},[]),ge=w.useCallback(async(F,W)=>{if(r)try{await se.setKProfileNote(r,F,W),ve()}catch(me){console.error("Failed to save note:",me),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,ve,e,t]),Z=w.useCallback(F=>{if(!ee?.notes)return{note:"",key:null};const W=he(F);for(const me of W)if(ee.notes[me])return{note:ee.notes[me],key:me};return{note:"",key:null}},[ee,he]),z=w.useCallback(F=>Z(F).note,[Z]);return H?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!D||D.length===0?a.jsx(_t,{children:a.jsxs(Nt,{className:"py-12 text-center",children:[a.jsx(Bi,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):de.length===0?a.jsx(_t,{children:a.jsxs(Nt,{className:"py-12 text-center",children:[a.jsx(Cr,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):a.jsxs(a.Fragment,{children:[K&&!I&&a.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[a.jsx(it,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),a.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[a.jsxs("div",{className:"flex-1 min-w-48",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),a.jsx("select",{value:r||"",onChange:F=>i(parseInt(F.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:de.map(F=>a.jsx("option",{value:F.id,children:F.name},F.id))})]}),a.jsxs("div",{className:"w-32",children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),a.jsxs("select",{value:s,onChange:F=>o(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"0.2",children:"0.2mm"}),a.jsx("option",{value:"0.4",children:"0.4mm"}),a.jsx("option",{value:"0.6",children:"0.6mm"}),a.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),a.jsxs("div",{className:"flex items-end gap-2",children:[a.jsxs(Te,{variant:"secondary",onClick:()=>ae(),disabled:K||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[a.jsx(Ur,{className:`w-4 h-4 ${K?"animate-spin":""}`}),t("kProfiles.refresh")]}),a.jsxs(Te,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[a.jsx(rr,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),a.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[a.jsxs("div",{className:"flex-1 min-w-48 relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:p,onChange:F=>x(F.target.value),placeholder:t("kProfiles.searchPlaceholder"),className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),Le&&a.jsx("div",{className:"w-36",children:a.jsxs("select",{value:v,onChange:F=>b(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),a.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),a.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:y,onChange:F=>S(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),a.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),a.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),a.jsx("div",{className:"w-32",children:a.jsxs("select",{value:N,onChange:F=>M(F.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"name",children:t("kProfiles.sortName")}),a.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),a.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),a.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[a.jsxs(Te,{variant:"secondary",onClick:$,disabled:!G?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[a.jsx(ui,{className:"w-4 h-4"}),t("kProfiles.export")]}),a.jsxs(Te,{variant:"secondary",onClick:X,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[a.jsx(sa,{className:"w-4 h-4"}),t("kProfiles.import")]}),a.jsx("div",{className:"flex-1"}),k?a.jsxs(a.Fragment,{children:[a.jsxs(Te,{variant:"secondary",onClick:q,children:[a.jsx(ao,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),a.jsxs(Te,{variant:"secondary",onClick:ie,disabled:C.size===0||!n("kprofiles:delete"),className:"text-red-500 hover:bg-red-500/10",title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(en,{className:"w-4 h-4"}),t("kProfiles.delete")," (",C.size,")"]}),a.jsxs(Te,{variant:"secondary",onClick:()=>{T(!1),j(new Set)},children:[a.jsx(Rt,{className:"w-4 h-4"}),t("common.cancel")]})]}):a.jsxs(Te,{variant:"secondary",onClick:()=>T(!0),disabled:!Ne.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[a.jsx(ao,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),I?a.jsx("div",{className:"flex justify-center py-12",children:a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):fe?a.jsx(_t,{children:a.jsxs(Nt,{className:"py-12 text-center",children:[a.jsx(Ff,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),a.jsxs(Te,{variant:"secondary",onClick:()=>ae(),children:[a.jsx(Ur,{className:"w-4 h-4"}),t("common.refresh")]})]})}):Ne.length>0?Le?a.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),a.jsx("div",{className:"space-y-1",children:Ne.filter(F=>F.extruder_id===1).map(F=>a.jsx(Rj,{profile:F,onEdit:()=>c(F),onCopy:()=>f(F),selectionMode:k,isSelected:C.has(B(F)),onToggleSelect:()=>ce(B(F)),note:z(F)},B(F)))})]}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),a.jsx("div",{className:"space-y-1",children:Ne.filter(F=>F.extruder_id===0).map(F=>a.jsx(Rj,{profile:F,onEdit:()=>c(F),onCopy:()=>f(F),selectionMode:k,isSelected:C.has(B(F)),onToggleSelect:()=>ce(B(F)),note:z(F)},B(F)))})]})]}):a.jsx("div",{className:"space-y-1",children:Ne.map(F=>a.jsx(Rj,{profile:F,onEdit:()=>c(F),onCopy:()=>f(F),selectionMode:k,isSelected:C.has(B(F)),onToggleSelect:()=>ce(B(F)),note:z(F)},B(F)))}):p||v!=="all"||y!=="all"?a.jsx(_t,{children:a.jsxs(Nt,{className:"py-12 text-center",children:[a.jsx(Br,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),a.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):a.jsx(_t,{children:a.jsxs(Nt,{className:"py-12 text-center",children:[a.jsx(ZC,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),a.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),a.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:s})}),a.jsxs(Te,{onClick:()=>d(!0),children:[a.jsx(rr,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:F,key:W}=Z(l);return a.jsx(Fj,{profile:l,printerId:r,nozzleDiameter:s,existingProfiles:V?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Le,initialNote:F,initialNoteKey:W,onSaveNote:ge,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),ae()},onSave:()=>{c(null),ae()}})})(),u&&r&&a.jsx(Fj,{printerId:r,nozzleDiameter:s,existingProfiles:V?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Le,onSaveNote:ge,hasPermission:n,onClose:()=>{d(!1),ae()},onSave:()=>{d(!1),ae()}}),h&&r&&a.jsx(Fj,{printerId:r,nozzleDiameter:s,existingProfiles:V?.profiles||G?.profiles,builtinFilaments:ue,isDualNozzle:Le,onSaveNote:ge,hasPermission:n,profile:{...h,slot_id:0,name:`${h.name} (Copy)`},onClose:()=>{f(null),ae()},onSave:()=>{f(null),ae()}}),E&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx(_t,{className:"w-full max-w-sm",children:a.jsxs(Nt,{className:"p-6",children:[a.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:a.jsx(en,{className:"w-5 h-5 text-red-500"})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),a.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),a.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:C.size})}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx(Te,{variant:"secondary",onClick:()=>P(!1),disabled:U,className:"flex-1",children:t("common.cancel")}),a.jsxs(Te,{onClick:te,disabled:U,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[U?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}const Fae=["PLA","PETG","ABS","ASA","TPU","PC","PA","PVA","HIPS","PP","PET","NYLON"],dZe={PLA:"E8E8E8",PETG:"4A90D9",ABS:"E67E22",ASA:"D35400",TPU:"9B59B6",PC:"BDC3C7",PA:"2ECC71",NYLON:"2ECC71",PVA:"F1C40F",HIPS:"95A5A6",PP:"ECF0F1",PET:"3498DB"};function hZe(t){const e=t.toUpperCase();for(const n of Fae)if(new RegExp(`\\b${n}\\b`).test(e))return n;return null}function mZe(t){const e=t.replace(/@.+$/,"").trim(),n=e.toUpperCase();for(const r of Fae){const i=n.indexOf(r);if(i>0){const s=e.slice(0,i).trim();if(s&&s.length>1)return s}}return null}function Lj({preset:t,onDelete:e,onExpand:n,isExpanded:r}){const{t:i}=Ut(),{hasPermission:s}=Fr(),o=t.filament_type||hZe(t.name),l=t.filament_vendor||mZe(t.name);let c=null,u=!1;if(t.default_filament_colour)try{const d=JSON.parse(t.default_filament_colour),h=Array.isArray(d)?d[0]:d;typeof h=="string"&&/^#?[0-9a-fA-F]{6,8}$/.test(h.replace("#",""))&&(c=h.replace("#","").slice(0,6),u=!0)}catch{const d=t.default_filament_colour;/^#?[0-9a-fA-F]{6,8}$/.test(d.replace("#",""))&&(c=d.replace("#","").slice(0,6),u=!0)}return!c&&o&&(c=dZe[o.toUpperCase()]||null),a.jsx(_t,{className:"bg-bambu-dark border-bambu-dark-tertiary hover:border-bambu-dark-tertiary/80 transition-colors",children:a.jsxs(Nt,{className:"p-3",children:[a.jsxs("div",{className:"flex items-start justify-between gap-2",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.preset_type==="filament"&&a.jsx("div",{className:`w-4 h-4 rounded-full border border-white/20 flex-shrink-0 ${!u&&!c?"opacity-25":u?"":"opacity-50"}`,style:{backgroundColor:c?`#${c}`:"#666"}}),a.jsx("span",{className:"text-sm font-medium text-white truncate",children:t.name})]}),a.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o&&a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:o}),l&&a.jsx("span",{className:"text-xs text-bambu-gray",children:l}),a.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-blue-500/20 text-blue-400",children:i("profiles.localProfiles.badge")})]})]}),a.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s("settings:update")&&a.jsx("button",{onClick:()=>e(t.id),className:"p-1 text-bambu-gray hover:text-red-400 transition-colors",title:i("profiles.localProfiles.delete"),children:a.jsx(en,{className:"w-3.5 h-3.5"})}),a.jsx("button",{onClick:()=>n(r?null:t.id),className:"p-1 text-bambu-gray hover:text-white transition-colors",children:r?a.jsx(Wl,{className:"w-3.5 h-3.5"}):a.jsx(Jn,{className:"w-3.5 h-3.5"})})]})]}),r&&a.jsxs("div",{className:"mt-3 pt-3 border-t border-bambu-dark-tertiary text-xs space-y-1.5",children:[o&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.filamentType")}),a.jsx("span",{className:"text-white",children:o})]}),l&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.vendor")}),a.jsx("span",{className:"text-white",children:l})]}),t.nozzle_temp_min!=null&&t.nozzle_temp_max!=null&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.nozzleTemp")}),a.jsxs("span",{className:"text-white",children:[t.nozzle_temp_min,"–",t.nozzle_temp_max,"°C"]})]}),t.filament_cost&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.cost")}),a.jsx("span",{className:"text-white",children:t.filament_cost})]}),t.filament_density&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.density")}),a.jsxs("span",{className:"text-white",children:[t.filament_density," g/cm³"]})]}),t.pressure_advance&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.pressureAdvance")}),a.jsx("span",{className:"text-white",children:t.pressure_advance})]}),t.compatible_printers&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.compatiblePrinters")}),a.jsx("span",{className:"text-white truncate ml-2",children:(()=>{try{return JSON.parse(t.compatible_printers).join(", ")}catch{return t.compatible_printers}})()})]}),t.inherits&&t.inherits!==t.name&&a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.inheritsFrom")}),a.jsx("span",{className:"text-white truncate ml-2",children:t.inherits})]}),a.jsxs("div",{className:"flex justify-between",children:[a.jsx("span",{className:"text-bambu-gray",children:i("profiles.localProfiles.source")}),a.jsx("span",{className:"text-white capitalize",children:t.source})]})]})]})})}function fZe(){const{t}=Ut(),{hasPermission:e}=Fr(),n=Zt(),{showToast:r}=hn(),[i,s]=w.useState(""),[o,l]=w.useState(null),[c,u]=w.useState(!1),[d,h]=w.useState(null),{data:f,isLoading:p}=et({queryKey:["localPresets"],queryFn:()=>se.getLocalPresets()}),x=ot({mutationFn:async C=>{const j=[];for(const E of Array.from(C)){const P=new FormData;P.append("file",E),j.push(await se.importLocalPresets(P))}return j},onSuccess:C=>{n.invalidateQueries({queryKey:["localPresets"]});let j=0,E=0,P=0;for(const U of C)j+=U.imported,E+=U.skipped,P+=U.errors.length;j>0&&r(t("profiles.localProfiles.toast.importSuccess",{count:j})),E>0&&r(t("profiles.localProfiles.toast.importSkipped",{count:E}),"warning"),P>0&&r(t("profiles.localProfiles.toast.importError",{count:P}),"error")},onError:C=>{r(C.message,"error")}}),v=ot({mutationFn:C=>se.deleteLocalPreset(C),onSuccess:()=>{n.invalidateQueries({queryKey:["localPresets"]}),h(null),r(t("profiles.localProfiles.toast.deleted"))}}),b=w.useCallback(C=>{!C||C.length===0||x.mutate(C)},[x]),y=w.useCallback(C=>{C.preventDefault(),u(!1),b(C.dataTransfer.files)},[b]),S=w.useCallback(C=>{if(!i)return C;const j=i.toLowerCase();return C.filter(E=>E.name.toLowerCase().includes(j)||E.filament_type?.toLowerCase().includes(j)||E.filament_vendor?.toLowerCase().includes(j))},[i]),N=w.useMemo(()=>S(f?.filament||[]),[f?.filament,S]),M=w.useMemo(()=>S(f?.printer||[]),[f?.printer,S]),k=w.useMemo(()=>S(f?.process||[]),[f?.process,S]),T=N.length+M.length+k.length;return p?a.jsx("div",{className:"flex items-center justify-center py-16",children:a.jsx(it,{className:"w-8 h-8 text-bambu-green animate-spin"})}):a.jsxs("div",{className:"space-y-6",children:[e("settings:update")&&a.jsxs("div",{onDragOver:C=>{C.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:y,className:`relative border-2 border-dashed rounded-lg p-6 text-center transition-colors ${c?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[a.jsx("input",{type:"file",accept:".json,.zip,.orca_filament,.bbscfg,.bbsflmt",multiple:!0,className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",onChange:C=>b(C.target.files)}),x.isPending?a.jsxs("div",{className:"flex items-center justify-center gap-2",children:[a.jsx(it,{className:"w-5 h-5 text-bambu-green animate-spin"}),a.jsx("span",{className:"text-bambu-gray",children:t("profiles.localProfiles.importing")})]}):a.jsxs(a.Fragment,{children:[a.jsx(sa,{className:"w-8 h-8 text-bambu-gray mx-auto mb-2"}),a.jsx("p",{className:"text-sm text-white font-medium",children:t("profiles.localProfiles.import")}),a.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("profiles.localProfiles.importDesc")})]})]}),T>0&&a.jsxs("div",{className:"relative",children:[a.jsx(Br,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),a.jsx("input",{type:"text",value:i,onChange:C=>s(C.target.value),placeholder:t("profiles.localProfiles.search"),className:"w-full pl-9 pr-4 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white placeholder-bambu-gray focus:outline-none focus:border-bambu-green"})]}),T===0&&!p&&a.jsxs("div",{className:"text-center py-12",children:[a.jsx($b,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3 opacity-50"}),a.jsx("p",{className:"text-bambu-gray",children:t("profiles.localProfiles.noPresets")}),a.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:t("profiles.localProfiles.importDesc")})]}),T>0&&a.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[N.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(XC,{className:"w-4 h-4 text-bambu-green"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.filament")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",N.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:N.map(C=>a.jsx(Lj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),k.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(is,{className:"w-4 h-4 text-blue-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.process")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",k.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:k.map(C=>a.jsx(Lj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]}),M.length>0&&a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(nd,{className:"w-4 h-4 text-orange-400"}),a.jsx("h3",{className:"text-sm font-medium text-white",children:t("profiles.localProfiles.printer")}),a.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",M.length,")"]})]}),a.jsx("div",{className:"space-y-2",children:M.map(C=>a.jsx(Lj,{preset:C,onDelete:j=>h(j),onExpand:l,isExpanded:o===C.id},C.id))})]})]}),d!==null&&a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:a.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg p-6 max-w-sm mx-4",children:[a.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[a.jsx(Bi,{className:"w-5 h-5 text-red-400"}),a.jsx("h3",{className:"text-white font-medium",children:t("profiles.localProfiles.deleteConfirmTitle")})]}),a.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("profiles.localProfiles.deleteConfirm")}),a.jsxs("div",{className:"flex justify-end gap-2",children:[a.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>h(null),children:t("profiles.localProfiles.cancel")}),a.jsxs(Te,{variant:"danger",size:"sm",onClick:()=>v.mutate(d),disabled:v.isPending,children:[v.isPending?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(en,{className:"w-4 h-4"}),t("profiles.localProfiles.delete")]})]})]})})]})}function hI(t,e){const n=`${t} ${e||""}`,r=n.match(/@?\s*(?:BBL\s+)?(?:Bambu\s+Lab\s+)?([XPAH][1-9][A-Z]?(?:\s*(?:Carbon|mini))?|H2D)/i),i=r?r[1].trim():null,s=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=s?(s[1]||s[2])+"mm":null,l=n.match(/(\d+\.?\d*)mm\s*(?:Standard|Fine|Extra Fine|Draft|Quality)?/i),c=l?l[1]+"mm":null,u=n.match(/\b(PLA|PETG|ABS|ASA|TPU|PC|PA|PVA|HIPS|PP|PET(?:-?CF)?|PA(?:-?CF)?|PLA(?:-?CF)?)\b/i),d=u?u[1].toUpperCase():null;return{printer:i,nozzle:o,layerHeight:c,filamentType:d}}function ov(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function pZe(t,e){const n=Ji(t);if(!n)return"";const i=new Date().getTime()-n.getTime(),s=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return s<1?e("profiles.time.justNow"):s<60?e("profiles.time.minsAgo",{count:s}):o<24?e("profiles.time.hoursAgo",{count:o}):l<7?e("profiles.time.daysAgo",{count:l}):n.toLocaleDateString()}function gZe({onSuccess:t,t:e}){const{showToast:n}=hn(),[r,i]=w.useState("email"),[s,o]=w.useState(""),[l,c]=w.useState(""),[u,d]=w.useState(""),[h,f]=w.useState(""),[p,x]=w.useState("global"),[v,b]=w.useState(null),[y,S]=w.useState(null),N=ot({mutationFn:()=>se.cloudLogin(s,l,p),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):j.needs_verification?(b(j.verification_type||"email"),S(j.tfa_key||null),j.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),i("code")):n(j.message,"error")},onError:j=>n(j.message,"error")}),M=ot({mutationFn:()=>se.cloudVerify(s,u,y||void 0),onSuccess:j=>{j.success?(n(e("profiles.login.toast.loggedIn")),t()):n(j.message,"error")},onError:j=>n(j.message,"error")}),k=ot({mutationFn:()=>se.cloudSetToken(h),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:j=>n(j.message,"error")}),T=j=>{j.preventDefault(),r==="email"?N.mutate():r==="code"?M.mutate():r==="token"&&k.mutate()},C=N.isPending||M.isPending||k.isPending;return a.jsx(_t,{className:"max-w-md mx-auto",children:a.jsxs(Nt,{children:[a.jsxs("div",{className:"text-center mb-6",children:[a.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:a.jsx(Hb,{className:"w-6 h-6 text-bambu-green"})}),a.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),a.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),a.jsxs("form",{onSubmit:T,className:"space-y-4",children:[r==="email"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),a.jsx("input",{type:"email",value:s,onChange:j=>o(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"your@email.com",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),a.jsx("input",{type:"password",value:l,onChange:j=>c(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"••••••••",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),a.jsxs("select",{value:p,onChange:j=>x(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[a.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),a.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(v==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:v==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:s})}),a.jsx("input",{type:"text",value:u,onChange:j=>d(j.target.value.replace(/\D/g,"").slice(0,6)),className:"w-full px-3 py-3 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-center text-2xl tracking-widest font-mono focus:border-bambu-green focus:outline-none",placeholder:"000000",maxLength:6,required:!0})]}),r==="token"&&a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),a.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),a.jsx("textarea",{value:h,onChange:j=>f(j.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-xs font-mono placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none resize-none",placeholder:"eyJ...",rows:4,required:!0})]}),a.jsxs("div",{className:"flex gap-2",children:[r==="code"&&a.jsx(Te,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),a.jsxs(Te,{type:"submit",disabled:C,className:"flex-1",children:[C?a.jsx(it,{className:"w-4 h-4 animate-spin"}):a.jsx(LB,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(tl,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&a.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:a.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[a.jsx(LB,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function Tg({label:t,value:e,options:n,onChange:r}){const[i,s]=w.useState(!1),o=n.find(l=>l.value===e);return a.jsxs("div",{className:"relative",children:[a.jsxs("button",{onClick:()=>s(!i),className:"flex items-center gap-2 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-sm text-white hover:border-bambu-gray-dark transition-colors",children:[a.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),a.jsx("span",{children:o?.label||"All"}),a.jsx(Jn,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>s(!1)}),a.jsx("div",{className:"absolute top-full left-0 mt-1 min-w-[160px] bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 py-1 max-h-60 overflow-y-auto",children:n.map(l=>a.jsxs("button",{onClick:()=>{r(l.value),s(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center justify-between hover:bg-bambu-dark-tertiary transition-colors ${e===l.value?"text-bambu-green":"text-white"}`,children:[a.jsx("span",{children:l.label}),l.count!==void 0&&a.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function bZe(){const[t,e]=w.useState(!1);w.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?a.jsx("button",{onClick:n,className:"fixed bottom-6 right-6 p-3 bg-bambu-green hover:bg-bambu-green-light text-white rounded-full shadow-lg shadow-bambu-green/25 transition-all z-40","aria-label":"Scroll to top",children:a.jsx(jf,{className:"w-5 h-5"})}):null}function Oj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:s,compareDisabled:o,t:l}){const c=hI(t.name),u=ov(t.setting_id);return a.jsxs("div",{className:"flex items-center gap-2 group",children:[a.jsx("button",{onClick:e,disabled:o,className:`flex-1 text-left px-3 py-2 rounded transition-colors ${i?"bg-blue-500/20 border border-blue-500/50":o?"bg-bambu-dark/50 opacity-40 cursor-not-allowed":"bg-bambu-dark hover:bg-bambu-dark-tertiary"} ${r&&!o?"cursor-pointer":""}`,children:a.jsxs("div",{className:"flex items-center gap-2",children:[i&&s!==void 0&&a.jsx("span",{className:"flex-shrink-0 w-5 h-5 rounded-full bg-blue-500 text-white text-xs flex items-center justify-center font-medium",children:s+1}),!i&&u&&a.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),a.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&a.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),a.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:l("profiles.presets.duplicate"),children:a.jsx(Kl,{className:"w-4 h-4"})})]})}function oF(t,e=0){const n=" ".repeat(e);if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){if(t.includes("\\n")||t.includes(` `)){const i=t.replace(/\\n/g,` `).replace(/\\"/g,'"').replace(/\\t/g," ").split(` diff --git a/static/index.html b/static/index.html index c1b219461..e26d0a739 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +