From 11456c0d2aabe35f52a9ae0d9d5b3f905ea74e19 Mon Sep 17 00:00:00 2001 From: maziggy Date: Tue, 3 Feb 2026 07:29:38 +0100 Subject: [PATCH] Fix monthly comparison calculation ignoring quantity multiplier (Issue #229) The filament statistics were under-reporting totals because the quantity field was not being multiplied with filament_used_grams. When users printed multiple items (quantity > 1), only the base filament amount was counted instead of the total. Closes #229 --- CHANGELOG.md | 7 +++++ backend/app/api/routes/archives.py | 5 +++- backend/app/api/routes/metrics.py | 6 ++-- frontend/src/components/FilamentTrends.tsx | 28 +++++++++++-------- .../{index-BXCvE4aN.js => index-POsspFOS.js} | 2 +- static/index.html | 2 +- 6 files changed, 33 insertions(+), 17 deletions(-) rename static/assets/{index-BXCvE4aN.js => index-POsspFOS.js} (91%) diff --git a/CHANGELOG.md b/CHANGELOG.md index c78d30451..8b9338bb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,13 @@ All notable changes to Bambuddy will be documented in this file. - Added locale parity test to ensure English and German stay in sync ### Fixed +- **Monthly Comparison Calculation Off** (Issue #229): + - Fixed filament statistics not accounting for quantity multiplier + - Monthly comparison chart now correctly multiplies `filament_used_grams` by `quantity` + - Daily and weekly charts also now account for quantity + - Filament type breakdown includes quantity in calculations + - Backend stats endpoint (`/archives/stats`) and Prometheus metrics also fixed + - Prints count now shows total items (sum of quantities) instead of archive count - **Authentication Required for Downloads** (Issue #231): - Fixed support bundle download returning 401 Unauthorized when auth is enabled - Fixed archive export (CSV/XLSX) failing with authentication enabled diff --git a/backend/app/api/routes/archives.py b/backend/app/api/routes/archives.py index 4d34a0508..e2e73c844 100644 --- a/backend/app/api/routes/archives.py +++ b/backend/app/api/routes/archives.py @@ -451,7 +451,10 @@ async def get_archive_stats(db: AsyncSession = Depends(get_db)): total_seconds += print_time_seconds total_time = total_seconds / 3600 # Convert to hours - filament_result = await db.execute(select(func.sum(PrintArchive.filament_used_grams))) + # Multiply filament by quantity to account for multiple items printed + filament_result = await db.execute( + select(func.sum(PrintArchive.filament_used_grams * func.coalesce(PrintArchive.quantity, 1))) + ) total_filament = filament_result.scalar() or 0 cost_result = await db.execute(select(func.sum(PrintArchive.cost))) diff --git a/backend/app/api/routes/metrics.py b/backend/app/api/routes/metrics.py index 57002d93a..757f531dc 100644 --- a/backend/app/api/routes/metrics.py +++ b/backend/app/api/routes/metrics.py @@ -362,11 +362,13 @@ async def get_metrics( ) lines.append(f"bambuddy_printer_prints_total{labels} {count}") - # Total filament used + # Total filament used (multiply by quantity to account for multiple items printed) lines.append("") lines.append("# HELP bambuddy_filament_used_grams Total filament used in grams") lines.append("# TYPE bambuddy_filament_used_grams counter") - result = await db.execute(select(func.coalesce(func.sum(PrintArchive.filament_used_grams), 0))) + result = await db.execute( + select(func.coalesce(func.sum(PrintArchive.filament_used_grams * func.coalesce(PrintArchive.quantity, 1)), 0)) + ) total_filament = result.scalar() or 0 lines.append(f"bambuddy_filament_used_grams {total_filament:.1f}") diff --git a/frontend/src/components/FilamentTrends.tsx b/frontend/src/components/FilamentTrends.tsx index e20d38597..594ef61c7 100644 --- a/frontend/src/components/FilamentTrends.tsx +++ b/frontend/src/components/FilamentTrends.tsx @@ -61,9 +61,10 @@ export function FilamentTrends({ archives, currency = '$' }: FilamentTrendsProps const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; const existing = dataMap.get(key) || { date: key, filament: 0, cost: 0, prints: 0 }; - existing.filament += archive.filament_used_grams || 0; + const qty = archive.quantity || 1; + existing.filament += (archive.filament_used_grams || 0) * qty; existing.cost += archive.cost || 0; - existing.prints += 1; + existing.prints += qty; dataMap.set(key, existing); }); @@ -89,9 +90,10 @@ export function FilamentTrends({ archives, currency = '$' }: FilamentTrendsProps const key = `${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, '0')}-${String(weekStart.getDate()).padStart(2, '0')}`; const existing = dataMap.get(key) || { week: key, filament: 0, cost: 0, prints: 0 }; - existing.filament += archive.filament_used_grams || 0; + const qty = archive.quantity || 1; + existing.filament += (archive.filament_used_grams || 0) * qty; existing.cost += archive.cost || 0; - existing.prints += 1; + existing.prints += qty; dataMap.set(key, existing); }); @@ -110,10 +112,11 @@ export function FilamentTrends({ archives, currency = '$' }: FilamentTrendsProps filteredArchives.forEach(archive => { const type = archive.filament_type || 'Unknown'; + const qty = archive.quantity || 1; // Handle multiple types (e.g., "PLA, PETG") const types = type.split(', '); types.forEach(t => { - const grams = (archive.filament_used_grams || 0) / types.length; + const grams = ((archive.filament_used_grams || 0) * qty) / types.length; dataMap.set(t, (dataMap.get(t) || 0) + grams); }); }); @@ -140,9 +143,9 @@ export function FilamentTrends({ archives, currency = '$' }: FilamentTrendsProps months.push({ month: monthStr, - filament: Math.round(monthArchives.reduce((sum, a) => sum + (a.filament_used_grams || 0), 0)), + filament: Math.round(monthArchives.reduce((sum, a) => sum + (a.filament_used_grams || 0) * (a.quantity || 1), 0)), cost: monthArchives.reduce((sum, a) => sum + (a.cost || 0), 0), - prints: monthArchives.length, + prints: monthArchives.reduce((sum, a) => sum + (a.quantity || 1), 0), }); } @@ -150,8 +153,9 @@ export function FilamentTrends({ archives, currency = '$' }: FilamentTrendsProps }, [archives]); const chartData = timeRange === '7d' || timeRange === '30d' ? dailyData : weeklyData; - const totalFilament = filteredArchives.reduce((sum, a) => sum + (a.filament_used_grams || 0), 0); + const totalFilament = filteredArchives.reduce((sum, a) => sum + (a.filament_used_grams || 0) * (a.quantity || 1), 0); const totalCost = filteredArchives.reduce((sum, a) => sum + (a.cost || 0), 0); + const totalPrints = filteredArchives.reduce((sum, a) => sum + (a.quantity || 1), 0); return (
@@ -185,17 +189,17 @@ export function FilamentTrends({ archives, currency = '$' }: FilamentTrendsProps

Period Cost

{currency}{totalCost.toFixed(2)}

-

{filteredArchives.length} prints

+

{totalPrints} prints

Avg per Print

- {filteredArchives.length > 0 - ? (totalFilament / filteredArchives.length).toFixed(0) + {totalPrints > 0 + ? (totalFilament / totalPrints).toFixed(0) : 0}g

- {currency}{filteredArchives.length > 0 ? (totalCost / filteredArchives.length).toFixed(2) : '0.00'} avg + {currency}{totalPrints > 0 ? (totalCost / totalPrints).toFixed(2) : '0.00'} avg

diff --git a/static/assets/index-BXCvE4aN.js b/static/assets/index-POsspFOS.js similarity index 91% rename from static/assets/index-BXCvE4aN.js rename to static/assets/index-POsspFOS.js index 49704dca7..24b6a8a71 100644 --- a/static/assets/index-BXCvE4aN.js +++ b/static/assets/index-POsspFOS.js @@ -8648,7 +8648,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${t0(t. transition-all duration-200 hover:border-bambu-dark-tertiary/80 ${T?"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:s.jsxs("div",{className:"flex items-center gap-4 p-4",children:[E&&d&&s.jsx("button",{onClick:A=>{A.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&&s.jsx(Ia,{className:"w-4 h-4"})}),E?s.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:s.jsx(zg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}):e!==void 0?s.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]}):s.jsx("div",{className:"w-8"}),s.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?s.jsx("img",{src:t.plate_id!=null?ue.getArchivePlateThumbnail(t.archive_id,t.plate_id):ue.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?s.jsx("img",{src:t.plate_id!=null?ue.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ue.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s.jsx(sl,{className:"w-6 h-6"})})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.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?s.jsx(Ds,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:m("queue.viewArchive"),children:s.jsx(Kr,{className:"w-3.5 h-3.5"})}):t.library_file_id?s.jsx(Ds,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:m("queue.viewInFileManager"),children:s.jsx(Kr,{className:"w-3.5 h-3.5"})}):null]}),s.jsxs("div",{className:"flex items-center gap-3 text-sm text-bambu-gray",children:[s.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:[s.jsx(Ur,{className:"w-3.5 h-3.5"}),t.target_model?`${m("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?m("queue.filter.unassigned"):t.printer_name||`${m("common.printer")} #${t.printer_id}`]}),t.print_time_seconds&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xu,{className:"w-3.5 h-3.5"}),Rre(t.print_time_seconds)]}),t.created_by_username&&s.jsxs("span",{className:"flex items-center gap-1.5",title:m("queue.addedBy",{name:t.created_by_username}),children:[s.jsx(am,{className:"w-3.5 h-3.5"}),t.created_by_username]}),E&&!t.manual_start&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(er,{className:"w-3.5 h-3.5"}),UWe(t.scheduled_time,c,m)]})]}),s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.manual_start&&s.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:[s.jsx(bW,{className:"w-3 h-3"}),m("queue.badges.staged")]}),t.require_previous_success&&s.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:m("queue.badges.requiresPrevious")}),t.auto_off_after&&s.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:[s.jsx(Gu,{className:"w-3 h-3"}),m("queue.badges.autoPowerOff")]})]}),C&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-gradient-to-r from-blue-500 to-blue-400 animate-pulse w-full opacity-50"})}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:m("queue.printingInProgress")})]}),t.waiting_reason&&t.status==="pending"&&s.jsxs("p",{className:"text-xs text-purple-400 mt-2 flex items-start gap-1",children:[s.jsx(Hi,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),s.jsx("span",{children:t.waiting_reason})]}),t.error_message&&s.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[s.jsx(Hi,{className:"w-3 h-3"}),t.error_message]})]}),s.jsx(zWe,{status:t.status,waitingReason:t.waiting_reason,t:m}),s.jsxs("div",{className:"flex items-center gap-1",children:[C&&s.jsx(Te,{variant:"ghost",size:"sm",onClick:a,disabled:!f("printers:control"),title:f("printers:control")?m("queue.actions.stopPrint"):m("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Xce,{className:"w-4 h-4"})}),E&&s.jsxs(s.Fragment,{children:[t.manual_start&&s.jsx(Te,{variant:"ghost",size:"sm",onClick:l,disabled:!f("printers:control"),title:f("printers:control")?m("queue.actions.startPrint"):m("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:s.jsx(Is,{className:"w-4 h-4"})}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?m("common.edit"):m("queue.permissions.noEdit"),children:s.jsx(Qi,{className:"w-4 h-4"})}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?m("common.cancel"):m("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Rt,{className:"w-4 h-4"})})]}),D&&s.jsxs(s.Fragment,{children:[s.jsx(Te,{variant:"ghost",size:"sm",onClick:o,disabled:!f("queue:create"),title:f("queue:create")?m("queue.actions.requeue"):m("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:s.jsx(Dr,{className:"w-4 h-4"})}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?m("common.remove"):m("queue.permissions.noRemove"),children:s.jsx(rn,{className:"w-4 h-4"})})]})]})]})})}function HWe(){const{t}=Hn(),e=an(),{showToast:n}=$n(),{hasPermission:r,hasAnyPermission:i,canModify:a}=Ai(),[o,l]=_.useState(null),[c,u]=_.useState(""),[d,f]=_.useState(""),[p,m]=_.useState(!1),[x,b]=_.useState(null),[y,v]=_.useState(null),[S,N]=_.useState(null),[T,k]=_.useState([]),[C,E]=_.useState(!1),[D,A]=_.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[R,U]=_.useState(()=>{const I=localStorage.getItem("queue.historySortAsc");return I!==null?I==="true":!1}),[F,$]=_.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[j,H]=_.useState(()=>{const I=localStorage.getItem("queue.pendingSortAsc");return I!==null?I==="true":!0});_.useEffect(()=>{localStorage.setItem("queue.historySortBy",D)},[D]),_.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(R))},[R]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",F)},[F]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(j))},[j]);const K=cre(ZM(B2,{activationConstraint:{distance:8}}),ZM(z2,{coordinateGetter:Pre})),{data:V}=at({queryKey:["settings"],queryFn:ue.getSettings}),Q=V?.time_format||"system",{data:Z,isLoading:ae}=at({queryKey:["queue",o,c],queryFn:()=>ue.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:B}=at({queryKey:["printers"],queryFn:()=>ue.getPrinters()}),X=mt({mutationFn:I=>ue.cancelQueueItem(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),ne=mt({mutationFn:I=>ue.removeFromQueue(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),se=mt({mutationFn:I=>ue.stopQueueItem(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),be=mt({mutationFn:I=>ue.startQueueItem(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),xe=mt({mutationFn:I=>ue.reorderQueue(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),de=mt({mutationFn:async()=>{const I=Z?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];for(const fe of I)await ue.removeFromQueue(fe.id);return I.length},onSuccess:I=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:I}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),Pe=mt({mutationFn:I=>ue.bulkUpdateQueue(I),onSuccess:I=>{e.invalidateQueries({queryKey:["queue"]}),k([]),E(!1),n(I.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),ie=mt({mutationFn:async I=>{for(const fe of I)await ue.cancelQueueItem(fe);return I.length},onSuccess:I=>{e.invalidateQueries({queryKey:["queue"]}),k([]),n(t("queue.toast.bulkCancelled",{count:I}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),Ne=I=>{k(fe=>fe.includes(I)?fe.filter(me=>me!==I):[...fe,I])},Oe=_.useMemo(()=>{const I=new Set;return B?.forEach(fe=>{fe.location&&I.add(fe.location)}),Z?.forEach(fe=>{fe.target_location&&I.add(fe.target_location)}),Array.from(I).sort()},[B,Z]),ge=_.useCallback(I=>d?I.target_location?I.target_location===d:I.printer_id?B?.find(me=>me.id===I.printer_id)?.location===d:!1:!0,[d,B]),Ke=_.useMemo(()=>{let I=Z?.filter(me=>me.status==="pending")||[];d&&(I=I.filter(ge));const fe=me=>{if(!me.scheduled_time)return 0;const Ee=new Date(me.scheduled_time).getTime(),z=Date.now()+4320*60*60*1e3;return Ee>z?0:Ee};return[...I].sort((me,Ee)=>{let z;if(F==="name"){const O=me.archive_name||me.library_file_name||"",ee=Ee.archive_name||Ee.library_file_name||"";z=O.localeCompare(ee)}else F==="printer"?z=(me.printer_name||"").localeCompare(Ee.printer_name||""):F==="time"?z=fe(me)-fe(Ee):z=me.position-Ee.position;return j?z:-z})},[Z,F,j,ge,d]),G=()=>{const I=Ke.map(fe=>fe.id);T.length===I.length?k([]):k(I)},Y=_.useMemo(()=>{let I=Z?.filter(fe=>fe.status==="printing")||[];return d&&(I=I.filter(ge)),I},[Z,d,ge]),ce=_.useMemo(()=>{let I=Z?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];return d&&(I=I.filter(ge)),[...I].sort((fe,me)=>{let Ee;if(D==="name"){const z=fe.archive_name||fe.library_file_name||"",O=me.archive_name||me.library_file_name||"";Ee=z.localeCompare(O)}else D==="printer"?Ee=(fe.printer_name||"").localeCompare(me.printer_name||""):Ee=new Date(me.completed_at||me.created_at).getTime()-new Date(fe.completed_at||fe.created_at).getTime();return R?-Ee:Ee})},[Z,D,R,ge,d]),q=_.useMemo(()=>Ke.reduce((I,fe)=>I+(fe.print_time_seconds||0),0),[Ke]),te=I=>{const{active:fe,over:me}=I;if(!me||fe.id===me.id)return;const Ee=Ke.findIndex(O=>O.id===fe.id),z=Ke.findIndex(O=>O.id===me.id);if(Ee!==-1&&z!==-1){const ee=V2(Ke,Ee,z).map((le,_e)=>({id:le.id,position:_e+1}));xe.mutate(ee)}};return s.jsxs("div",{className:"p-4 md:p-8",children:[s.jsx("div",{className:"flex items-center justify-between mb-8",children:s.jsxs("div",{children:[s.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[s.jsx(yW,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),s.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[s.jsx(_t,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:s.jsx(Is,{className:"w-5 h-5 text-blue-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Y.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.printing")})]})]})})}),s.jsx(_t,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center",children:s.jsx(er,{className:"w-5 h-5 text-yellow-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Ke.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.queued")})]})]})})}),s.jsx(_t,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center",children:s.jsx(xu,{className:"w-5 h-5 text-bambu-green"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Rre(q)}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.totalTime")})]})]})})}),s.jsx(_t,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-500/20 flex items-center justify-center",children:s.jsx(Ar,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:ce.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.history")})]})]})})})]}),s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.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:I=>{const fe=I.target.value;l(fe==="unassigned"?-1:fe===""?null:Number(fe))},children:[s.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),s.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),B?.map(I=>s.jsx("option",{value:I.id,children:I.name},I.id))]}),s.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:I=>u(I.target.value),children:[s.jsx("option",{value:"",children:t("queue.filter.allStatus")}),s.jsx("option",{value:"pending",children:t("queue.status.pending")}),s.jsx("option",{value:"printing",children:t("queue.status.printing")}),s.jsx("option",{value:"completed",children:t("queue.status.completed")}),s.jsx("option",{value:"failed",children:t("queue.status.failed")}),s.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),s.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Oe.length>0&&s.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:I=>f(I.target.value),children:[s.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Oe.map(I=>s.jsx("option",{value:I,children:I},I))]}),s.jsx("div",{className:"flex-1"}),ce.length>0&&s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>m(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[s.jsx(rn,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),ae?s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Z?.length===0?s.jsxs(_t,{className:"p-12 text-center border-dashed",children:[s.jsx(si,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),s.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),s.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):s.jsxs("div",{className:"space-y-8",children:[Y.length>0&&s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white mb-4 flex items-center gap-2",children:[s.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),s.jsx("div",{className:"space-y-3",children:Y.map(I=>s.jsx(Hj,{item:I,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:I}),onRequeue:()=>{},onStart:()=>{},timeFormat:Q,hasPermission:r,canModify:a,t},I.id))})]}),Ke.length>0&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(er,{className:"w-5 h-5 text-yellow-400"}),t("queue.sections.queued"),s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:Ke.length}),")"]}),s.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.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:F,onChange:I=>$(I.target.value),children:[s.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),s.jsx("option",{value:"name",children:t("queue.sort.byName")}),s.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),s.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>H(!j),title:t(j?"common.ascending":"common.descending"),className:"px-2",children:j?s.jsx(Ig,{className:"w-4 h-4"}):s.jsx(G0,{className:"w-4 h-4"})})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-bambu-dark rounded-lg",children:[s.jsxs(Te,{variant:"ghost",size:"sm",onClick:G,className:"flex items-center gap-2",children:[T.length===Ke.length&&Ke.length>0?s.jsx(ol,{className:"w-4 h-4 text-bambu-green"}):s.jsx(ll,{className:"w-4 h-4"}),T.length===Ke.length&&Ke.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),T.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:T.length})}),s.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),s.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>E(!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:[s.jsx(Qi,{className:"w-4 h-4"}),t("queue.bulkEdit.editSelected")]}),s.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>ie.mutate(T),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:ie.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?void 0:t("queue.permissions.noCancelItems"),children:[s.jsx(Rt,{className:"w-4 h-4"}),t("queue.bulkEdit.cancelSelected")]})]})]}),s.jsx(kre,{sensors:K,collisionDetection:fre,onDragEnd:te,children:s.jsx(Are,{items:Ke.map(I=>I.id),strategy:TWe,children:s.jsx("div",{className:"space-y-3",children:Ke.map((I,fe)=>s.jsx(Hj,{item:I,position:fe+1,onEdit:()=>b(I),onCancel:()=>N({type:"cancel",item:I}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>be.mutate(I.id),timeFormat:Q,isSelected:T.includes(I.id),onToggleSelect:()=>Ne(I.id),hasPermission:r,canModify:a,t},I.id))})})})]}),ce.length>0&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Ar,{className:"w-5 h-5 text-bambu-gray"}),t("queue.sections.history"),s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:ce.length}),")"]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.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:D,onChange:I=>A(I.target.value),children:[s.jsx("option",{value:"date",children:t("queue.sort.byDate")}),s.jsx("option",{value:"name",children:t("queue.sort.byName")}),s.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>U(!R),title:t(R?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:R?s.jsx(Ig,{className:"w-4 h-4"}):s.jsx(G0,{className:"w-4 h-4"})})]})]}),s.jsx("div",{className:"space-y-3",children:ce.slice(0,20).map((I,fe)=>s.jsx(Hj,{item:I,position:fe+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:I}),onStop:()=>{},onRequeue:()=>v(I),onStart:()=>{},timeFormat:Q,hasPermission:r,canModify:a,t},I.id))})]})]}),x&&s.jsx(jh,{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:()=>b(null)}),y&&s.jsx(jh,{mode:"add-to-queue",archiveId:y.archive_id??void 0,libraryFileId:y.library_file_id??void 0,archiveName:y.archive_name||y.library_file_name||`File #${y.archive_id||y.library_file_id}`,onClose:()=>v(null)}),S&&s.jsx(Zn,{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"?X.mutate(S.item.id):S.type==="stop"?se.mutate(S.item.id):ne.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),p&&s.jsx(Zn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:ce.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{de.mutate(),m(!1)},onCancel:()=>m(!1)}),C&&s.jsx(BWe,{selectedCount:T.length,printers:B?.map(I=>({id:I.id,name:I.name}))||[],onSave:I=>{Object.keys(I).length>0&&Pe.mutate({item_ids:T,...I})},onClose:()=>E(!1),isSaving:Pe.isPending,t})]})}function $We({printDates:t,months:e=3}){const n=_.useRef(null),[r,i]=_.useState(0);_.useEffect(()=>{const S=n.current;if(!S)return;const N=new ResizeObserver(T=>{const k=T[0]?.contentRect.width||0;i(k)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:a,monthLabels:o,printCounts:l}=_.useMemo(()=>{const S={};t.forEach(U=>{const F=U.split("T")[0];S[F]=(S[F]||0)+1});const N=new Date,T=new Date(N);T.setMonth(T.getMonth()-e),T.setDate(T.getDate()-T.getDay());const k=[],C=[];let E=[],D=-1;const A=new Date(T);let R=0;for(;A<=N;)A.getDay()===0&&E.length>0&&(k.push(E),E=[],R++),A.getMonth()!==D&&(C.push({month:A.toLocaleDateString("en-US",{month:"short"}),weekIndex:R}),D=A.getMonth()),E.push(new Date(A)),A.setDate(A.getDate()+1);return E.length>0&&k.push(E),{weeks:k,monthLabels:C,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"],f=a.length,p=32,m=2,x=r-p-16,b=f>0?Math.floor((x-(f-1)*m)/f):12,y=Math.max(8,Math.min(20,b)),v=y<=10?10:12;return s.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&s.jsxs("div",{children:[s.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:S,weekIndex:N},T)=>s.jsx("div",{className:"text-bambu-gray",style:{fontSize:v,marginLeft:T===0?0:`${(N-(o[T-1]?.weekIndex||0))*(y+m)-24}px`},children:S},T))}),s.jsxs("div",{className:"flex",style:{gap:m},children:[s.jsx("div",{className:"flex flex-col",style:{gap:m,marginRight:4,width:p},children:d.map((S,N)=>s.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:y,fontSize:v,visibility:N%2===1?"visible":"hidden"},children:S},S))}),a.map((S,N)=>s.jsx("div",{className:"flex flex-col",style:{gap:m},children:[0,1,2,3,4,5,6].map(T=>{const k=S.find(A=>A.getDay()===T);if(!k)return s.jsx("div",{style:{width:y,height:y}},T);const C=k.toISOString().split("T")[0],E=l[C]||0,D=C===new Date().toISOString().split("T")[0];return s.jsx("div",{className:`rounded-sm ${u(E)} ${D?"ring-1 ring-white":""}`,style:{width:y,height:y},title:`${k.toLocaleDateString()}: ${E} print${E!==1?"s":""}`},T)})},N))]}),s.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:v},children:[s.jsx("span",{children:"Less"}),s.jsxs("div",{className:"flex",style:{gap:m},children:[s.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:y,height:y}})]}),s.jsx("span",{children:"More"})]})]})})}const d1=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function VWe(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 GWe({archives:t,currency:e="$"}){const[n,r]=_.useState("30d"),i=_.useMemo(()=>{const p=VWe(n);return t.filter(m=>(Ii(m.completed_at||m.created_at)||new Date(0))>=p)},[t,n]),a=_.useMemo(()=>{const p=new Map;return i.forEach(m=>{const x=Ii(m.completed_at||m.created_at)||new Date,b=`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,y=p.get(b)||{date:b,filament:0,cost:0,prints:0};y.filament+=m.filament_used_grams||0,y.cost+=m.cost||0,y.prints+=1,p.set(b,y)}),Array.from(p.values()).sort((m,x)=>m.date.localeCompare(x.date)).map(m=>({...m,dateLabel:new Date(m.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=_.useMemo(()=>{if(n==="7d"||n==="30d")return a;const p=new Map;return i.forEach(m=>{const x=Ii(m.completed_at||m.created_at)||new Date,b=new Date(x);b.setDate(x.getDate()-x.getDay());const y=`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`,v=p.get(y)||{week:y,filament:0,cost:0,prints:0};v.filament+=m.filament_used_grams||0,v.cost+=m.cost||0,v.prints+=1,p.set(y,v)}),Array.from(p.values()).sort((m,x)=>m.week.localeCompare(x.week)).map(m=>({date:m.week,dateLabel:`Week of ${new Date(m.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...m}))},[i,a,n]),l=_.useMemo(()=>{const p=new Map;return i.forEach(m=>{const b=(m.filament_type||"Unknown").split(", ");b.forEach(y=>{const v=(m.filament_used_grams||0)/b.length;p.set(y,(p.get(y)||0)+v)})}),Array.from(p.entries()).map(([m,x])=>({name:m,value:Math.round(x)})).sort((m,x)=>x.value-m.value)},[i]),c=_.useMemo(()=>{const p=new Date,m=[];for(let x=5;x>=0;x--){const b=new Date(p.getFullYear(),p.getMonth()-x,1),y=new Date(p.getFullYear(),p.getMonth()-x+1,0),v=b.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),S=t.filter(N=>{const T=Ii(N.completed_at||N.created_at)||new Date(0);return T>=b&&T<=y});m.push({month:v,filament:Math.round(S.reduce((N,T)=>N+(T.filament_used_grams||0),0)),cost:S.reduce((N,T)=>N+(T.cost||0),0),prints:S.length})}return m},[t]),u=n==="7d"||n==="30d"?a:o,d=i.reduce((p,m)=>p+(m.filament_used_grams||0),0),f=i.reduce((p,m)=>p+(m.cost||0),0);return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),s.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(p=>s.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))})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Filament"}),s.jsxs("p",{className:"text-2xl font-bold text-white",children:[(d/1e3).toFixed(2),"kg"]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Cost"}),s.jsxs("p",{className:"text-2xl font-bold text-white",children:[e,f.toFixed(2)]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[i.length," prints"]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Avg per Print"}),s.jsxs("p",{className:"text-2xl font-bold text-white",children:[i.length>0?(d/i.length).toFixed(0):0,"g"]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,i.length>0?(f/i.length).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),s.jsx(v1,{width:"100%",height:250,children:s.jsxs(zCe,{data:u,children:[s.jsx("defs",{children:s.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[s.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),s.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),s.jsx(BS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx($S,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),s.jsx(VS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),s.jsx(_1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:p=>[`${Number(p??0).toFixed(0)}g`,"Filament"]}),s.jsx(PZ,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):s.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(v1,{width:160,height:160,children:s.jsxs(ICe,{children:[s.jsx(nZ,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((p,m)=>s.jsx(cv,{fill:d1[m%d1.length]},`cell-${m}`))}),s.jsx(_1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:p=>[`${p??0}g`,"Usage"]})]})}),s.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((p,m)=>{const x=l.reduce((y,v)=>y+v.value,0),b=x>0?(p.value/x*100).toFixed(0):0;return s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:d1[m%d1.length]}}),s.jsx("span",{className:"text-white truncate flex-1",children:p.name}),s.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[b,"%"]})]},p.name)})})]}):s.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),s.jsx(v1,{width:"100%",height:200,children:s.jsxs(kCe,{data:c,children:[s.jsx(BS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx($S,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),s.jsx(VS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:p=>`${p}g`}),s.jsx(_1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(p,m)=>[m==="filament"?`${p??0}g`:m==="cost"?`${e}${Number(p??0).toFixed(2)}`:p??0,m==="filament"?"Filament":m==="cost"?"Cost":"Prints"]}),s.jsx(dO,{}),s.jsx(lZ,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function qWe({id:t,title:e,component:n,isHidden:r,size:i,onToggleVisibility:a,onToggleSize:o}){const{attributes:l,listeners:c,setNodeRef:u,transform:d,transition:f,isDragging:p}=jre({id:t}),m={transform:mx.Transform.toString(d),transition:f,opacity:p?.5:1};return r?null:s.jsxs("div",{ref:u,style:{...m,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${p?"ring-2 ring-bambu-green shadow-lg":""}`,children:[s.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.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:s.jsx(zg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),s.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.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?s.jsx(wW,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):s.jsx(vW,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),s.jsx("button",{onClick:a,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:s.jsx(lN,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),s.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function WWe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:a}){const o=()=>{const T={};return t.forEach(k=>{T[k.id]=k.defaultSize||4}),T},[l,c]=_.useState(()=>{const T=localStorage.getItem(e);if(T)try{const k=JSON.parse(T);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]=_.useState(!1);_.useEffect(()=>{const T=()=>d(k=>!k);return window.addEventListener("toggle-hidden-panel",T),()=>window.removeEventListener("toggle-hidden-panel",T)},[]),_.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),_.useEffect(()=>{const k=t.map(C=>C.id).filter(C=>!l.order.includes(C));k.length>0&&c(C=>({...C,order:[...C.order,...k]}))},[t,l.order]);const f=cre(ZM(B2,{activationConstraint:{distance:8}}),ZM(z2,{coordinateGetter:Pre})),p=T=>{const{active:k,over:C}=T;C&&k.id!==C.id&&c(E=>{const D=E.order.indexOf(k.id),A=E.order.indexOf(C.id);return{...E,order:V2(E.order,D,A)}})},m=T=>{c(k=>({...k,hidden:k.hidden.includes(T)?k.hidden.filter(C=>C!==T):[...k.hidden,T]}))},x=T=>{c(k=>{const C=k.sizes[T]||4,E=C===1?2:C===2?4:1;return{...k,sizes:{...k.sizes,[T]:E}}})},b=()=>{const T={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:o()};c(T),i?.()},y=l.order.map(T=>t.find(k=>k.id===T)).filter(Boolean),v=y.filter(T=>!l.hidden.includes(T.id)),S=y.filter(T=>l.hidden.includes(T.id)),N=a?.({hiddenCount:S.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:b});return s.jsxs("div",{className:"space-y-4",children:[N,!r&&!a&&s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsxs(Te,{variant:"secondary",size:"sm",onClick:b,children:[s.jsx(Rh,{className:"w-4 h-4"}),"Reset Layout"]}),S.length>0&&s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[s.jsx(Ru,{className:"w-4 h-4"}),S.length," Hidden"]})]}),u&&S.length>0&&s.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(T=>s.jsxs("button",{onClick:()=>m(T.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:[s.jsx(Ru,{className:"w-3 h-3"}),T.title]},T.id))})]}),s.jsx(kre,{sensors:f,collisionDetection:fre,onDragEnd:p,children:s.jsx(Are,{items:v.map(T=>T.id),strategy:lF,children:s.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:v.map(T=>s.jsx(qWe,{id:T.id,title:T.title,component:T.component,isHidden:l.hidden.includes(T.id),size:l.sizes[T.id]||2,onToggleVisibility:()=>m(T.id),onToggleSize:()=>x(T.id)},T.id))})})}),v.length===0&&s.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[s.jsx("p",{children:"All widgets are hidden."}),s.jsx(Te,{className:"mt-4",onClick:b,children:"Reset Layout"})]})]})}function KWe({stats:t,currency:e,t:n}){return s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:s.jsx(mc,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),s.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:s.jsx(er,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:s.jsx(mc,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:s.jsx(hP,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:s.jsx(vh,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(2)||"0.00"," kWh"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:s.jsx(hP,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function XWe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,a=n===1?112:n===2?128:144,o=a/2-8,l=o*2*Math.PI;return s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"relative flex-shrink-0",style:{width:a,height:a},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:a/2,cy:a/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:a/2,cy:a/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${i/100*l} ${l}`})]}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:s.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i,"%"]})})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),s.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Yi,{className:"w-4 h-4 text-status-error flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),s.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&&s.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),s.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])=>s.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[s.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),s.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function YWe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.average_time_accuracy;if(i==null)return s.jsx("div",{className:"flex items-center justify-center h-full",children:s.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=(b=>b>=95&&b<=105?"#00ae42":b>105?"#3b82f6":"#f97316")(i),u=i-100,d=n===1?112:n===2?128:144,f=d/2-8,p=f*2*Math.PI,m=n===1?3:n===2?6:999,x=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,m):[];return s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:d/2,cy:d/2,r:f,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:d/2,cy:d/2,r:f,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[s.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),s.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[s.jsx(EW,{className:"w-3 h-3 flex-shrink-0"}),s.jsx("span",{children:r("stats.perfectEstimate")})]}),x.length>0&&s.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(([b,y])=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(b)||`${r("common.printer")} ${b}`}),s.jsxs("span",{className:`font-medium ${y>=95&&y<=105?"text-status-ok":y>105?"text-blue-400":"text-status-warning"}`,children:[y.toFixed(0),"%"]})]},b))})]})]})}function QWe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return s.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,a=r.slice(0,i),o=r.length>i;return e===4&&a.length>4?s.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[s.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),s.jsx("span",{className:"text-bambu-gray",children:c})]}),s.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:s.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):s.jsxs("div",{className:"space-y-3",children:[a.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[s.jsx("span",{className:"text-white",children:l}),s.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),s.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:s.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&s.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-i})})]})}function ZWe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return s.jsx($We,{printDates:t,months:n})}function JWe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?s.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,i])=>s.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[s.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:s.jsx(Ur,{className:"w-4 h-4 text-bambu-green"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[i," ",n("common.prints")]})]})]},r))})}function eKe({archives:t,currency:e,t:n}){return!t||t.length===0?s.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):s.jsx(GWe,{archives:t,currency:e})}function tKe({size:t=1,t:e}){const{data:n,isLoading:r}=at({queryKey:["failureAnalysis"],queryFn:()=>ue.getFailureAnalysis({days:30})});if(r)return s.jsx("div",{className:"flex justify-center py-4",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return s.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const i=t===1?5:t===2?8:999,a=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=a.slice(0,i),l=a.length>i;return s.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[s.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[s.jsx("div",{className:"flex items-center gap-4",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Cn,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),s.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),s.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&&s.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx(AW,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate0&&s.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[s.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),s.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),s.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&s.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:a.length-i})})]})]})}function nKe(){const{t}=Hn(),{showToast:e}=$n(),{hasPermission:n}=Ai(),[r,i]=_.useState(!1),[a,o]=_.useState(!1),[l,c]=_.useState(0),[u,d]=_.useState(0),[f,p]=_.useState(!1);_.useEffect(()=>{const A=()=>{try{const U=localStorage.getItem("bambusy-dashboard-layout");if(U){const F=JSON.parse(U);d(F.hidden?.length||0)}}catch{d(0)}};A(),window.addEventListener("storage",A);const R=setInterval(A,500);return()=>{window.removeEventListener("storage",A),clearInterval(R)}},[l]);const{data:m,isLoading:x,refetch:b}=at({queryKey:["archiveStats"],queryFn:ue.getArchiveStats}),{data:y}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:v}=at({queryKey:["archives"],queryFn:()=>ue.getArchives(void 0,void 0,1e3,0)}),{data:S}=at({queryKey:["settings"],queryFn:ue.getSettings}),N=async A=>{o(!1),i(!0);try{const{blob:R,filename:U}=await ue.exportStats({format:A,days:90}),F=URL.createObjectURL(R),$=document.createElement("a");$.href=F,$.download=U,$.click(),URL.revokeObjectURL(F),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{i(!1)}},T=async()=>{p(!0);try{const A=await ue.recalculateCosts();await b(),e(t("stats.recalculatedCosts",{count:A.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{p(!1)}},k=S?.currency||"$",C=new Map(y?.map(A=>[String(A.id),A.name])||[]),E=v?.map(A=>A.created_at)||[];if(x)return s.jsx("div",{className:"p-4 md:p-8",children:s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const D=[{id:"quick-stats",title:t("stats.quickStats"),component:s.jsx(KWe,{stats:m,currency:k,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:A=>s.jsx(XWe,{stats:m,printerMap:C,size:A,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:A=>s.jsx(YWe,{stats:m,printerMap:C,size:A,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:A=>s.jsx(QWe,{stats:m,size:A,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:A=>s.jsx(tKe,{size:A,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:A=>s.jsx(ZWe,{printDates:E,size:A}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:s.jsx(JWe,{stats:m,printerMap:C,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:s.jsx(eKe,{archives:v||[],currency:k,t}),defaultSize:4}];return s.jsxs("div",{className:"p-4 md:p-8",children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),s.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u>0&&s.jsxs(Te,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[s.jsx(Ru,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),s.jsxs(Te,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(A=>A+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[s.jsx(Rh,{className:"w-4 h-4"}),t("stats.resetLayout")]}),s.jsxs(Te,{variant:"secondary",onClick:T,disabled:f||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[f?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Tce,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),s.jsxs("div",{className:"relative",children:[s.jsxs(Te,{variant:"secondary",onClick:()=>o(!a),disabled:r,children:[r?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(q1,{className:"w-4 h-4"}),t("stats.exportStats")]}),a&&s.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:[s.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:[s.jsx(Ls,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),s.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:[s.jsx(q1,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),s.jsx(WWe,{widgets:D,storageKey:"bambusy-dashboard-layout",hideControls:!0},l)]})}function rKe({plug:t,onEdit:e}){const n=an(),{showToast:r}=$n(),[i,a]=_.useState(!1),[o,l]=_.useState(!1),[c,u]=_.useState(!1),[d,f]=_.useState(!1),{data:p,isLoading:m}=at({queryKey:["smart-plug-status",t.id],queryFn:()=>ue.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:x}=at({queryKey:["printers"],queryFn:ue.getPrinters}),b=x?.find(A=>A.id===t.printer_id),y=mt({mutationFn:A=>ue.controlSmartPlug(t.id,A),onMutate:async A=>{await n.cancelQueries({queryKey:["smart-plug-status",t.id]});const R=n.getQueryData(["smart-plug-status",t.id]),U=A==="on"?"ON":A==="off"||p?.state==="ON"?"OFF":"ON";return n.setQueryData(["smart-plug-status",t.id],F=>({...F,state:U})),{previousStatus:R}},onError:(A,R,U)=>{U?.previousStatus&&n.setQueryData(["smart-plug-status",t.id],U.previousStatus),r(`Failed to turn ${R} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{n.invalidateQueries({queryKey:["smart-plug-status",t.id]}),n.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),v=mt({mutationFn:A=>ue.updateSmartPlug(t.id,A),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&n.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]})}}),S=mt({mutationFn:()=>ue.deleteSmartPlug(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]})}}),N=p?.state==="ON",T=t.plug_type==="mqtt"&&p?.energy?.power!==null&&p?.energy?.power!==void 0,k=(p?.reachable??!1)||T,C=y.isPending,D=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const A=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${A}/`:`http://${A}/`})();return s.jsxs(s.Fragment,{children:[s.jsx(_t,{className:"relative",children:s.jsxs(Mt,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[s.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?k?"bg-teal-500/20":"bg-red-500/20":k?N?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?s.jsx(jR,{className:`w-5 h-5 ${k?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?s.jsx(fN,{className:`w-5 h-5 ${k?N?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):s.jsx(tl,{className:`w-5 h-5 ${k?N?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),s.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})]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[m?s.jsx(ht,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?s.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[s.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"}),k&&s.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?s.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[s.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),s.jsx("span",{className:k?N?"text-status-ok":"text-bambu-gray":"text-status-error",children:k?p?.state||"?":"Offline"})]}):k?s.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[s.jsx(Sg,{className:"w-4 h-4 text-status-ok"}),s.jsx("span",{className:N?"text-status-ok":"text-bambu-gray",children:p?.state||"Unknown"})]}):s.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[s.jsx(sm,{className:"w-4 h-4"}),s.jsx("span",{children:"Offline"})]}),D&&s.jsxs("a",{href:D,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:"Open plug admin page",children:[s.jsx(Kr,{className:"w-3 h-3"}),"Admin"]})]})]}),b&&s.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),s.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&s.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&s.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:[s.jsx(Ru,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&s.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:[s.jsx(wg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&s.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:[s.jsx(si,{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"&&s.jsxs("div",{className:"flex gap-2 mb-3",children:[s.jsxs(Te,{size:"sm",variant:N?"primary":"secondary",disabled:!k||C,onClick:()=>l(!0),className:"flex-1",children:[C?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Gu,{className:"w-4 h-4"}),"On"]}),s.jsxs(Te,{size:"sm",variant:N?"secondary":"primary",disabled:!k||C,onClick:()=>u(!0),className:"flex-1",children:[C?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(gN,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&p?.energy&&s.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&&s.jsxs("div",{className:"flex-1 text-center",children:[s.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(p.energy.power),"W"]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),p.energy.today!==null&&p.energy.today!==void 0&&s.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-lg font-semibold text-white",children:p.energy.today.toFixed(2)}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),s.jsxs("button",{onClick:()=>f(!d),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(bh,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),s.jsx("span",{children:d?"-":"+"})]}),d&&s.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mN,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:A=>v.mutate({show_in_switchbar:A.target.checked}),className:"sr-only peer"}),s.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"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Enabled"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.enabled,onChange:A=>v.mutate({enabled:A.target.checked}),className:"sr-only peer"}),s.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"})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Auto On"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:A=>v.mutate({auto_on:A.target.checked}),className:"sr-only peer"}),s.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"})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:A=>v.mutate({auto_off:A.target.checked}),className:"sr-only peer"}),s.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&&s.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("button",{onClick:()=>v.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:[s.jsx(er,{className:"w-4 h-4"}),"Time"]}),s.jsxs("button",{onClick:()=>v.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:[s.jsx(bN,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),s.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:A=>v.mutate({off_delay_minutes:parseInt(A.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"})]}):s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),s.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:A=>v.mutate({off_temp_threshold:parseInt(A.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),s.jsxs("div",{className:"flex gap-2 pt-2",children:[s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx(fg,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>a(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(rn,{className:"w-4 h-4"})})]})]})]})}),i&&s.jsx(Zn,{title:"Delete Smart Plug",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{S.mutate(),a(!1)},onCancel:()=>a(!1)}),o&&s.jsx(Zn,{title:"Turn On Smart Plug",message:`Are you sure you want to turn on "${t.name}"?`,confirmText:"Turn On",variant:"default",onConfirm:()=>{y.mutate("on"),l(!1)},onCancel:()=>l(!1)}),c&&s.jsx(Zn,{title:"Turn Off Smart Plug",message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:"Turn Off",variant:"danger",onConfirm:()=>{y.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function iKe({plug:t,onClose:e}){const n=an(),r=!!t,[i,a]=_.useState(t?.plug_type||"tasmota"),[o,l]=_.useState(t?.name||""),[c,u]=_.useState(t?.ip_address||""),[d,f]=_.useState(t?.username||""),[p,m]=_.useState(t?.password||""),[x,b]=_.useState(t?.ha_entity_id||""),[y,v]=_.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[S,N]=_.useState(t?.mqtt_power_path||""),[T,k]=_.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,E]=_.useState(t?.mqtt_energy_topic||""),[D,A]=_.useState(t?.mqtt_energy_path||""),[R,U]=_.useState((t?.mqtt_energy_multiplier??1).toString()),[F,$]=_.useState(t?.mqtt_state_topic||""),[j,H]=_.useState(t?.mqtt_state_path||""),[K,V]=_.useState(t?.mqtt_state_on_value||""),[Q,Z]=_.useState(t?.ha_power_entity||""),[ae,B]=_.useState(t?.ha_energy_today_entity||""),[X,ne]=_.useState(t?.ha_energy_total_entity||""),[se,be]=_.useState(""),[xe,de]=_.useState(""),[Pe,ie]=_.useState(!1),Ne=_.useRef(null),[Oe,ge]=_.useState(""),[Ke,G]=_.useState(!1),Y=_.useRef(null),[ce,q]=_.useState(""),[te,I]=_.useState(!1),fe=_.useRef(null),[me,Ee]=_.useState(""),[z,O]=_.useState(!1),ee=_.useRef(null),[le,_e]=_.useState(t?.printer_id||null),[we,re]=_.useState(null),[Fe,He]=_.useState(null),[Ve,$e]=_.useState(t?.power_alert_enabled||!1),[ye,je]=_.useState(t?.power_alert_high?.toString()||""),[Be,Se]=_.useState(t?.power_alert_low?.toString()||""),[Xe,Me]=_.useState(t?.schedule_enabled||!1),[tt,ke]=_.useState(t?.schedule_on_time||""),[We,ze]=_.useState(t?.schedule_off_time||""),[W,De]=_.useState(t?.show_in_switchbar||!1),[Ye,xt]=_.useState(!1),[ft,Bt]=_.useState({scanned:0,total:0}),[Lt,vn]=_.useState([]),Jt=_.useRef(null),{data:ir}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:fr}=at({queryKey:["smart-plugs"],queryFn:ue.getSmartPlugs}),{data:Dn}=at({queryKey:["settings"],queryFn:ue.getSettings}),ln=!!(Dn?.ha_enabled&&Dn?.ha_url&&Dn?.ha_token);_.useEffect(()=>{const pe=setTimeout(()=>{de(se)},300);return()=>clearTimeout(pe)},[se]),_.useEffect(()=>{const pe=Ie=>{Ne.current&&!Ne.current.contains(Ie.target)&&ie(!1),Y.current&&!Y.current.contains(Ie.target)&&G(!1),fe.current&&!fe.current.contains(Ie.target)&&I(!1),ee.current&&!ee.current.contains(Ie.target)&&O(!1)};return document.addEventListener("mousedown",pe),()=>document.removeEventListener("mousedown",pe)},[]);const{data:mr,isLoading:Fn,error:Xn}=at({queryKey:["ha-entities",xe],queryFn:()=>ue.getHAEntities(xe||void 0),enabled:i==="homeassistant"&&ln,retry:!1,staleTime:0}),{data:bn}=at({queryKey:["ha-sensor-entities"],queryFn:ue.getHASensorEntities,enabled:i==="homeassistant"&&ln,retry:!1,staleTime:0});_.useEffect(()=>{const pe=Ie=>{Ie.key==="Escape"&&e()};return window.addEventListener("keydown",pe),()=>{window.removeEventListener("keydown",pe),Jt.current&&clearInterval(Jt.current)}},[e]);const wi=async()=>{xt(!0),vn([]),Bt({scanned:0,total:0}),He(null);try{await ue.startTasmotaScan();const pe=async()=>{try{const Ie=await ue.getTasmotaScanStatus();Bt({scanned:Ie.scanned,total:Ie.total});const Le=await ue.getDiscoveredTasmotaDevices();vn(Le),Ie.running||(xt(!1),Jt.current&&(clearInterval(Jt.current),Jt.current=null))}catch(Ie){console.error("Polling error:",Ie)}};await pe(),Jt.current=setInterval(pe,500)}catch(pe){xt(!1);const Ie=pe instanceof Error?pe.message:typeof pe=="string"?pe:JSON.stringify(pe);He(Ie||"Failed to start scan")}},Ba=async()=>{try{await ue.stopTasmotaScan()}catch{}xt(!1),Jt.current&&(clearInterval(Jt.current),Jt.current=null)},Ae=pe=>{u(pe.ip_address),l(pe.name),re(null)},Ze=mt({mutationFn:()=>ue.testSmartPlugConnection(c,d||null,p||null),onSuccess:pe=>{re(pe),He(null),!o&&pe.device_name&&l(pe.device_name)},onError:pe=>{re(null),He(pe.message)}}),st=mt({mutationFn:pe=>ue.createSmartPlug(pe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:pe=>{He(pe.message)}}),lt=mt({mutationFn:pe=>ue.updateSmartPlug(t.id,pe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:pe=>{He(pe.message)}}),ot=ir?.filter(pe=>!fr?.some(Le=>Le.printer_id===pe.id&&Le.id!==t?.id)),Et=pe=>{if(pe.preventDefault(),He(null),!o.trim()){He("Name is required");return}if(i==="tasmota"&&!c.trim()){He("IP address is required for Tasmota plugs");return}if(i==="homeassistant"&&!x){He("Entity is required for Home Assistant plugs");return}if(i==="mqtt"){const Le=y.trim(),Ce=C.trim(),ut=F.trim();if(!Le&&!Ce&&!ut){He("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const Ie={name:o.trim(),plug_type:i,ip_address:i==="tasmota"?c.trim():null,ha_entity_id:i==="homeassistant"?x:null,ha_power_entity:i==="homeassistant"&&Q||null,ha_energy_today_entity:i==="homeassistant"&&ae||null,ha_energy_total_entity:i==="homeassistant"&&X||null,mqtt_power_topic:i==="mqtt"&&y.trim()||null,mqtt_power_path:i==="mqtt"&&S.trim()||null,mqtt_power_multiplier:i==="mqtt"&&parseFloat(T)||1,mqtt_energy_topic:i==="mqtt"&&C.trim()||null,mqtt_energy_path:i==="mqtt"&&D.trim()||null,mqtt_energy_multiplier:i==="mqtt"&&parseFloat(R)||1,mqtt_state_topic:i==="mqtt"&&F.trim()||null,mqtt_state_path:i==="mqtt"&&j.trim()||null,mqtt_state_on_value:i==="mqtt"&&K.trim()||null,username:i==="tasmota"&&d.trim()||null,password:i==="tasmota"&&p.trim()||null,printer_id:le,power_alert_enabled:Ve,power_alert_high:ye?parseFloat(ye):null,power_alert_low:Be?parseFloat(Be):null,schedule_enabled:Xe,schedule_on_time:tt||null,schedule_off_time:We||null,show_in_switchbar:W};r?lt.mutate(Ie):st.mutate(Ie)},he=st.isPending||lt.isPending;return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:s.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:pe=>pe.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Smart Plug":"Add Smart Plug"}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:Et,className:"p-6 space-y-4 overflow-y-auto",children:[Fe&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Fe}),!r&&s.jsxs("div",{className:"flex gap-2 mb-2",children:[s.jsxs("button",{type:"button",onClick:()=>{a("tasmota"),re(null),He(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${i==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[s.jsx(tl,{className:"w-4 h-4"}),"Tasmota"]}),s.jsxs("button",{type:"button",onClick:()=>{a("homeassistant"),re(null),He(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${i==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[s.jsx(fN,{className:"w-4 h-4"}),"HA"]}),s.jsxs("button",{type:"button",onClick:()=>{a("mqtt"),re(null),He(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${i==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[s.jsx(jR,{className:"w-4 h-4"}),"MQTT"]})]}),!r&&i==="tasmota"&&s.jsxs("div",{className:"space-y-3",children:[Ye?s.jsxs(Te,{type:"button",variant:"secondary",onClick:Ba,className:"w-full",children:[s.jsx(Rt,{className:"w-4 h-4"}),"Stop Scanning"]}):s.jsxs(Te,{type:"button",variant:"primary",onClick:wi,className:"w-full",children:[s.jsx(ba,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),Ye&&ft.total>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[s.jsx("span",{children:"Scanning network..."}),s.jsxs("span",{children:[ft.scanned," / ",ft.total]})]}),s.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:s.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${ft.scanned/ft.total*100}%`}})})]}),Lt.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",Lt.length," device(s) - click to select:"]}),s.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Lt.map(pe=>s.jsxs("button",{type:"button",onClick:()=>Ae(pe),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:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(tl,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:pe.name}),s.jsx("p",{className:"text-xs text-bambu-gray",children:pe.ip_address})]})]}),pe.state&&s.jsxs("span",{className:`flex items-center gap-1 text-xs ${pe.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[s.jsx(Gu,{className:"w-3 h-3"}),pe.state]})]},pe.ip_address))})]}),!Ye&&Lt.length===0&&ft.total>0&&s.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),i==="homeassistant"&&s.jsxs("div",{className:"space-y-3",children:[!ln&&s.jsxs("div",{className:"space-y-3",children:[s.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"," ",s.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),s.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:s.jsx("option",{children:"Choose an entity..."})})]})]}),ln&&s.jsxs(s.Fragment,{children:[Fn&&s.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[s.jsx(ht,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Xn&&s.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: ",Xn.message]}),(()=>{const pe=fr?.filter(Ce=>Ce.ha_entity_id&&Ce.id!==t?.id).map(Ce=>Ce.ha_entity_id)||[],Ie=(mr||[]).filter(Ce=>!pe.includes(Ce.entity_id)),Le=mr?.find(Ce=>Ce.entity_id===x);return s.jsxs("div",{ref:Ne,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:Pe?se:Le?`${Le.friendly_name} (${Le.entity_id})`:"",onChange:Ce=>{be(Ce.target.value),Pe||ie(!0)},onFocus:()=>{ie(!0),be("")},placeholder:"Search entities...",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"}),x&&!Pe&&s.jsx("button",{type:"button",onClick:()=>{b(""),be("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Fn&&s.jsx(ht,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),Pe&&s.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:[Fn&&s.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Fn&&Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:xe?`No entities found matching "${xe}"`:"No entities available"}),!Fn&&Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{b(Ce.entity_id),ie(!1),be(""),o||l(Ce.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Ce.entity_id===x?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[s.jsx("span",{children:Ce.entity_id}),s.jsx("span",{className:Ce.state==="on"?"text-bambu-green":"",children:Ce.state})]})]},Ce.entity_id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:xe?`Searching all entities (${Ie.length} found)`:`Showing switch, light, input_boolean (${Ie.length} available)`})]})})(),x&&bn&&bn.length>0&&s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),s.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const pe=bn.filter(Ce=>Ce.unit_of_measurement==="W"||Ce.unit_of_measurement==="kW"||Ce.unit_of_measurement==="mW"),Ie=Oe?pe.filter(Ce=>Ce.entity_id.toLowerCase().includes(Oe.toLowerCase())||Ce.friendly_name.toLowerCase().includes(Oe.toLowerCase())):pe,Le=bn.find(Ce=>Ce.entity_id===Q);return s.jsxs("div",{ref:Y,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:Ke?Oe:Le?`${Le.friendly_name} (${Le.state} ${Le.unit_of_measurement})`:"",onChange:Ce=>{ge(Ce.target.value),Ke||G(!0)},onFocus:()=>{G(!0),ge("")},placeholder:"Search power sensors...",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&&!Ke&&s.jsx("button",{type:"button",onClick:()=>{Z(""),ge("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Ke&&s.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:[s.jsx("button",{type:"button",onClick:()=>{Z(""),G(!1),ge("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{Z(Ce.entity_id),G(!1),ge("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ce.entity_id===Q?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ce.entity_id," • ",Ce.state," ",Ce.unit_of_measurement]})]},Ce.entity_id)),Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const pe=bn.filter(Ce=>Ce.unit_of_measurement==="kWh"||Ce.unit_of_measurement==="Wh"||Ce.unit_of_measurement==="MWh"),Ie=ce?pe.filter(Ce=>Ce.entity_id.toLowerCase().includes(ce.toLowerCase())||Ce.friendly_name.toLowerCase().includes(ce.toLowerCase())):pe,Le=bn.find(Ce=>Ce.entity_id===ae);return s.jsxs("div",{ref:fe,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:te?ce:Le?`${Le.friendly_name} (${Le.state} ${Le.unit_of_measurement})`:"",onChange:Ce=>{q(Ce.target.value),te||I(!0)},onFocus:()=>{I(!0),q("")},placeholder:"Search energy sensors...",className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ae&&!te&&s.jsx("button",{type:"button",onClick:()=>{B(""),q("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),te&&s.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:[s.jsx("button",{type:"button",onClick:()=>{B(""),I(!1),q("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{B(Ce.entity_id),I(!1),q("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ce.entity_id===ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ce.entity_id," • ",Ce.state," ",Ce.unit_of_measurement]})]},Ce.entity_id)),Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const pe=bn.filter(Ce=>Ce.unit_of_measurement==="kWh"||Ce.unit_of_measurement==="Wh"||Ce.unit_of_measurement==="MWh"),Ie=me?pe.filter(Ce=>Ce.entity_id.toLowerCase().includes(me.toLowerCase())||Ce.friendly_name.toLowerCase().includes(me.toLowerCase())):pe,Le=bn.find(Ce=>Ce.entity_id===X);return s.jsxs("div",{ref:ee,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:z?me:Le?`${Le.friendly_name} (${Le.state} ${Le.unit_of_measurement})`:"",onChange:Ce=>{Ee(Ce.target.value),z||O(!0)},onFocus:()=>{O(!0),Ee("")},placeholder:"Search energy sensors...",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"}),X&&!z&&s.jsx("button",{type:"button",onClick:()=>{ne(""),Ee("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),z&&s.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:[s.jsx("button",{type:"button",onClick:()=>{ne(""),O(!1),Ee("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{ne(Ce.entity_id),O(!1),Ee("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ce.entity_id===X?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ce.entity_id," • ",Ce.state," ",Ce.unit_of_measurement]})]},Ce.entity_id)),Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),i==="mqtt"&&s.jsxs("div",{className:"space-y-3",children:[!Dn?.mqtt_broker&&s.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"," ",s.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),Dn?.mqtt_broker&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[s.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),s.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."})]}),s.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),s.jsx("input",{type:"text",value:y,onChange:pe=>v(pe.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"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),s.jsx("input",{type:"text",value:S,onChange:pe=>N(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),s.jsx("input",{type:"text",value:T,onChange:pe=>k(pe.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"})]})]}),s.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.',s.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),s.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[s.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",s.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),s.jsx("input",{type:"text",value:C,onChange:pe=>E(pe.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"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),s.jsx("input",{type:"text",value:D,onChange:pe=>A(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),s.jsx("input",{type:"text",value:R,onChange:pe=>U(pe.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"})]})]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",s.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),s.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[s.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",s.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),s.jsx("input",{type:"text",value:F,onChange:pe=>$(pe.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"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),s.jsx("input",{type:"text",value:j,onChange:pe=>H(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),s.jsx("input",{type:"text",value:K,onChange:pe=>V(pe.target.value),placeholder:"ON, true, 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"})]})]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",s.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),i==="tasmota"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{type:"text",value:c,onChange:pe=>{u(pe.target.value),re(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"}),s.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>Ze.mutate(),disabled:!c.trim()||Ze.isPending,children:[Ze.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Sg,{className:"w-4 h-4"}),"Test"]})]})]}),i==="tasmota"&&we&&s.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${we.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:we.success?s.jsxs(s.Fragment,{children:[s.jsx(Ar,{className:"w-5 h-5"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Connected!"}),s.jsxs("p",{className:"text-sm opacity-80",children:[we.device_name&&`Device: ${we.device_name} - `,"State: ",we.state]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(sm,{className:"w-5 h-5"}),s.jsx("span",{children:"Connection failed"})]})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),s.jsx("input",{type:"text",value:o,onChange:pe=>l(pe.target.value),placeholder:"Living Room Plug",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i==="tasmota"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),s.jsx("input",{type:"text",value:d,onChange:pe=>f(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),s.jsx("input",{type:"password",value:p,onChange:pe=>m(pe.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"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),i!=="mqtt"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),s.jsxs("select",{value:le??"",onChange:pe=>_e(pe.target.value?Number(pe.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:[s.jsx("option",{value:"",children:"No printer (manual control only)"}),ot?.map(pe=>s.jsx("option",{value:pe.id,children:pe.name},pe.id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(wg,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:Ve,onChange:pe=>$e(pe.target.checked),className:"sr-only peer"}),s.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"})]})]}),Ve&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),s.jsx("input",{type:"number",value:ye,onChange:pe=>je(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),s.jsx("input",{type:"number",value:Be,onChange:pe=>Se(pe.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"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),i!=="mqtt"&&s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(er,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:Xe,onChange:pe=>Me(pe.target.checked),className:"sr-only peer"}),s.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"})]})]}),Xe&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),s.jsx("input",{type:"time",value:tt,onChange:pe=>ke(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),s.jsx("input",{type:"time",value:We,onChange:pe=>ze(pe.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"})]})]}),s.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."})]})]}),s.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mN,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:W,onChange:pe=>De(pe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Te,{type:"submit",disabled:he,className:"flex-1",children:[he?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(hs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function On({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return s.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:s.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 aKe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function sKe({provider:t,onEdit:e}){const n=an(),[r,i]=_.useState(!1),[a,o]=_.useState(!1),[l,c]=_.useState(null),{data:u}=at({queryKey:["printers"],queryFn:ue.getPrinters}),d=u?.find(b=>b.id===t.printer_id),f=mt({mutationFn:b=>ue.updateNotificationProvider(t.id,b),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=mt({mutationFn:()=>ue.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),m=mt({mutationFn:()=>ue.testNotificationProvider(t.id),onSuccess:b=>{c(b),n.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{c({success:!1,message:b.message})}}),x=b=>b||"";return s.jsxs(s.Fragment,{children:[s.jsx(_t,{className:"relative",children:s.jsxs(Mt,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:s.jsx(wg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),s.jsxs("div",{children:[s.jsx("h3",{className:"font-medium text-white",children:t.name}),s.jsx("p",{className:"text-sm text-bambu-gray",children:aKe[t.provider_type]||t.provider_type})]})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&s.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",Bg(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(Ii(t.last_error_at)?.getTime()||0)>(Ii(t.last_success)?.getTime()||0))&&s.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),s.jsx(On,{checked:t.enabled,onChange:b=>f.mutate({enabled:b})})]})]}),d&&s.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),s.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&s.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:s.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&s.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&&s.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&&s.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&s.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&s.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&s.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&s.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&s.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&s.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&&s.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&&s.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&&s.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&&s.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&&s.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&&s.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[s.jsx(W1,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&s.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[s.jsx(si,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),s.jsx("div",{className:"mb-3",children:s.jsxs(Te,{size:"sm",variant:"secondary",disabled:m.isPending,onClick:()=>{c(null),m.mutate()},className:"w-full",children:[m.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(PR,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&s.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?s.jsx(Ar,{className:"w-4 h-4"}):s.jsx(Yi,{className:"w-4 h-4"}),s.jsx("span",{children:l.message})]}),s.jsxs("button",{onClick:()=>o(!a),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:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(bh,{className:"w-4 h-4"}),"Event Settings"]}),a?s.jsx(xh,{className:"w-4 h-4"}):s.jsx(ei,{className:"w-4 h-4"})]}),a&&s.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Enabled"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),s.jsx(On,{checked:t.enabled,onChange:b=>f.mutate({enabled:b})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Started"}),s.jsx(On,{checked:t.on_print_start,onChange:b=>f.mutate({on_print_start:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),s.jsx(On,{checked:t.on_plate_not_empty??!0,onChange:b=>f.mutate({on_plate_not_empty:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),s.jsx(On,{checked:t.on_print_complete,onChange:b=>f.mutate({on_print_complete:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),s.jsx(On,{checked:t.on_print_failed,onChange:b=>f.mutate({on_print_failed:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),s.jsx(On,{checked:t.on_print_stopped,onChange:b=>f.mutate({on_print_stopped:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),s.jsx(On,{checked:t.on_print_progress,onChange:b=>f.mutate({on_print_progress:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),s.jsx(On,{checked:t.on_printer_offline,onChange:b=>f.mutate({on_printer_offline:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),s.jsx(On,{checked:t.on_printer_error,onChange:b=>f.mutate({on_printer_error:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),s.jsx(On,{checked:t.on_filament_low,onChange:b=>f.mutate({on_filament_low:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),s.jsx(On,{checked:t.on_maintenance_due??!1,onChange:b=>f.mutate({on_maintenance_due:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_humidity_high??!1,onChange:b=>f.mutate({on_ams_humidity_high:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_temperature_high??!1,onChange:b=>f.mutate({on_ams_temperature_high:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>f.mutate({on_ams_ht_humidity_high:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>f.mutate({on_ams_ht_temperature_high:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Added"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),s.jsx(On,{checked:t.on_queue_job_added??!1,onChange:b=>f.mutate({on_queue_job_added:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),s.jsx(On,{checked:t.on_queue_job_assigned??!1,onChange:b=>f.mutate({on_queue_job_assigned:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Started"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),s.jsx(On,{checked:t.on_queue_job_started??!1,onChange:b=>f.mutate({on_queue_job_started:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),s.jsx(On,{checked:t.on_queue_job_waiting??!0,onChange:b=>f.mutate({on_queue_job_waiting:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),s.jsx(On,{checked:t.on_queue_job_skipped??!0,onChange:b=>f.mutate({on_queue_job_skipped:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),s.jsx(On,{checked:t.on_queue_job_failed??!0,onChange:b=>f.mutate({on_queue_job_failed:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),s.jsx(On,{checked:t.on_queue_completed??!1,onChange:b=>f.mutate({on_queue_completed:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W1,{className:"w-4 h-4 text-purple-400"}),s.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),s.jsx(On,{checked:t.quiet_hours_enabled,onChange:b=>f.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&s.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(er,{className:"w-4 h-4 text-bambu-gray"}),s.jsxs("span",{className:"text-sm text-white",children:[x(t.quiet_hours_start)||"22:00"," - ",x(t.quiet_hours_end)||"07:00"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(si,{className:"w-4 h-4 text-emerald-400"}),s.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),s.jsx(On,{checked:t.daily_digest_enabled,onChange:b=>f.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&s.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(er,{className:"w-4 h-4 text-bambu-gray"}),s.jsxs("span",{className:"text-sm text-white",children:["Send at ",x(t.daily_digest_time)||"08:00"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),s.jsxs("div",{className:"flex gap-2 pt-2",children:[s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx(fg,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(rn,{className:"w-4 h-4"})})]})]})]})}),r&&s.jsx(Zn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{p.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const hq=[{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 oKe({provider:t,onClose:e}){const n=an(),r=!!t,[i,a]=_.useState(t?.name||""),[o,l]=_.useState(t?.provider_type||"email"),[c,u]=_.useState(t?.printer_id||null),[d,f]=_.useState(t?.quiet_hours_enabled||!1),[p,m]=_.useState(t?.quiet_hours_start||"22:00"),[x,b]=_.useState(t?.quiet_hours_end||"07:00"),[y,v]=_.useState(t?.daily_digest_enabled||!1),[S,N]=_.useState(t?.daily_digest_time||"08:00"),[T,k]=_.useState(t?.on_print_start??!1),[C,E]=_.useState(t?.on_print_complete??!0),[D,A]=_.useState(t?.on_print_failed??!0),[R,U]=_.useState(t?.on_print_stopped??!0),[F,$]=_.useState(t?.on_print_progress??!1),[j,H]=_.useState(t?.on_printer_offline??!1),[K,V]=_.useState(t?.on_printer_error??!1),[Q,Z]=_.useState(t?.on_filament_low??!1),[ae,B]=_.useState(t?.on_maintenance_due??!1),[X,ne]=_.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([q,te])=>[q,String(te)])):{}),[se,be]=_.useState(null),[xe,de]=_.useState(null),{data:Pe}=at({queryKey:["printers"],queryFn:ue.getPrinters});_.useEffect(()=>{const q=te=>{te.key==="Escape"&&e()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[e]);const ie=mt({mutationFn:()=>ue.testNotificationConfig({provider_type:o,config:X}),onSuccess:q=>{be(q),de(null)},onError:q=>{be({success:!1,message:q.message})}}),Ne=mt({mutationFn:q=>ue.createNotificationProvider(q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),Oe=mt({mutationFn:q=>ue.updateNotificationProvider(t.id,q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),ge=q=>{if(q.preventDefault(),de(null),!i.trim()){de("Name is required");return}const te=Y(o);for(const fe of te)if(!X[fe.key]?.trim()){de(`${fe.label} is required`);return}const I={name:i.trim(),provider_type:o,config:X,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?p:null,quiet_hours_end:d?x:null,daily_digest_enabled:y,daily_digest_time:y?S:null,on_print_start:T,on_print_complete:C,on_print_failed:D,on_print_stopped:R,on_print_progress:F,on_printer_offline:j,on_printer_error:K,on_filament_low:Q,on_maintenance_due:ae};r?Oe.mutate(I):Ne.mutate(I)},Ke=Ne.isPending||Oe.isPending,G=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:te=>te.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:te=>te.payload_format!=="slack"}];default:return[]}},Y=q=>G(q).filter(te=>te.required),ce=G(o);return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:s.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:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:ge,className:"p-6 space-y-4",children:[xe&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:xe}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),s.jsx("input",{type:"text",value:i,onChange:q=>a(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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),s.jsx("select",{value:o,onChange:q=>{l(q.target.value),ne({}),be(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:hq.map(q=>s.jsx("option",{value:q.value,children:q.label},q.value))}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:hq.find(q=>q.value===o)?.description})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),ce.filter(q=>!("showIf"in q)||q.showIf?.(X)!==!1).map(q=>s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[q.label," ",q.required&&"*"]}),q.type==="select"&&"options"in q&&q.options?s.jsx("select",{value:X[q.key]||q.options[0]?.value||"",onChange:te=>{ne({...X,[q.key]:te.target.value}),be(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(te=>s.jsx("option",{value:te.value,children:te.label},te.value))}):s.jsx("input",{type:q.type,value:X[q.key]||"",onChange:te=>{ne({...X,[q.key]:te.target.value}),be(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))]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>{be(null),ie.mutate()},disabled:ie.isPending||!X[Y(o)[0]?.key],className:"flex-1",children:[ie.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(PR,{className:"w-4 h-4"}),"Test Configuration"]})}),se&&s.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${se.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:se.success?s.jsxs(s.Fragment,{children:[s.jsx(Ar,{className:"w-5 h-5"}),s.jsx("span",{children:se.message})]}):s.jsxs(s.Fragment,{children:[s.jsx(Yi,{className:"w-5 h-5"}),s.jsx("span",{children:se.message})]})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),s.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:[s.jsx("option",{value:"",children:"All printers"}),Pe?.map(q=>s.jsx("option",{value:q.id,children:q.name},q.id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),s.jsx(On,{checked:d,onChange:f})]}),d&&s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),s.jsx("input",{type:"time",value:p,onChange:q=>m(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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),s.jsx("input",{type:"time",value:x,onChange:q=>b(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"})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),s.jsx(On,{checked:y,onChange:v})]}),y&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),s.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),s.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Start"}),s.jsx(On,{checked:T,onChange:k})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Complete"}),s.jsx(On,{checked:C,onChange:E})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Failed"}),s.jsx(On,{checked:D,onChange:A})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Stopped"}),s.jsx(On,{checked:R,onChange:U})]}),s.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-white",children:"Progress"}),s.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),s.jsx(On,{checked:F,onChange:$})]})]})]}),s.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Offline"}),s.jsx(On,{checked:j,onChange:H})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Error"}),s.jsx(On,{checked:K,onChange:V})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),s.jsx(On,{checked:Q,onChange:Z})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),s.jsx(On,{checked:ae,onChange:B})]})]})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Te,{type:"submit",disabled:Ke,className:"flex-1",children:[Ke?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(hs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function lKe({template:t,onClose:e}){const n=an(),r=_.useRef(null),[i,a]=_.useState(t.title_template),[o,l]=_.useState(t.body_template),[c,u]=_.useState(null),[d,f]=_.useState(!0),{data:p}=at({queryKey:["template-variables"],queryFn:ue.getTemplateVariables}),m=p?.find(k=>k.event_type===t.event_type),{data:x,isLoading:b}=at({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>ue.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});_.useEffect(()=>{const k=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[e]);const y=mt({mutationFn:k=>ue.updateNotificationTemplate(t.id,k),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:k=>{u(k.message)}}),v=mt({mutationFn:()=>ue.resetNotificationTemplate(t.id),onSuccess:k=>{a(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}y.mutate({title_template:i,body_template:o})},N=k=>{const C=r.current;if(!C)return;const E=C.selectionStart,D=C.selectionEnd,A=o,R=A.substring(0,E),U=A.substring(D),F=R+`{${k}}`+U;l(F),setTimeout(()=>{C.focus();const $=E+k.length+2;C.setSelectionRange($,$)},0)},T=i!==t.title_template||o!==t.body_template;return s.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),s.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:s.jsx(Rt,{className:"w-5 h-5 text-bambu-gray"})})]}),s.jsxs("form",{onSubmit:S,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),s.jsx("input",{type:"text",value:i,onChange:k=>a(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..."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),s.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..."})]}),m&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:m.variables.map(k=>s.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:[s.jsx(dr,{className:"w-3 h-3"}),k]},k))}),s.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(Ru,{className:"w-4 h-4"}),"Live Preview"]}),s.jsx("button",{type:"button",onClick:()=>f(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&s.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):x?s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),s.jsx("div",{className:"text-white font-medium",children:x.title})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),s.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:x.body})]})]}):s.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),s.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[s.jsxs(Te,{type:"button",variant:"ghost",onClick:()=>v.mutate(),disabled:v.isPending,className:"text-orange-400 hover:text-orange-300",children:[v.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(Rh,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),s.jsxs(Te,{onClick:S,disabled:y.isPending||!T,children:[y.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(hs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const cKe={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"},uKe={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 dKe({onClose:t}){const e=an(),{showToast:n}=$n(),[r,i]=_.useState(7),[a,o]=_.useState(null),[l,c]=_.useState(!1),{data:u}=at({queryKey:["settings"],queryFn:ue.getSettings}),d=u?.time_format||"system",{data:f,isLoading:p,refetch:m,isRefetching:x}=at({queryKey:["notification-logs",r,l],queryFn:()=>ue.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:b}=at({queryKey:["notification-log-stats",r],queryFn:()=>ue.getNotificationLogStats(r)}),y=mt({mutationFn:()=>ue.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")}}),v=S=>{const N=Ii(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()+" "+Dfe(N,d)};return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.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:[s.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(q0,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),s.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&s.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:s.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[s.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",s.jsx("span",{className:"text-white font-medium",children:b.total})," notifications"]}),s.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[s.jsx(Ar,{className:"w-4 h-4"}),b.success_count," sent"]}),b.failure_count>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(Yi,{className:"w-4 h-4"}),b.failure_count," failed"]})]})}),s.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[s.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:[s.jsx("option",{value:1,children:"Last 24 hours"}),s.jsx("option",{value:7,children:"Last 7 days"}),s.jsx("option",{value:30,children:"Last 30 days"}),s.jsx("option",{value:90,children:"Last 90 days"})]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[s.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"]}),s.jsx("div",{className:"flex-1"}),s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>m(),disabled:x,children:[x?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Refresh"]}),s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>y.mutate(),disabled:y.isPending,className:"text-red-400 hover:text-red-300",children:[y.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"}),"Clear Old"]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:p?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):f&&f.length>0?s.jsx("div",{className:"space-y-2",children:f.map(S=>s.jsx(hKe,{log:S,isExpanded:a===S.id,onToggle:()=>o(a===S.id?null:S.id),formatDate:v,formatFullDate:N=>Hg(N,d)},S.id))}):s.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[s.jsx(q0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function hKe({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){return s.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:[s.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?s.jsx(Ar,{className:"w-4 h-4 text-bambu-green shrink-0"}):s.jsx(Yi,{className:"w-4 h-4 text-red-400 shrink-0"}),s.jsx("span",{className:`text-xs font-medium ${uKe[t.event_type]||"text-bambu-gray"}`,children:cKe[t.event_type]||t.event_type}),s.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&s.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),s.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?s.jsx(xh,{className:"w-4 h-4 text-bambu-gray shrink-0"}):s.jsx(ei,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&s.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),s.jsx("p",{className:"text-sm text-white",children:t.title})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),s.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),s.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),s.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[s.jsxs("span",{children:["Provider: ",t.provider_type]}),s.jsxs("span",{children:["Time: ",i(t.created_at)]})]})]})]})}async function fKe(){const t=await fetch("/api/v1/settings/spoolman");if(!t.ok)throw new Error("Failed to load Spoolman settings");return t.json()}async function mKe(t){const e=await fetch("/api/v1/settings/spoolman",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)throw new Error("Failed to save Spoolman settings");return e.json()}function pKe(){const t=an(),[e,n]=_.useState(!1),[r,i]=_.useState(""),[a,o]=_.useState("auto"),[l,c]=_.useState(!1),[u,d]=_.useState("all"),[f,p]=_.useState(!1),[m,x]=_.useState(!1),{data:b,isLoading:y}=at({queryKey:["spoolman-settings"],queryFn:fKe}),{data:v,isLoading:S,refetch:N}=at({queryKey:["spoolman-status"],queryFn:ue.getSpoolmanStatus,refetchInterval:3e4}),{data:T}=at({queryKey:["printers"],queryFn:ue.getPrinters});_.useEffect(()=>{b&&(n(b.spoolman_enabled==="true"),i(b.spoolman_url||""),o(b.spoolman_sync_mode||"auto"),p(!0))},[b]),_.useEffect(()=>{if(!f||!b)return;if(b.spoolman_enabled==="true"!==e||(b.spoolman_url||"")!==r||(b.spoolman_sync_mode||"auto")!==a){const H=setTimeout(()=>{k.mutate()},500);return()=>clearTimeout(H)}},[e,r,a,f]);const k=mt({mutationFn:()=>mKe({spoolman_enabled:e?"true":"false",spoolman_url:r,spoolman_sync_mode:a}),onSuccess:()=>{t.invalidateQueries({queryKey:["spoolman-settings"]}),t.invalidateQueries({queryKey:["spoolman-status"]}),c(!0),setTimeout(()=>c(!1),2e3)}}),C=mt({mutationFn:ue.connectSpoolman,onSuccess:()=>{N()}}),E=mt({mutationFn:ue.disconnectSpoolman,onSuccess:()=>{N()}}),D=mt({mutationFn:ue.syncAllPrintersAms,onSuccess:j=>{j.success}}),A=mt({mutationFn:j=>ue.syncPrinterAms(j),onSuccess:j=>{j.success}}),R=()=>{u==="all"?D.mutate():A.mutate(u)},U=D.isPending||A.isPending,F=u==="all"?D.data:A.data,$=u==="all"?D.isSuccess:A.isSuccess;return y?s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Nu,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]})}),s.jsx(Mt,{children:s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Nu,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]}),k.isPending&&s.jsx(ht,{className:"w-4 h-4 text-bambu-green animate-spin"}),l&&s.jsx(Ia,{className:"w-4 h-4 text-bambu-green"})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Spoolman for filament inventory tracking. AMS data will sync automatically."}),s.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Zo,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-xs text-blue-300",children:[s.jsx("p",{className:"font-medium mb-1",children:"How Sync Works"}),s.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[s.jsx("li",{children:"Only official Bambu Lab spools with RFID are synced"}),s.jsx("li",{children:"New spools are auto-created in Spoolman on first sync"}),s.jsx("li",{children:"Non-Bambu Lab spools (third-party, refilled) are skipped"})]}),s.jsx("p",{className:"font-medium mt-2 mb-1",children:"Linking Existing Spools"}),s.jsx("p",{className:"text-blue-300/80",children:'To link existing Spoolman spools to your AMS, hover over an AMS slot and click "Link to Spoolman".'})]})]})}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Enable Spoolman"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Sync filament data with Spoolman server"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:e,onChange:j=>n(j.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Spoolman URL"}),s.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:r,onChange:j=>i(j.target.value),disabled:!e,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 disabled:opacity-50"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"URL of your Spoolman server (e.g., http://localhost:7912)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Sync Mode"}),s.jsxs("select",{value:a,onChange:j=>o(j.target.value),disabled:!e,className:"w-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:[s.jsx("option",{value:"auto",children:"Automatic"}),s.jsx("option",{value:"manual",children:"Manual Only"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a==="auto"?"AMS data syncs automatically when changes are detected":"Only sync when manually triggered"})]}),e&&s.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:"Status:"}),S?s.jsx(ht,{className:"w-4 h-4 text-bambu-gray animate-spin"}):v?.connected?s.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[s.jsx(Ia,{className:"w-4 h-4"}),"Connected"]}):s.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[s.jsx(Rt,{className:"w-4 h-4"}),"Disconnected"]})]}),s.jsx("div",{className:"flex gap-2",children:v?.connected?s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(gde,{className:"w-4 h-4"}),"Disconnect"]}):s.jsxs(Te,{size:"sm",onClick:()=>C.mutate(),disabled:C.isPending||!r,children:[C.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(uc,{className:"w-4 h-4"}),"Connect"]})})]}),C.isError&&s.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:C.error.message}),v?.connected&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Sync AMS Data"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Manually sync printer AMS data to Spoolman"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsxs("select",{value:u,onChange:j=>d(j.target.value==="all"?"all":Number(j.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:[s.jsx("option",{value:"all",children:"All Printers"}),T?.map(j=>s.jsx("option",{value:j.id,children:j.name},j.id))]}),s.jsx(ei,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:R,disabled:U,children:[U?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Sync"]})]})]}),$&&F&&s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx("div",{className:`p-2 rounded text-sm ${F.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:F.success?`Synced ${F.synced_count} spool${F.synced_count!==1?"s":""} successfully`:`Synced ${F.synced_count} spool${F.synced_count!==1?"s":""} with ${F.errors.length} error${F.errors.length!==1?"s":""}`}),F.skipped_count>0&&s.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[s.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Cn,{className:"w-3.5 h-3.5"}),s.jsxs("span",{className:"font-medium",children:[F.skipped_count," spool",F.skipped_count!==1?"s":""," skipped"]})]}),F.skipped_count>5&&s.jsx("button",{onClick:()=>x(!m),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:m?"Show less":"Show all"})]}),s.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(m?F.skipped:F.skipped.slice(0,5)).map((j,H)=>s.jsxs("li",{className:"flex items-center gap-2",children:[j.color&&s.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${j.color}`}}),s.jsx("span",{children:j.location}),s.jsxs("span",{className:"text-amber-300/60",children:["- ",j.reason]})]},H)),!m&&F.skipped_count>5&&s.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",F.skipped_count-5," more"]})]})]}),F.errors.length>0&&s.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[s.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),s.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:F.errors.map((j,H)=>s.jsx("li",{children:j},H))})]})]})]})]})]})}function gKe({link:t,onClose:e}){const n=an(),{mode:r}=Oh(),i=!!t,a=_.useRef(null),[o,l]=_.useState(t?.name||""),[c,u]=_.useState(t?.url||""),[d,f]=_.useState(t?.icon||"link"),[p,m]=_.useState(!!t?.custom_icon),[x,b]=_.useState(t?.custom_icon?ue.getExternalLinkIconUrl(t.id):null),[y,v]=_.useState(null),[S,N]=_.useState(null);_.useEffect(()=>{const U=F=>{F.key==="Escape"&&e()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[e]);const T=mt({mutationFn:async U=>{const F=await ue.createExternalLink(U);return y?await ue.uploadExternalLinkIcon(F.id,y):F},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{N(U.message)}}),k=mt({mutationFn:async U=>{let F=await ue.updateExternalLink(t.id,U);return y?F=await ue.uploadExternalLinkIcon(t.id,y):!p&&t?.custom_icon&&(F=await ue.deleteExternalLinkIcon(t.id)),F},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{N(U.message)}}),C=U=>{const F=U.target.files?.[0];if(F){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(F.type)){N("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(F.size>1024*1024){N("Image file must be less than 1MB");return}v(F),m(!0);const j=new FileReader;j.onload=H=>{b(H.target?.result)},j.readAsDataURL(F)}},E=()=>{v(null),b(null),m(!1),a.current&&(a.current.value="")},D=U=>{if(U.preventDefault(),N(null),!o.trim()){N("Name is required");return}if(!c.trim()){N("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){N("URL must start with http:// or https://");return}const F={name:o.trim(),url:c.trim(),icon:d};i?k.mutate(F):T.mutate(F)},A=T.isPending||k.isPending,R=yN(d);return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:U=>U.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:p&&x?s.jsx("img",{src:x,alt:"",className:`w-5 h-5 rounded ${r==="dark"?"invert opacity-[0.65]":"opacity-60"}`}):s.jsx(R,{className:"w-5 h-5"})}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:D,className:"p-6 space-y-4",children:[S&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:S}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),s.jsx("input",{type:"text",value:o,onChange:U=>l(U.target.value),placeholder:"My Link",maxLength:50,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),s.jsx("input",{type:"text",value:c,onChange:U=>u(U.target.value),placeholder:"https://example.com",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),s.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),s.jsx("input",{ref:a,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:C}),p&&x?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("img",{src:x,alt:"Custom icon",className:`w-8 h-8 rounded border border-bambu-dark-tertiary ${r==="dark"?"invert opacity-[0.65]":"opacity-60"}`}),s.jsx("button",{type:"button",onClick:E,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:s.jsx(rn,{className:"w-4 h-4"})})]}):s.jsxs(Te,{type:"button",variant:"secondary",size:"sm",onClick:()=>a.current?.click(),children:[s.jsx(Ua,{className:"w-4 h-4"}),"Upload"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!p&&s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),s.jsx(Mfe,{value:d,onChange:f})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Te,{type:"submit",disabled:A,className:"flex-1",children:[A?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(hs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function xKe(){const t=an(),[e,n]=_.useState(!1),[r,i]=_.useState(null),[a,o]=_.useState(null),[l,c]=_.useState(null),{data:u,isLoading:d}=at({queryKey:["external-links"],queryFn:ue.getExternalLinks}),f=mt({mutationFn:S=>ue.deleteExternalLink(S),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),p=mt({mutationFn:S=>ue.reorderExternalLinks(S),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),m=(S,N)=>{c(N),S.dataTransfer.effectAllowed="move"},x=S=>{S.preventDefault(),S.dataTransfer.dropEffect="move"},b=(S,N)=>{if(S.preventDefault(),l===null||l===N||!u)return;const T=u.map(D=>D.id),k=T.indexOf(l),C=T.indexOf(N);if(k===-1||C===-1)return;const E=[...T];E.splice(k,1),E.splice(C,0,l),p.mutate(E),c(null)},y=S=>{o(S)},v=()=>{a&&(f.mutate(a.id),o(null))};return s.jsxs(s.Fragment,{children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(uc,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),s.jsxs(Te,{size:"sm",onClick:()=>n(!0),children:[s.jsx(dr,{className:"w-4 h-4"}),"Add Link"]})]})}),s.jsxs(Mt,{children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),d?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?s.jsx("div",{className:"space-y-2",children:u.map(S=>{const N=yN(S.icon);return s.jsxs("div",{draggable:!0,onDragStart:T=>m(T,S.id),onDragOver:x,onDrop:T=>b(T,S.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${l===S.id?"opacity-50":""}`,children:[s.jsx(zg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:s.jsx(N,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-white font-medium truncate",children:S.name}),s.jsx(Kr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),s.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:S.url})]}),s.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s.jsx("button",{onClick:()=>i(S),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:"Edit",children:s.jsx(Qi,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>y(S),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:"Delete",children:s.jsx(rn,{className:"w-4 h-4"})})]})]},S.id)})}):s.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[s.jsx(uc,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),s.jsx("p",{children:"No external links configured"}),s.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(e||r)&&s.jsx(gKe,{link:r,onClose:()=>{n(!1),i(null)}}),a&&s.jsx(Zn,{title:"Delete Link",message:`Are you sure you want to delete "${a.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:v,onCancel:()=>o(null)})]})}function bKe(){const t=an(),{showToast:e}=$n(),[n,r]=_.useState(!1),[i,a]=_.useState(""),[o,l]=_.useState("immediate"),[c,u]=_.useState("3DPrinter-X1-Carbon"),[d,f]=_.useState(!1),[p,m]=_.useState(null),{data:x,isLoading:b}=at({queryKey:["virtual-printer-settings"],queryFn:p1.getSettings,refetchInterval:1e4}),{data:y}=at({queryKey:["virtual-printer-models"],queryFn:p1.getModels});_.useEffect(()=>{if(x){r(x.enabled);let D=x.mode==="queue"?"review":x.mode;D!=="immediate"&&D!=="review"&&D!=="print_queue"&&(D="immediate"),l(D),u(x.model)}},[x]);const v=mt({mutationFn:D=>p1.updateSettings(D),onSuccess:()=>{t.invalidateQueries({queryKey:["virtual-printer-settings"]}),e("Virtual printer settings updated"),m(null)},onError:D=>{if(e(D.message||"Failed to update settings","error"),x){r(x.enabled);const A=x.mode==="queue"?"review":x.mode;l(A==="print_queue"||A==="review"?A:"immediate"),u(x.model)}m(null)}}),S=()=>{const D=!n;if(D&&!i&&!x?.access_code_set){e("Please set an access code first","error");return}r(D),m("toggle"),v.mutate({enabled:D,access_code:i||void 0,mode:o})},N=()=>{if(!i){e("Access code cannot be empty","error");return}if(i.length!==8){e("Access code must be exactly 8 characters","error");return}m("accessCode"),v.mutate({access_code:i}),a("")},T=D=>{l(D),m("mode"),v.mutate({mode:D})},k=D=>{u(D),m("model"),v.mutate({model:D})};if(b)return s.jsx(_t,{children:s.jsx(Mt,{className:"py-8 flex justify-center",children:s.jsx(ht,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const C=x?.status,E=C?.running||!1;return s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[s.jsx("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ur,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Virtual Printer"})]}),C&&s.jsxs("div",{className:`flex items-center gap-2 text-sm ${E?"text-green-400":"text-bambu-gray"}`,children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${E?"bg-green-400 animate-pulse":"bg-gray-500"}`}),E?"Running":"Stopped"]})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable a virtual printer that appears in Bambu Studio and OrcaSlicer. Files sent to this printer will be archived directly without printing."}),s.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-white font-medium",children:"Enable Virtual Printer"}),s.jsx("div",{className:"text-sm text-bambu-gray",children:E?'Visible as "Bambuddy" in slicer discovery':"Not visible to slicers"})]}),s.jsx("button",{onClick:S,disabled:p==="toggle",className:`relative w-12 h-6 rounded-full transition-colors ${n?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${p==="toggle"?"opacity-50":""}`,children:s.jsx("span",{className:`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${n?"translate-x-6":""}`})})]}),s.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[s.jsx("div",{className:"text-white font-medium mb-2",children:"Printer Model"}),s.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:"Select which printer model to emulate."}),s.jsxs("div",{className:"relative",children:[s.jsx("select",{value:c,onChange:D=>k(D.target.value),disabled:p==="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:y?.models&&Object.entries(y.models).sort(([,D],[,A])=>D.localeCompare(A)).map(([D,A])=>s.jsx("option",{value:D,children:A},D))}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),n&&E&&s.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[s.jsx(Zo,{className:"w-3 h-3 inline mr-1"}),"Changing the model will restart the virtual printer"]})]}),s.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[s.jsx("div",{className:"text-white font-medium mb-2",children:"Access Code"}),s.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:x?.access_code_set?s.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[s.jsx(Ia,{className:"w-4 h-4"}),"Access code is set"]}):s.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[s.jsx(Cn,{className:"w-4 h-4"}),"No access code set - required to enable"]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx("input",{type:d?"text":"password",value:i,onChange:D=>a(D.target.value),placeholder:x?.access_code_set?"Enter new code to change":"Enter 8-char code",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"}),s.jsx("button",{onClick:()=>f(!d),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:d?s.jsx(lN,{className:"w-4 h-4"}):s.jsx(Ru,{className:"w-4 h-4"})})]}),s.jsx(Te,{onClick:N,disabled:!i||p==="accessCode",variant:"primary",children:p==="accessCode"?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):"Save"})]}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:["Must be exactly 8 characters. Used by slicers to authenticate.",i&&s.jsxs("span",{className:i.length===8?"text-green-400":"text-yellow-400",children:[" ","(",i.length,"/8)"]})]})]}),s.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[s.jsx("div",{className:"text-white font-medium mb-2",children:"Mode"}),s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsxs("button",{onClick:()=>T("immediate"),disabled:p==="mode",className:`p-3 rounded-lg border text-left transition-colors ${o==="immediate"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[s.jsx("div",{className:"text-white font-medium",children:"Archive"}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Archive files immediately"})]}),s.jsxs("button",{onClick:()=>T("review"),disabled:p==="mode",className:`p-3 rounded-lg border text-left transition-colors ${o==="review"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[s.jsx("div",{className:"text-white font-medium",children:"Review"}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Review and tag before archiving"})]}),s.jsxs("button",{onClick:()=>T("print_queue"),disabled:p==="mode",className:`p-3 rounded-lg border text-left transition-colors ${o==="print_queue"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[s.jsx("div",{className:"text-white font-medium",children:"Queue"}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Archive and add to print queue"})]})]})]})]})]})}),s.jsxs("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:[s.jsx(_t,{className:"border-l-4 border-l-yellow-500",children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Cn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm",children:[s.jsx("p",{className:"text-white font-medium mb-2",children:"Setup Required"}),s.jsx("p",{className:"text-bambu-gray mb-3",children:"The virtual printer feature requires additional system configuration before it will work. This includes port forwarding, firewall rules, and platform-specific settings."}),s.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:[s.jsx(Kr,{className:"w-4 h-4"}),"Read the setup guide before enabling"]})]})]})})}),s.jsx(_t,{children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Zo,{className:"w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-bambu-gray",children:[s.jsx("p",{className:"mb-2",children:s.jsx("strong",{className:"text-white",children:"How it works:"})}),s.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[s.jsx("li",{children:"Complete the setup guide for your platform"}),s.jsx("li",{children:"Enable the virtual printer and set an access code"}),s.jsx("li",{children:'In Bambu Studio or OrcaSlicer, go to "Add Printer"'}),s.jsx("li",{children:'The "Bambuddy" printer should appear in the discovery list'}),s.jsx("li",{children:"Connect using the access code you set"}),s.jsx("li",{children:'When you "print" to Bambuddy, the 3MF file is archived instead'})]})]})]})})}),C&&E&&s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h3",{className:"text-md font-semibold text-white",children:"Status Details"})}),s.jsx(Mt,{children:s.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Printer Name"}),s.jsx("div",{className:"text-white",children:C.name})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Model"}),s.jsx("div",{className:"text-white",children:C.model_name||C.model})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Serial Number"}),s.jsx("div",{className:"text-white font-mono",children:C.serial})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Mode"}),s.jsx("div",{className:"text-white capitalize",children:C.mode})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Pending Files"}),s.jsx("div",{className:"text-white",children:C.pending_files})]})]})})]})]})]})}function fq({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:s.jsx(Ar,{className:"w-3 h-3"}),failed:s.jsx(Yi,{className:"w-3 h-3"}),skipped:s.jsx(DR,{className:"w-3 h-3"}),running:s.jsx(ht,{className:"w-3 h-3 animate-spin"})};return s.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 yKe(t){return t?new Date(t).toLocaleString():"-"}function mq(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 a=Math.abs(i);if(a<60)return`${a}m ago`;const o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}else{if(i<60)return`in ${i}m`;const a=Math.floor(i/60);return a<24?`in ${a}h`:`in ${Math.floor(a/24)}d`}}function vKe(){const t=an(),{showToast:e}=$n(),[n,r]=_.useState(""),[i,a]=_.useState(""),[o,l]=_.useState("main"),[c,u]=_.useState(!1),[d,f]=_.useState("daily"),[p,m]=_.useState(!0),[x,b]=_.useState(!0),[y,v]=_.useState(!1),[S,N]=_.useState(!0),[T,k]=_.useState(!1),[C,E]=_.useState(!1),[D,A]=_.useState(""),[R,U]=_.useState(!1),[F,$]=_.useState(null),[j,H]=_.useState(null),K=_.useRef(null);_.useEffect(()=>{if(T||C){const Ee=z=>(z.preventDefault(),z.returnValue="A backup operation is in progress. Are you sure you want to leave?",z.returnValue);return window.addEventListener("beforeunload",Ee),()=>window.removeEventListener("beforeunload",Ee)}},[T,C]);const[V,Q]=_.useState(!1),[Z,ae]=_.useState(null),B=_.useRef(null),X=_.useRef(!1),{data:ne,isLoading:se}=at({queryKey:["github-backup-config"],queryFn:ue.getGitHubBackupConfig}),{data:be}=at({queryKey:["github-backup-status"],queryFn:ue.getGitHubBackupStatus,refetchInterval:me=>me.state.data?.is_running?500:1e4}),{data:xe}=at({queryKey:["github-backup-logs"],queryFn:()=>ue.getGitHubBackupLogs(20)}),{data:de}=at({queryKey:["cloud-status"],queryFn:ue.getCloudStatus}),{data:Pe}=at({queryKey:["printers"],queryFn:ue.getPrinters}),ie=dW({queries:(Pe??[]).map(me=>({queryKey:["printerStatus",me.id],queryFn:()=>ue.getPrinterStatus(me.id),staleTime:1e4,refetchInterval:3e4}))}),Ne=(Pe??[]).map((me,Ee)=>({printer:me,connected:ie[Ee]?.data?.connected??!1})),Oe=Ne.length,ge=Ne.filter(me=>me.connected).length,Ke=Oe>0&&ge===0,G=ge>0&&ge{ne&&(r(ne.repository_url),l(ne.branch),u(ne.schedule_enabled),f(ne.schedule_type),m(ne.backup_kprofiles),b(ne.backup_cloud_profiles),v(ne.backup_settings),N(ne.enabled),a(""),setTimeout(()=>{X.current=!0},100))},[ne]);const Y=_.useCallback(async(me=!1)=>{if(ne?.has_token)try{me&&i?(await ue.saveGitHubBackupConfig({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:p,backup_cloud_profiles:x,backup_settings:y,enabled:S}),a(""),e("Token updated")):(await ue.updateGitHubBackupConfig({repository_url:n,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:p,backup_cloud_profiles:x,backup_settings:y,enabled:S}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(Ee){e(`Failed to save: ${Ee.message}`,"error")}},[ne?.has_token,n,i,o,c,d,p,x,y,S,t,e]);_.useEffect(()=>{if(!(!X.current||!ne?.has_token))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{Y(!1)},500),()=>{B.current&&clearTimeout(B.current)}},[n,o,c,d,p,x,y,S,Y,ne?.has_token]),_.useEffect(()=>{if(!(!X.current||!ne?.has_token||!i))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{Y(!0)},1e3),()=>{B.current&&clearTimeout(B.current)}},[i,Y,ne?.has_token]);const ce=mt({mutationFn:me=>ue.saveGitHubBackupConfig(me),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),a(""),X.current=!0},onError:me=>{e(`Failed to save: ${me.message}`,"error")}}),q=mt({mutationFn:ue.triggerGitHubBackup,onSuccess:me=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),me.success?me.files_changed>0?e(`Backup complete - ${me.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${me.message}`,"error")},onError:me=>{e(`Backup failed: ${me.message}`,"error")}}),te=mt({mutationFn:()=>ue.clearGitHubBackupLogs(0),onSuccess:me=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${me.deleted} logs`)},onError:me=>{e(`Failed to clear logs: ${me.message}`,"error")}}),I=async()=>{Q(!0),ae(null);try{let me;if(i){if(!n){e("Enter repository URL","error"),Q(!1);return}me=await ue.testGitHubConnection(n,i)}else if(ne?.has_token)me=await ue.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),Q(!1);return}ae({success:me.success,message:me.message})}catch(me){ae({success:!1,message:me.message})}finally{Q(!1)}},fe=()=>{if(!n){e("Repository URL is required","error");return}if(!i){e("Access token is required","error");return}ce.mutate({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:p,backup_cloud_profiles:x,backup_settings:y,enabled:S})};return se?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 animate-spin text-bambu-green"})}):s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fP,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),ne&&de?.is_authenticated&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),s.jsx(On,{checked:S,onChange:N})]})]})}),s.jsx(Mt,{className:"space-y-4",children:de?.is_authenticated?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),s.jsx("input",{type:"text",value:n,onChange:me=>{r(me.target.value),ae(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"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",ne?.has_token&&s.jsx("span",{className:"text-green-400",children:"(saved)"})]}),s.jsx("input",{type:"password",value:i,onChange:me=>{a(me.target.value),ae(null)},placeholder:ne?.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),s.jsx("input",{type:"text",value:o,onChange:me=>l(me.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),s.jsxs("select",{value:c?d:"disabled",onChange:me=>{me.target.value==="disabled"?u(!1):(u(!0),f(me.target.value))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[s.jsx("option",{value:"disabled",children:"Manual only"}),s.jsx("option",{value:"hourly",children:"Hourly"}),s.jsx("option",{value:"daily",children:"Daily"}),s.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:`flex items-start gap-2 ${Ke?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:me=>m(me.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:Ke}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm ${Ke?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),Ke&&s.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:[s.jsx(Cn,{className:"w-3 h-3"}),"No printers connected"]}),G&&s.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:[s.jsx(Cn,{className:"w-3 h-3"}),ge,"/",Oe," connected"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:x,onChange:me=>b(me.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:!de?.is_authenticated}),s.jsxs("div",{children:[s.jsx("span",{className:`text-sm ${de?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:y,onChange:me=>v(me.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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white text-sm",children:"App Settings"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (excludes sensitive data)"})]})]})]})]}),s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[be?.configured&&s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:be.last_backup_at?s.jsxs(s.Fragment,{children:[s.jsxs("span",{children:["Last backup: ",mq(be.last_backup_at)]}),s.jsx(fq,{status:be.last_backup_status})]}):s.jsx("span",{children:"No backups yet"})}),be.next_scheduled_run&&s.jsxs("span",{className:"text-bambu-gray",children:[s.jsx(er,{className:"w-3 h-3 inline mr-1"}),"Next: ",mq(be.next_scheduled_run)]})]}),Z&&s.jsxs("div",{className:`text-sm flex items-center gap-1 ${Z.success?"text-green-400":"text-red-400"}`,children:[Z.success?s.jsx(Ar,{className:"w-4 h-4"}):s.jsx(Yi,{className:"w-4 h-4"}),Z.message]}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:be?.configured?s.jsx(s.Fragment,{children:q.isPending||be.is_running?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{className:"text-sm",children:be.progress||"Starting backup..."})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"primary",size:"sm",onClick:()=>q.mutate(),disabled:!ne?.enabled,children:[s.jsx(Is,{className:"w-4 h-4"}),"Backup Now"]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:I,disabled:V,children:[V?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Test"]})]})}):s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"primary",size:"sm",onClick:fe,disabled:ce.isPending||!n||!i,children:[ce.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Ar,{className:"w-4 h-4"}),"Enable Backup"]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:I,disabled:V||!n||!i,children:[V?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):s.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[s.jsx(Cn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),s.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),xe&&xe.length>0&&s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(q0,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),s.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>te.mutate(),disabled:te.isPending,children:[s.jsx(rn,{className:"w-4 h-4"}),"Clear"]})]})}),s.jsx(Mt,{children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[s.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),s.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),s.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),s.jsx("tbody",{children:xe.slice(0,10).map(me=>s.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[s.jsx("td",{className:"py-2 px-2 text-white",children:yKe(me.started_at)}),s.jsx("td",{className:"py-2 px-2",children:s.jsx(fq,{status:me.status})}),s.jsx("td",{className:"py-2 px-2",children:me.commit_sha?s.jsxs("a",{href:`${ne?.repository_url}/commit/${me.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[me.commit_sha.substring(0,7),s.jsx(Kr,{className:"w-3 h-3"})]}):s.jsx("span",{className:"text-bambu-gray",children:"-"})})]},me.id))})]})})})]})]}),s.jsx("div",{className:"space-y-6",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Nu,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Download Backup"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),s.jsxs(Te,{variant:"secondary",size:"sm",disabled:T||C,onClick:async()=>{k(!0),A("Preparing backup...");try{A("Creating backup archive... This may take a while for large archives.");const{blob:me,filename:Ee}=await ue.exportBackup();A("Downloading backup file...");const z=URL.createObjectURL(me),O=document.createElement("a");O.href=z,O.download=Ee,O.click(),URL.revokeObjectURL(z),e("Backup downloaded successfully")}catch(me){e(`Failed to create backup: ${me instanceof Error?me.message:"Unknown error"}`,"error")}finally{k(!1),A("")}},children:[s.jsx(yi,{className:"w-4 h-4"}),"Download"]})]}),s.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Restore Backup"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Replace all data from a backup file"})]}),s.jsx("input",{ref:K,type:"file",accept:".zip",className:"hidden",onChange:me=>{const Ee=me.target.files?.[0];Ee&&($(Ee),U(!0)),me.target.value=""}}),s.jsxs(Te,{variant:"secondary",size:"sm",disabled:C||T,onClick:()=>K.current?.click(),children:[s.jsx(Ua,{className:"w-4 h-4"}),"Restore"]})]}),j&&s.jsx("div",{className:`p-3 rounded-lg ${j.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[j.success?s.jsx(Ar,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):s.jsx(Yi,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:j.success?"text-green-200":"text-red-200",children:[j.message,j.success&&s.jsx("div",{className:"mt-2",children:s.jsxs(Te,{size:"sm",onClick:()=>window.location.reload(),children:[s.jsx(Rh,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),s.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Cn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-yellow-200",children:[s.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",s.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),R&&F&&s.jsx(Zn,{title:"Restore Backup",message:`Are you sure you want to restore from "${F.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()=>{U(!1),E(!0),H(null);try{A("Uploading backup file...");const me=await ue.importBackup(F);H(me),me.success?e("Backup restored. Please restart Bambuddy.","success"):e(me.message,"error")}catch(me){const Ee=me instanceof Error?me.message:"Failed to restore backup";H({success:!1,message:Ee}),e(Ee,"error")}finally{E(!1),A(""),$(null)}},onCancel:()=>{U(!1),$(null)}}),(T||C)&&s.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:s.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:[s.jsx("div",{className:"flex justify-center mb-4",children:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),s.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),s.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:T?"Creating Backup":"Restoring Backup"}),s.jsx("p",{className:"text-bambu-gray mb-4",children:D||(T?"Preparing...":"Processing...")}),s.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Cn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),s.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}const wKe={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 _Ke(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function p0(t,e,n=0){if(n>5)return"...";if(e.$ref)return p0(t,_Ke(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const a=p0(t,i,n+1);typeof a=="object"&&a!==null&&Object.assign(r,a)}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?[p0(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,a]of Object.entries(e.properties))r[i]=p0(t,a,n+1);return r}return{};default:return null}}function SKe({path:t,method:e,spec:n,schema:r,apiKey:i}){const[a,o]=_.useState(!1),[l,c]=_.useState({}),[u,d]=_.useState(""),[f,p]=_.useState(null),[m,x]=_.useState(!1),[b,y]=_.useState(!1);_.useEffect(()=>{if(a&&n.parameters){const D={};for(const A of n.parameters)A.schema?.default!==void 0&&(D[A.name]=String(A.schema.default));c(A=>({...D,...A}))}},[a,n.parameters]),_.useEffect(()=>{if(a&&n.requestBody?.content?.["application/json"]?.schema&&!u){const D=n.requestBody.content["application/json"].schema,A=p0(r,D);d(JSON.stringify(A,null,2))}},[a,n.requestBody,r,u]);const S=(()=>{const D=[];for(const A of n.parameters||[])if(A.in==="path"||A.required){const R=l[A.name];(R===void 0||R==="")&&D.push(A.name)}return D})(),N=async()=>{if(S.length>0){p({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${S.join(", ")}`,duration:0});return}x(!0),p(null);try{let D=t;const A=new URLSearchParams;for(const ae of n.parameters||[]){const B=l[ae.name];B!==void 0&&B!==""&&(ae.in==="path"?D=D.replace(`{${ae.name}}`,encodeURIComponent(B)):ae.in==="query"&&A.append(ae.name,B))}const R=A.toString(),U=`${D}${R?`?${R}`:""}`,F={"Content-Type":"application/json"};i&&(F["X-API-Key"]=i);const $={method:e.toUpperCase(),headers:F};["post","put","patch"].includes(e)&&u&&($.body=u);const j=performance.now(),H=await fetch(U,$),K=Math.round(performance.now()-j),V={};H.headers.forEach((ae,B)=>{V[B]=ae});let Q;H.headers.get("content-type")?.includes("application/json")?Q=await H.json():Q=await H.text(),p({status:H.status,statusText:H.statusText,headers:V,body:Q,duration:K})}catch(D){p({status:0,statusText:"Network Error",headers:{},body:D instanceof Error?D.message:"Unknown error",duration:0})}finally{x(!1)}},T=async()=>{if(f){const D=typeof f.body=="string"?f.body:JSON.stringify(f.body,null,2);try{await navigator.clipboard.writeText(D),y(!0),setTimeout(()=>y(!1),2e3)}catch{const A=document.createElement("textarea");A.value=D,A.style.position="fixed",A.style.left="-999999px",document.body.appendChild(A),A.select(),document.execCommand("copy"),document.body.removeChild(A),y(!0),setTimeout(()=>y(!1),2e3)}}},k=(n.parameters||[]).filter(D=>D.in==="path"),C=(n.parameters||[]).filter(D=>D.in==="query"),E=["post","put","patch"].includes(e)&&n.requestBody;return s.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>o(!a),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[a?s.jsx(ei,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):s.jsx(gs,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),s.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${wKe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),s.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&s.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),a&&s.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&s.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),k.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),s.jsx("div",{className:"space-y-2",children:k.map(D=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[D.name,D.required&&s.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),s.jsx("input",{type:"text",value:l[D.name]||"",onChange:A=>c(R=>({...R,[D.name]:A.target.value})),placeholder:D.description||D.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"})]},D.name))})]}),C.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),s.jsx("div",{className:"space-y-2",children:C.map(D=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[D.name,D.required&&s.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),D.schema?.enum?s.jsxs("select",{value:l[D.name]||"",onChange:A=>c(R=>({...R,[D.name]:A.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:[s.jsx("option",{value:"",children:"-- Select --"}),D.schema.enum.map(A=>s.jsx("option",{value:A,children:A},A))]}):s.jsx("input",{type:"text",value:l[D.name]||"",onChange:A=>c(R=>({...R,[D.name]:A.target.value})),placeholder:D.description||D.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"})]},D.name))})]}),E&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),s.jsx("textarea",{value:u,onChange:D=>d(D.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..."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Te,{onClick:N,disabled:m,children:[m?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Is,{className:"w-4 h-4"}),"Execute"]}),S.length>0&&s.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[s.jsx(Hi,{className:"w-3 h-3"}),"Fill in: ",S.join(", ")]})]}),f&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",s.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${f.status>=200&&f.status<300?"bg-green-500/20 text-green-400":f.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[f.status," ",f.statusText]}),s.jsxs("span",{className:"text-xs text-bambu-gray",children:[f.duration,"ms"]})]}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:T,children:b?s.jsx(Ar,{className:"w-3 h-3 text-green-400"}):s.jsx(Fl,{className:"w-3 h-3"})})]}),s.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 f.body=="string"?f.body:JSON.stringify(f.body,null,2)})]})]})]})}function MKe({apiKey:t=""}){const[e,n]=_.useState(null),[r,i]=_.useState(!0),[a,o]=_.useState(null),[l,c]=_.useState(new Set),[u,d]=_.useState("");if(_.useEffect(()=>{async function y(){try{const v=await fetch("/openapi.json");if(!v.ok)throw new Error("Failed to fetch OpenAPI schema");const S=await v.json();n(S)}catch(v){o(v instanceof Error?v.message:"Unknown error")}finally{i(!1)}}y()},[]),r)return s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(a||!e)return s.jsx(_t,{children:s.jsx(Mt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-red-400",children:[s.jsx(Hi,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),s.jsx("p",{children:"Failed to load API schema"}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a})]})})});const f={};for(const[y,v]of Object.entries(e.paths))for(const[S,N]of Object.entries(v)){if(S==="parameters")continue;const T=N.tags||["Other"];for(const k of T)f[k]||(f[k]=[]),f[k].push({path:y,method:S,spec:N})}const p=Object.entries(f).map(([y,v])=>{if(!u)return{tag:y,endpoints:v};const S=v.filter(({path:N,method:T,spec:k})=>{const C=u.toLowerCase();return N.toLowerCase().includes(C)||T.toLowerCase().includes(C)||(k.summary?.toLowerCase()||"").includes(C)||(k.description?.toLowerCase()||"").includes(C)});return{tag:y,endpoints:S}}).filter(({endpoints:y})=>y.length>0).sort((y,v)=>y.tag.localeCompare(v.tag)),m=y=>{c(v=>{const S=new Set(v);return S.has(y)?S.delete(y):S.add(y),S})},x=()=>{c(new Set(p.map(y=>y.tag)))},b=()=>{c(new Set)};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("div",{className:"flex-1",children:s.jsx("input",{type:"text",value:u,onChange:y=>d(y.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"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Te,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:b,children:"Collapse All"}),s.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[s.jsx(Kr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:[p.reduce((y,v)=>y+v.endpoints.length,0)," endpoints in ",p.length," categories"]}),s.jsx("div",{className:"space-y-3",children:p.map(({tag:y,endpoints:v})=>s.jsxs(_t,{children:[s.jsx("button",{onClick:()=>m(y),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:s.jsxs("div",{className:"flex items-center gap-2",children:[l.has(y)?s.jsx(ei,{className:"w-5 h-5 text-bambu-gray"}):s.jsx(gs,{className:"w-5 h-5 text-bambu-gray"}),s.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:y.replace(/-/g," ")}),s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:v.length})]})}),l.has(y)&&s.jsx(Mt,{className:"pt-0 space-y-2",children:v.map(({path:S,method:N,spec:T})=>s.jsx(SKe,{path:S,method:N,spec:T,schema:e,apiKey:t},`${N}-${S}`))})]},y))})]})}const NKe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"];function kKe(){const t=an(),e=Nc(),[n,r]=wR(),{t:i,i18n:a}=Hn(),{showToast:o}=$n(),{authEnabled:l,user:c,refreshAuth:u}=Ai(),{mode:d,darkStyle:f,darkBackground:p,darkAccent:m,lightStyle:x,lightBackground:b,lightAccent:y,setDarkStyle:v,setDarkBackground:S,setDarkAccent:N,setLightStyle:T,setLightBackground:k,setLightAccent:C}=Oh(),[E,D]=_.useState(null),[A,R]=_.useState(!1),[U,F]=_.useState(null),[$,j]=_.useState(!1),[H,K]=_.useState(null),[V,Q]=_.useState(null),[Z,ae]=_.useState(!1),[B,X]=_.useState(OW()),ne=n.get("tab"),se=ne&&NKe.includes(ne)?ne:"general",[be,xe]=_.useState(se),de=oe=>{xe(oe),oe==="general"?n.delete("tab"):n.set("tab",oe),r(n,{replace:!0})},[Pe,ie]=_.useState(!1),[Ne,Oe]=_.useState(""),[ge,Ke]=_.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[G,Y]=_.useState(null),[ce,q]=_.useState(null),[te,I]=_.useState(""),[fe,me]=_.useState(!1),[Ee,z]=_.useState(!1),[O,ee]=_.useState(null),[le,_e]=_.useState(!1),[we,re]=_.useState(!1),[Fe,He]=_.useState(!1),[Ve,$e]=_.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[ye,je]=_.useState(!1),[Be,Se]=_.useState(!1),[Xe,Me]=_.useState(!1),[tt,ke]=_.useState(null),[We,ze]=_.useState(null),[W,De]=_.useState(null),[Ye,xt]=_.useState(!1),[ft,Bt]=_.useState({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]}),[Lt,vn]=_.useState(!1),[Jt,ir]=_.useState(null),[fr,Dn]=_.useState(null),[ln,mr]=_.useState({name:"",description:"",permissions:[]}),[Fn,Xn]=_.useState(new Set),[bn,wi]=_.useState(null),[Ba,Ae]=_.useState(!1),[Ze,st]=_.useState({}),[lt,ot]=_.useState({}),Et=oe=>{X(oe),jfe(oe),o(i("settings.toast.settingsSaved"),"success")},he=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:pe,isLoading:Ie}=at({queryKey:["settings"],queryFn:ue.getSettings}),{data:Le,isLoading:Ce}=at({queryKey:["smart-plugs"],queryFn:ue.getSmartPlugs}),{data:ut,isLoading:St}=at({queryKey:["smart-plugs-energy",Le?.map(oe=>oe.id)],queryFn:async()=>{if(!Le||Le.length===0)return null;const oe=await Promise.all(Le.filter(is=>is.enabled).map(async is=>{try{const as=await ue.getSmartPlugStatus(is.id);return{plug:is,status:as}}catch{return{plug:is,status:null}}}));let wt=0,Rn=0,Jn=0,No=0,Ju=0;for(const{plug:is,status:as}of oe){const $x=is.plug_type==="mqtt"&&as?.energy?.power!=null;(as?.reachable||$x)&&as?.energy&&(Ju++,as.energy?.power!=null&&(wt+=as.energy.power),as.energy?.today!=null&&(Rn+=as.energy.today),as.energy?.yesterday!=null&&(Jn+=as.energy.yesterday),as.energy?.total!=null&&(No+=as.energy.total))}return{totalPower:wt,totalToday:Rn,totalYesterday:Jn,totalLifetime:No,reachableCount:Ju,totalPlugs:Le.filter(is=>is.enabled).length}},enabled:be==="plugs"&&!!Le&&Le.length>0,refetchInterval:be==="plugs"?1e4:!1}),{data:At,isLoading:Tt}=at({queryKey:["notification-providers"],queryFn:ue.getNotificationProviders}),{data:Ft,isLoading:Pt}=at({queryKey:["api-keys"],queryFn:ue.getAPIKeys}),Nt=mt({mutationFn:oe=>ue.createAPIKey(oe),onSuccess:oe=>{Y(oe.key||null),ie(!1),Oe(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:oe=>{o(`Failed to create API key: ${oe.message}`,"error")}}),en=mt({mutationFn:oe=>ue.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:Ht}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:dn,isLoading:cn}=at({queryKey:["notification-templates"],queryFn:ue.getNotificationTemplates}),{data:Sn}=at({queryKey:["virtual-printer-settings"],queryFn:p1.getSettings,refetchInterval:1e4}),Gt=Sn?.status?.running??!1,{data:sn}=at({queryKey:["ffmpeg-status"],queryFn:ue.checkFfmpeg}),{data:un}=at({queryKey:["version"],queryFn:ue.getVersion}),{data:Yt,refetch:nr,isRefetching:jn}=at({queryKey:["updateCheck"],queryFn:ue.checkForUpdates,staleTime:300*1e3}),{data:ii,refetch:rr}=at({queryKey:["updateStatus"],queryFn:ue.getUpdateStatus,refetchInterval:oe=>{const wt=oe.state.data;return wt?.status==="downloading"||wt?.status==="installing"?1e3:!1}}),{data:cr}=at({queryKey:["mqtt-status"],queryFn:ue.getMQTTStatus,refetchInterval:be==="network"?5e3:!1}),{data:et}=at({queryKey:["github-backup-status"],queryFn:ue.getGitHubBackupStatus}),{data:jt}=at({queryKey:["cloud-status"],queryFn:ue.getCloudStatus}),{hasPermission:qt}=Ai(),{data:yt=[],isLoading:wn}=at({queryKey:["users"],queryFn:()=>ue.getUsers(),enabled:l&&qt("users:read")}),{data:Fr=[],isLoading:Yr}=at({queryKey:["groups"],queryFn:()=>ue.getGroups(),enabled:l&&qt("groups:read")}),{data:Br}=at({queryKey:["permissions"],queryFn:()=>ue.getPermissions(),enabled:l&&qt("groups:read")}),Ws=mt({mutationFn:oe=>ue.createUser(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:oe=>{o(oe.message,"error")}}),tn=mt({mutationFn:({id:oe,data:wt})=>ue.updateUser(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:oe=>{o(oe.message,"error")}}),on=mt({mutationFn:({id:oe,deleteItems:wt})=>ue.deleteUser(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),ze(null),De(null)},onError:oe=>{o(oe.message,"error")}}),_i=async oe=>{ze(oe),xt(!0);try{const wt=await ue.getUserItemsCount(oe);De(wt)}catch{De({archives:0,queue_items:0,library_files:0})}finally{xt(!1)}},Ss=mt({mutationFn:oe=>ue.createGroup(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),vn(!1),la(),o(i("settings.toast.groupCreated"))},onError:oe=>{o(oe.message,"error")}}),_o=mt({mutationFn:({id:oe,data:wt})=>ue.updateGroup(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),ir(null),la(),o(i("settings.toast.groupUpdated"))},onError:oe=>{o(oe.message,"error")}}),So=mt({mutationFn:oe=>ue.deleteGroup(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:oe=>{o(oe.message,"error")}}),Mo=()=>{if(!ft.username||!ft.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(ft.password!==ft.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(ft.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}Ws.mutate({username:ft.username,password:ft.password,role:ft.role,group_ids:ft.group_ids.length>0?ft.group_ids:void 0})},Ms=oe=>{if(ft.password){if(ft.password!==ft.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(ft.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}const wt={username:ft.username||void 0,password:ft.password||void 0,role:ft.role,group_ids:ft.group_ids};wt.password||delete wt.password,tn.mutate({id:oe,data:wt})},Si=oe=>{ke(oe.id),Bt({username:oe.username,password:"",confirmPassword:"",role:oe.role,group_ids:oe.groups?.map(wt=>wt.id)||[]}),Me(!0)},Ks=oe=>{Bt(wt=>({...wt,group_ids:wt.group_ids.includes(oe)?wt.group_ids.filter(Rn=>Rn!==oe):[...wt.group_ids,oe]}))},la=()=>{mr({name:"",description:"",permissions:[]}),Xn(new Set)},Hr=()=>{if(!ln.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}Ss.mutate({name:ln.name,description:ln.description||void 0,permissions:ln.permissions})},Ux=()=>{if(Jt){if(!ln.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}_o.mutate({id:Jt.id,data:{name:ln.name!==Jt.name?ln.name:void 0,description:ln.description,permissions:ln.permissions}})}},$h=oe=>{ir(oe),mr({name:oe.name,description:oe.description||"",permissions:oe.permissions});const wt=new Set;Br?.categories.forEach(Rn=>{Rn.permissions.some(Jn=>oe.permissions.includes(Jn.value))&&wt.add(Rn.name)}),Xn(wt)},$l=oe=>{Xn(wt=>{const Rn=new Set(wt);return Rn.has(oe)?Rn.delete(oe):Rn.add(oe),Rn})},zx=oe=>{mr(wt=>{const Rn=wt.permissions.includes(oe)?wt.permissions.filter(Jn=>Jn!==oe):[...wt.permissions,oe];return{...wt,permissions:Rn}})},Dm=(oe,wt)=>{mr(Rn=>{const Jn=oe.permissions.map(is=>is.value),No=Rn.permissions.filter(is=>!Jn.includes(is)),Ju=wt?[...No,...Jn]:No;return{...Rn,permissions:Ju}})},Rm=oe=>oe.permissions.every(wt=>ln.permissions.includes(wt.value)),Vh=oe=>{const wt=oe.permissions.filter(Rn=>ln.permissions.includes(Rn.value));return wt.length>0&&wt.length{oe.is_docker?o(oe.message,"error"):rr()}}),[Cc,ca]=_.useState(null),pl=mt({mutationFn:ue.testAllNotificationProviders,onSuccess:oe=>{ca(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")}}),Vl=mt({mutationFn:async oe=>{if(!Le)return{success:0,failed:0};const wt=Le.filter(Jn=>Jn.enabled),Rn=await Promise.all(wt.map(async Jn=>{try{return await ue.controlSmartPlug(Jn.id,oe),{success:!0}}catch{return{success:!1}}}));return{success:Rn.filter(Jn=>Jn.success).length,failed:Rn.filter(Jn=>!Jn.success).length}},onSuccess:(oe,wt)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),oe.failed===0?o(`All ${oe.success} plugs turned ${wt}`,"success"):o(`${oe.success} plugs turned ${wt}, ${oe.failed} failed`,"error")},onError:oe=>{o(`Failed: ${oe.message}`,"error")}}),gl=_.useRef(null),Om=_.useRef(!1),Lm=_.useRef(!0);_.useEffect(()=>{if(pe&&!E){const oe={...pe,external_url:pe.external_url||window.location.origin};D(oe),setTimeout(()=>{Lm.current=!1},100)}},[pe,E]);const Fm=mt({mutationFn:ue.updateSettings,onSuccess:oe=>{t.setQueryData(["settings"],oe),D(oe),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:oe=>{o(`Failed to save: ${oe.message}`,"error")},onSettled:()=>{Om.current=!1}}),Zu=mt({mutationFn:({id:oe,data:wt})=>ue.updatePrinter(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:oe=>{o(`Failed to update printer: ${oe.message}`,"error")}});_.useEffect(()=>{if(!(Lm.current||!E||!pe||!(pe.auto_archive!==E.auto_archive||pe.save_thumbnails!==E.save_thumbnails||pe.capture_finish_photo!==E.capture_finish_photo||pe.default_filament_cost!==E.default_filament_cost||pe.currency!==E.currency||pe.energy_cost_per_kwh!==E.energy_cost_per_kwh||pe.energy_tracking_mode!==E.energy_tracking_mode||pe.check_updates!==E.check_updates||(pe.check_printer_firmware??!0)!==(E.check_printer_firmware??!0)||pe.notification_language!==E.notification_language||pe.ams_humidity_good!==E.ams_humidity_good||pe.ams_humidity_fair!==E.ams_humidity_fair||pe.ams_temp_good!==E.ams_temp_good||pe.ams_temp_fair!==E.ams_temp_fair||pe.ams_history_retention_days!==E.ams_history_retention_days||pe.per_printer_mapping_expanded!==E.per_printer_mapping_expanded||pe.date_format!==E.date_format||pe.time_format!==E.time_format||pe.default_printer_id!==E.default_printer_id||pe.ftp_retry_enabled!==E.ftp_retry_enabled||pe.ftp_retry_count!==E.ftp_retry_count||pe.ftp_retry_delay!==E.ftp_retry_delay||pe.ftp_timeout!==E.ftp_timeout||pe.mqtt_enabled!==E.mqtt_enabled||pe.mqtt_broker!==E.mqtt_broker||pe.mqtt_port!==E.mqtt_port||pe.mqtt_username!==E.mqtt_username||pe.mqtt_password!==E.mqtt_password||pe.mqtt_topic_prefix!==E.mqtt_topic_prefix||pe.mqtt_use_tls!==E.mqtt_use_tls||pe.external_url!==E.external_url||pe.ha_enabled!==E.ha_enabled||pe.ha_url!==E.ha_url||pe.ha_token!==E.ha_token||(pe.library_archive_mode??"ask")!==(E.library_archive_mode??"ask")||Number(pe.library_disk_warning_gb??5)!==Number(E.library_disk_warning_gb??5)||(pe.camera_view_mode??"window")!==(E.camera_view_mode??"window")||pe.prometheus_enabled!==E.prometheus_enabled||pe.prometheus_token!==E.prometheus_token))&&!Om.current)return gl.current&&clearTimeout(gl.current),gl.current=setTimeout(()=>{if(Om.current)return;Om.current=!0;const wt={auto_archive:E.auto_archive,save_thumbnails:E.save_thumbnails,capture_finish_photo:E.capture_finish_photo,default_filament_cost:E.default_filament_cost,currency:E.currency,energy_cost_per_kwh:E.energy_cost_per_kwh,energy_tracking_mode:E.energy_tracking_mode,check_updates:E.check_updates,check_printer_firmware:E.check_printer_firmware,notification_language:E.notification_language,ams_humidity_good:E.ams_humidity_good,ams_humidity_fair:E.ams_humidity_fair,ams_temp_good:E.ams_temp_good,ams_temp_fair:E.ams_temp_fair,ams_history_retention_days:E.ams_history_retention_days,per_printer_mapping_expanded:E.per_printer_mapping_expanded,date_format:E.date_format,time_format:E.time_format,default_printer_id:E.default_printer_id,ftp_retry_enabled:E.ftp_retry_enabled,ftp_retry_count:E.ftp_retry_count,ftp_retry_delay:E.ftp_retry_delay,ftp_timeout:E.ftp_timeout,mqtt_enabled:E.mqtt_enabled,mqtt_broker:E.mqtt_broker,mqtt_port:E.mqtt_port,mqtt_username:E.mqtt_username,mqtt_password:E.mqtt_password,mqtt_topic_prefix:E.mqtt_topic_prefix,mqtt_use_tls:E.mqtt_use_tls,external_url:E.external_url,ha_enabled:E.ha_enabled,ha_url:E.ha_url,ha_token:E.ha_token,library_archive_mode:E.library_archive_mode,library_disk_warning_gb:E.library_disk_warning_gb,camera_view_mode:E.camera_view_mode,prometheus_enabled:E.prometheus_enabled,prometheus_token:E.prometheus_token};Fm.mutate(wt)},500),()=>{gl.current&&clearTimeout(gl.current)}},[E,pe,Fm]);const hn=_.useCallback((oe,wt)=>{D(Rn=>Rn?{...Rn,[oe]:wt}:null)},[]),Sv=async(oe,wt,Rn)=>{if(!wt){o(i("settings.toast.enterCameraUrl"),"error");return}ot(Jn=>({...Jn,[oe]:!0})),st(Jn=>({...Jn,[oe]:null}));try{const Jn=await ue.testExternalCamera(oe,wt,Rn);st(No=>({...No,[oe]:Jn})),Jn.success?o(i("settings.toast.cameraConnected",{resolution:Jn.resolution||""}),"success"):o(Jn.error||i("settings.toast.connectionFailed"),"error")}catch(Jn){const No=Jn instanceof Error?Jn.message:i("settings.toast.testFailed");st(Ju=>({...Ju,[oe]:{success:!1,error:No}})),o(No,"error")}finally{ot(Jn=>({...Jn,[oe]:!1}))}},[Bx,Mv]=_.useState({}),Hx=_.useRef({}),Im=_.useRef(new Set);_.useEffect(()=>{if(Ht){const oe={};Ht.forEach(wt=>{wt.external_camera_url&&!Im.current.has(wt.id)&&(oe[wt.id]=wt.external_camera_url,Im.current.add(wt.id))}),Object.keys(oe).length>0&&Mv(wt=>({...wt,...oe}))}},[Ht]);const G2=(oe,wt)=>{Mv(Rn=>({...Rn,[oe]:wt})),Hx.current[oe]&&clearTimeout(Hx.current[oe]),Hx.current[oe]=setTimeout(()=>{Zu.mutate({id:oe,data:{external_camera_url:wt||null}})},800)},Nv=(oe,wt)=>{const Rn={};wt.type!==void 0&&(Rn.external_camera_type=wt.type||null),wt.enabled!==void 0&&(Rn.external_camera_enabled=wt.enabled),Zu.mutate({id:oe,data:Rn})};return Ie||!E?s.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s.jsxs("div",{className:"p-4 md:p-8",children:[s.jsxs("div",{className:"mb-8",children:[s.jsx("h1",{className:"text-2xl font-bold text-white",children:i("settings.title")}),s.jsx("p",{className:"text-bambu-gray",children:i("settings.configureBambuddy")})]}),s.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary overflow-x-auto",children:[s.jsx("button",{onClick:()=>de("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${be==="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")}),s.jsxs("button",{onClick:()=>de("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(tl,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),Le&&Le.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Le.length})]}),s.jsxs("button",{onClick:()=>de("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(wg,{className:"w-4 h-4"}),i("settings.tabs.notifications"),At&&At.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:At.length})]}),s.jsxs("button",{onClick:()=>de("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(hue,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),s.jsxs("button",{onClick:()=>de("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Sg,{className:"w-4 h-4"}),i("settings.tabs.network"),s.jsx("span",{className:`w-2 h-2 rounded-full ${cr?.enabled?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>de("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx($o,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),Ft&&Ft.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ft.length})]}),s.jsxs("button",{onClick:()=>de("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Ur,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),s.jsx("span",{className:`w-2 h-2 rounded-full ${Gt?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>de("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(mg,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&s.jsx("span",{className:`w-2 h-2 rounded-full ${l?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>de("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Nu,{className:"w-4 h-4"}),i("settings.tabs.backup"),s.jsx("span",{className:`w-2 h-2 rounded-full ${jt?.is_authenticated&&et?.configured&&et?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),be==="general"&&s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[s.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(sh,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),s.jsxs("div",{className:"relative",children:[s.jsx("select",{value:a.language,onChange:oe=>{a.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:mz.map(oe=>s.jsxs("option",{value:oe.code,children:[oe.nativeName," (",oe.name,")"]},oe.code))}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),s.jsxs("div",{className:"relative",children:[s.jsx("select",{value:B,onChange:oe=>Et(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:K0.map(oe=>s.jsx("option",{value:oe.to,children:i(oe.labelKey)},oe.id))}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),s.jsxs("div",{className:"relative",children:[s.jsxs("select",{value:E.date_format||"system",onChange:oe=>hn("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:[s.jsx("option",{value:"system",children:i("settings.systemDefault")}),s.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),s.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),s.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),s.jsxs("div",{className:"relative",children:[s.jsxs("select",{value:E.time_format||"system",onChange:oe=>hn("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:[s.jsx("option",{value:"system",children:i("settings.systemDefault")}),s.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),s.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),s.jsxs("div",{className:"relative",children:[s.jsxs("select",{value:E.default_printer_id??"",onChange:oe=>hn("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:[s.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),Ht?.map(oe=>s.jsx("option",{value:oe.id,children:oe.name},oe.id))]}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:he,children:[s.jsx(Rh,{className:"w-4 h-4"}),"Reset"]})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(SW,{className:"w-5 h-5"}),"Appearance"]})}),s.jsxs(Mt,{className:"space-y-6",children:[s.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:[s.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&s.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),s.jsxs("select",{value:p,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:[s.jsx("option",{value:"neutral",children:"Neutral"}),s.jsx("option",{value:"warm",children:"Warm"}),s.jsx("option",{value:"cool",children:"Cool"}),s.jsx("option",{value:"oled",children:"OLED Black"}),s.jsx("option",{value:"slate",children:"Slate Blue"}),s.jsx("option",{value:"forest",children:"Forest Green"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),s.jsxs("select",{value:m,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:[s.jsx("option",{value:"green",children:"Green"}),s.jsx("option",{value:"teal",children:"Teal"}),s.jsx("option",{value:"blue",children:"Blue"}),s.jsx("option",{value:"orange",children:"Orange"}),s.jsx("option",{value:"purple",children:"Purple"}),s.jsx("option",{value:"red",children:"Red"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),s.jsxs("select",{value:f,onChange:oe=>{v(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:[s.jsx("option",{value:"classic",children:"Classic"}),s.jsx("option",{value:"glow",children:"Glow"}),s.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),s.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:[s.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&s.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),s.jsxs("select",{value:b,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:[s.jsx("option",{value:"neutral",children:"Neutral"}),s.jsx("option",{value:"warm",children:"Warm"}),s.jsx("option",{value:"cool",children:"Cool"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),s.jsxs("select",{value:y,onChange:oe=>{C(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:[s.jsx("option",{value:"green",children:"Green"}),s.jsx("option",{value:"teal",children:"Teal"}),s.jsx("option",{value:"blue",children:"Blue"}),s.jsx("option",{value:"orange",children:"Orange"}),s.jsx("option",{value:"purple",children:"Purple"}),s.jsx("option",{value:"red",children:"Red"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),s.jsxs("select",{value:x,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:[s.jsx("option",{value:"classic",children:"Classic"}),s.jsx("option",{value:"glow",children:"Glow"}),s.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Auto-archive prints"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.auto_archive,onChange:oe=>hn("auto_archive",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.save_thumbnails,onChange:oe=>hn("save_thumbnails",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.capture_finish_photo,onChange:oe=>hn("capture_finish_photo",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.capture_finish_photo&&sn&&!sn.installed&&s.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[s.jsx(Cn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm",children:[s.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),s.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",s.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",s.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),s.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(OR,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),s.jsxs("select",{value:E.camera_view_mode??"window",onChange:oe=>hn("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:[s.jsx("option",{value:"window",children:i("settings.newWindow")}),s.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:E.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[s.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),s.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."}),Ht&&Ht.length>0?s.jsx("div",{className:"space-y-3",children:Ht.map(oe=>s.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-white font-medium text-sm",children:oe.name}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:oe.external_camera_enabled,onChange:wt=>Nv(oe.id,{enabled:wt.target.checked}),className:"sr-only peer"}),s.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&&s.jsxs("div",{className:"space-y-2 mt-2",children:[s.jsx("input",{type:"text",placeholder:oe.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Bx[oe.id]??oe.external_camera_url??"",onChange:wt=>G2(oe.id,wt.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"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("select",{value:oe.external_camera_type||"mjpeg",onChange:wt=>Nv(oe.id,{type:wt.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:[s.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),s.jsx("option",{value:"rtsp",children:"RTSP Stream"}),s.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),s.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),s.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>Sv(oe.id,Bx[oe.id]??oe.external_camera_url??"",oe.external_camera_type||"mjpeg"),disabled:lt[oe.id]||!(Bx[oe.id]??oe.external_camera_url),children:lt[oe.id]?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):"Test"})]}),Ze[oe.id]&&s.jsx("div",{className:`text-xs flex items-center gap-1 ${Ze[oe.id]?.success?"text-green-500":"text-red-500"}`,children:Ze[oe.id]?.success?s.jsxs(s.Fragment,{children:[s.jsx(Ar,{className:"w-3 h-3"}),"Connected",Ze[oe.id]?.resolution&&` (${Ze[oe.id]?.resolution})`]}):s.jsxs(s.Fragment,{children:[s.jsx(Yi,{className:"w-3 h-3"}),Ze[oe.id]?.error||i("settings.toast.connectionFailed")]})})]})]},oe.id))}):s.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:E.default_filament_cost,onChange:oe=>hn("default_filament_cost",parseFloat(oe.target.value)||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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),s.jsxs("select",{value:E.currency,onChange:oe=>hn("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:[s.jsx("option",{value:"USD",children:"USD ($)"}),s.jsx("option",{value:"EUR",children:"EUR (€)"}),s.jsx("option",{value:"GBP",children:"GBP (£)"}),s.jsx("option",{value:"CHF",children:"CHF (Fr.)"}),s.jsx("option",{value:"JPY",children:"JPY (¥)"}),s.jsx("option",{value:"CNY",children:"CNY (¥)"}),s.jsx("option",{value:"CAD",children:"CAD ($)"}),s.jsx("option",{value:"AUD",children:"AUD ($)"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:E.energy_cost_per_kwh,onChange:oe=>hn("energy_cost_per_kwh",parseFloat(oe.target.value)||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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),s.jsxs("select",{value:E.energy_tracking_mode||"total",onChange:oe=>hn("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:[s.jsx("option",{value:"print",children:i("settings.printsOnly")}),s.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:E.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Ls,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),s.jsxs("select",{value:E.library_archive_mode??"ask",onChange:oe=>hn("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:[s.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),s.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),s.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:E.library_disk_warning_gb??5,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),s.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[s.jsx(xKe,{}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.check_updates,onChange:oe=>hn("check_updates",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.check_printer_firmware??!0,onChange:oe=>hn("check_printer_firmware",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",un?.version||"..."]})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>nr(),disabled:jn,children:[jn?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Check now"]})]}),Yt?.update_available?s.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{children:[s.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",Yt.latest_version]}),Yt.release_name&&Yt.release_name!==Yt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:Yt.release_name})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[Yt.release_notes&&s.jsx("button",{onClick:()=>_e(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),Yt.release_url&&s.jsx("a",{href:Yt.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:s.jsx(Kr,{className:"w-4 h-4"})})]})]}),ii?.status==="downloading"||ii?.status==="installing"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{children:ii.message})]}),s.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:s.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${ii.progress}%`}})})]}):ii?.status==="complete"?s.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:ii.message}):ii?.status==="error"?s.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:ii.error||ii.message}):Yt?.is_docker?s.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),s.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"})]}):s.jsxs(Te,{className:"mt-3",onClick:()=>Qu.mutate(),disabled:Qu.isPending,children:[Qu.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(yi,{className:"w-4 h-4"}),"Install Update"]})]}):Yt?.error?s.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: ",Yt.error]}):Yt&&!Yt.update_available?s.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>me(!0),children:[s.jsx(rn,{className:"w-4 h-4"}),i("common.clear")]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>z(!0),children:[s.jsx(rn,{className:"w-4 h-4"}),"Reset"]})]}),s.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Backup & Restore"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>de("backup"),children:[s.jsx(Nu,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),be==="network"&&E&&s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[s.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(sh,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),s.jsx("input",{type:"text",value:E.external_url??"",onChange:oe=>hn("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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Dr,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.ftp_retry_enabled??!0,onChange:oe=>hn("ftp_retry_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.ftp_retry_enabled&&s.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"1",max:"10",value:E.ftp_retry_count??3,onChange:oe=>hn("ftp_retry_count",Math.min(10,Math.max(1,parseInt(oe.target.value)||3))),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"}),s.jsx("span",{className:"text-bambu-gray",children:"times"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Number of retry attempts before giving up (1-10)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"1",max:"30",value:E.ftp_retry_delay??2,onChange:oe=>hn("ftp_retry_delay",Math.min(30,Math.max(1,parseInt(oe.target.value)||2))),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"}),s.jsx("span",{className:"text-bambu-gray",children:"seconds"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Wait time between retries (1-30)"})]})]}),s.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"10",max:"120",value:E.ftp_timeout??30,onChange:oe=>hn("ftp_timeout",Math.min(120,Math.max(10,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"}),s.jsx("span",{className:"text-bambu-gray",children:"seconds"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Socket timeout for slow connections. Increase for A1/A1 Mini printers with weak WiFi (10-120)"})]})]})]})]}),s.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(fN,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),E.ha_enabled&&bn&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${bn.success?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${bn.success?"text-green-400":"text-red-400"}`,children:bn.success?"Connected":"Disconnected"})]})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.ha_enabled??!1,onChange:oe=>hn("ha_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.ha_enabled&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Home Assistant URL"}),s.jsx("input",{type:"text",value:E.ha_url??"",onChange:oe=>hn("ha_url",oe.target.value),placeholder:"http://192.168.1.100:8123",className:"w-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.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Long-Lived Access Token"}),s.jsx("input",{type:"password",value:E.ha_token??"",onChange:oe=>hn("ha_token",oe.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",className:"w-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.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),E.ha_url&&E.ha_token&&s.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:s.jsxs(Te,{variant:"secondary",size:"sm",disabled:Ba,onClick:async()=>{Ae(!0),wi(null);try{const oe=await ue.testHAConnection(E.ha_url,E.ha_token);wi(oe)}catch(oe){wi({success:!1,message:null,error:oe instanceof Error?oe.message:i("common.unknownError")})}finally{Ae(!1)}},children:[Ba?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Sg,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Sg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),cr?.enabled&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${cr.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${cr.connected?"text-green-400":"text-red-400"}`,children:cr.connected?"Connected":"Disconnected"})]})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.mqtt_enabled??!1,onChange:oe=>hn("mqtt_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.mqtt_enabled&&s.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),s.jsx("input",{type:"text",value:E.mqtt_broker??"",onChange:oe=>hn("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"})]}),s.jsxs("div",{className:"flex items-end gap-4",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),s.jsx("input",{type:"number",min:"1",max:"65535",value:E.mqtt_port??1883,onChange:oe=>hn("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"})]}),s.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.mqtt_use_tls??!1,onChange:oe=>{const wt=oe.target.checked;hn("mqtt_use_tls",wt);const Rn=E.mqtt_port??1883;wt&&Rn===1883?hn("mqtt_port",8883):!wt&&Rn===8883&&hn("mqtt_port",1883)},className:"sr-only peer"}),s.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.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),s.jsx("input",{type:"text",value:E.mqtt_username??"",onChange:oe=>hn("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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),s.jsx("input",{type:"password",value:E.mqtt_password??"",onChange:oe=>hn("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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),s.jsx("input",{type:"text",value:E.mqtt_topic_prefix??"bambuddy",onChange:oe=>hn("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"}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",E.mqtt_topic_prefix||"bambuddy","/printers//status, etc."]})]}),cr&&s.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${cr.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:"text-bambu-gray",children:cr.connected?s.jsxs(s.Fragment,{children:[i("settings.mqttConnectedTo")," ",s.jsxs("span",{className:"text-white",children:[cr.broker,":",cr.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),s.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(yP,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",s.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.prometheus_enabled??!1,onChange:oe=>hn("prometheus_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.prometheus_enabled&&s.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),s.jsx("input",{type:"password",value:E.prometheus_token??"",onChange:oe=>hn("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"}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",s.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer "})]})]}),s.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),s.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),s.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),bn&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[bn.success?s.jsx(Ar,{className:"w-8 h-8 text-green-400"}):s.jsx(Yi,{className:"w-8 h-8 text-red-400"}),s.jsx("h3",{className:"text-lg font-medium text-white",children:bn.success?"Connection Successful":"Connection Failed"})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:bn.success?bn.message||"Successfully connected to Home Assistant.":bn.error||"Failed to connect to Home Assistant."}),s.jsx("div",{className:"flex justify-end",children:s.jsx(Te,{variant:"primary",onClick:()=>wi(null),children:"OK"})})]})}),be==="plugs"&&s.jsxs("div",{className:"max-w-4xl",children:[s.jsxs("div",{className:"flex items-start justify-between mb-6",children:[s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(tl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),s.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."})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Le&&Le.filter(oe=>oe.enabled).length>1&&s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>ee("on"),disabled:Vl.isPending,title:i("settings.turnAllPlugsOn"),children:[Vl.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Gu,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),s.jsxs(Te,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>ee("off"),disabled:Vl.isPending,title:i("settings.turnAllPlugsOff"),children:[Vl.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(gN,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),s.jsxs(Te,{className:"whitespace-nowrap",onClick:()=>{F(null),R(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Le&&Le.length>0&&s.jsxs(_t,{className:"mb-6",children:[s.jsx(Kn,{children:s.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[s.jsx(vh,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",St&&s.jsx(ht,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),s.jsx(Mt,{children:ut?s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(vh,{className:"w-3 h-3"}),"Current Power"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalPower.toFixed(1),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[ut.reachableCount,"/",ut.totalPlugs," plugs online"]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(si,{className:"w-3 h-3"}),"Today"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalToday.toFixed(2),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),E&&E.energy_cost_per_kwh>0&&s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(ut.totalToday*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(yP,{className:"w-3 h-3"}),"Yesterday"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalYesterday.toFixed(2),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),E&&E.energy_cost_per_kwh>0&&s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(ut.totalYesterday*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(hP,{className:"w-3 h-3"}),"Total"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalLifetime.toFixed(1),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),E&&E.energy_cost_per_kwh>0&&s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(ut.totalLifetime*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]})]}):St?null:s.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),Ce?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Le&&Le.length>0?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Le.map(oe=>s.jsx(rKe,{plug:oe,onEdit:wt=>{F(wt),R(!0)}},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(tl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),s.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),s.jsxs(Te,{onClick:()=>{F(null),R(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),be==="notifications"&&s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(wg,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>ae(!0),children:[s.jsx(q0,{className:"w-4 h-4"}),i("settings.log")]}),At&&At.length>0&&s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>{ca(null),pl.mutate()},disabled:pl.isPending,children:[pl.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(PR,{className:"w-4 h-4"}),i("settings.testAll")]}),s.jsxs(Te,{size:"sm",onClick:()=>{K(null),j(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),"Add"]})]})]}),s.jsx(_t,{className:"mb-4",children:s.jsx(Mt,{className:"py-3",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),s.jsx("select",{value:E.notification_language||"en",onChange:oe=>hn("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:mz.map(oe=>s.jsx("option",{value:oe.code,children:oe.nativeName},oe.code))})]})})}),Cc&&s.jsx(_t,{className:"mb-4",children:s.jsxs(Mt,{className:"py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),s.jsx("button",{onClick:()=>ca(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),s.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[s.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[s.jsx(Ar,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:Cc.success})]}),Cc.failed>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(Yi,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:Cc.failed})]})]}),Cc.results.filter(oe=>!oe.success).length>0&&s.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:Cc.results.filter(oe=>!oe.success).map(oe=>s.jsxs("div",{className:"text-xs text-red-400",children:[s.jsxs("span",{className:"font-medium",children:[oe.provider_name,":"]})," ",oe.message]},oe.provider_id))})]})}),Tt?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):At&&At.length>0?s.jsx("div",{className:"space-y-3",children:At.map(oe=>s.jsx(sKe,{provider:oe,onEdit:wt=>{K(wt),j(!0)}},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(wg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),s.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),s.jsxs(Te,{size:"sm",onClick:()=>{K(null),j(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[s.jsx(Ls,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:i("settings.messageTemplatesDescription")}),cn?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):dn&&dn.length>0?s.jsx("div",{className:"space-y-2",children:dn.map(oe=>s.jsx(_t,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>Q(oe),children:s.jsx(Mt,{className:"py-2.5 px-3",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-white font-medium text-sm truncate",children:oe.name}),s.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:oe.title_template})]}),s.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:wt=>{wt.stopPropagation(),Q(oe)},children:s.jsx(fg,{className:"w-4 h-4 text-bambu-gray"})})]})})},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(Ls,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),be==="apikeys"&&s.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx($o,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),s.jsxs(Te,{size:"sm",onClick:()=>ie(!0),className:"flex-shrink-0",children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.createKey")]})]}),G&&s.jsx(_t,{className:"mb-6 border-bambu-green",children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Ar,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),s.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),s.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[s.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:G}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(G);else{const oe=document.createElement("textarea");oe.value=G,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:s.jsx(Fl,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>{I(G),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>Y(null),children:i("common.dismiss")})]})]})]})})}),Pe&&s.jsxs(_t,{className:"mb-6",children:[s.jsx(Kn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),s.jsx("input",{type:"text",value:Ne,onChange:oe=>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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ge.can_read_status,onChange:oe=>Ke(wt=>({...wt,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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white",children:i("settings.readStatus")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ge.can_queue,onChange:oe=>Ke(wt=>({...wt,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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ge.can_control_printer,onChange:oe=>Ke(wt=>({...wt,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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[s.jsxs(Te,{onClick:()=>Nt.mutate({name:Ne||i("settings.unnamedKey"),...ge}),disabled:Nt.isPending,children:[Nt.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(dr,{className:"w-4 h-4"}),i("settings.createKey")]}),s.jsx(Te,{variant:"secondary",onClick:()=>ie(!1),children:i("common.cancel")})]})]})]}),Pt?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Ft&&Ft.length>0?s.jsx("div",{className:"space-y-3",children:Ft.map(oe=>s.jsx(_t,{children:s.jsx(Mt,{className:"py-3",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx($o,{className:`w-5 h-5 ${oe.enabled?"text-bambu-green":"text-bambu-gray"}`}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium",children:oe.name}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[oe.key_prefix,"••••••••",oe.last_used&&` · ${i("settings.lastUsed")}: ${Bg(oe.last_used)}`]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"flex gap-1 text-xs",children:[oe.can_read_status&&s.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),oe.can_queue&&s.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&&s.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")})]}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>q(oe.id),children:s.jsx(rn,{className:"w-4 h-4 text-red-400"})})]})]})})},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx($o,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),s.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),s.jsxs(Te,{onClick:()=>ie(!0),children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),s.jsxs(_t,{className:"mt-6",children:[s.jsx(Kn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.webhookEndpoints")})}),s.jsxs(Mt,{className:"space-y-3 text-sm",children:[s.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),s.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-blue-400",children:"GET"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-blue-400",children:"GET"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-green-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-orange-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-orange-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-red-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"mb-6",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(sh,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),s.jsx(_t,{className:"mb-4",children:s.jsxs(Mt,{className:"py-3",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),s.jsx("input",{type:"text",value:te,onChange:oe=>I(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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),s.jsx(MKe,{apiKey:te})]})]}),be==="virtual-printer"&&s.jsx(bKe,{}),be==="filament"&&E&&s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[s.jsx("div",{className:"flex-1 lg:max-w-xl",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(AR,{className:"w-4 h-4 text-blue-400"}),s.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"0",max:"100",value:E.ams_humidity_good??40,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"0",max:"100",value:E.ams_humidity_fair??60,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")})]}),s.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(bN,{className:"w-4 h-4 text-orange-400"}),s.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:E.ams_temp_good??28,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:E.ams_temp_fair??35,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),s.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(Nu,{className:"w-4 h-4 text-purple-400"}),s.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"1",max:"365",value:E.ams_history_retention_days??30,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]}),s.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(Ur,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"font-medium",children:i("settings.printModal")})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-white",children:i("settings.expandCustomMapping")}),s.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.expandCustomMappingDescription")})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.per_printer_mapping_expanded??!1,onChange:oe=>hn("per_printer_mapping_expanded",oe.target.checked),className:"sr-only peer"}),s.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.jsx("div",{className:"flex-1 lg:max-w-xl",children:s.jsx(pKe,{})})]}),ce!==null&&s.jsx(Zn,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{en.mutate(ce),q(null)},onCancel:()=>q(null)}),A&&s.jsx(iKe,{plug:U,onClose:()=>{R(!1),F(null)}}),$&&s.jsx(oKe,{provider:H,onClose:()=>{j(!1),K(null)}}),V&&s.jsx(lKe,{template:V,onClose:()=>Q(null)}),Z&&s.jsx(dKe,{onClose:()=>ae(!1)}),fe&&s.jsx(Zn,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{me(!1);try{const oe=await ue.clearNotificationLogs(30);o(oe.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>me(!1)}),Ee&&s.jsx(Zn,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{z(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>z(!1)}),O&&s.jsx(Zn,{title:`Turn All Plugs ${O==="on"?"On":"Off"}`,message:`This will turn ${O==="on"?"ON":"OFF"} all ${Le?.filter(oe=>oe.enabled).length||0} enabled smart plugs. ${O==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${O==="on"?"On":"Off"}`,variant:O==="off"?"danger":"warning",onConfirm:()=>{const oe=O;ee(null),Vl.mutate(oe)},onCancel:()=>ee(null)}),le&&Yt?.release_notes&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>_e(!1),children:s.jsxs(_t,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:oe=>oe.stopPropagation(),children:[s.jsxs(Kn,{className:"flex flex-row items-center justify-between shrink-0",children:[s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",Yt.latest_version]}),Yt.release_name&&Yt.release_name!==Yt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray",children:Yt.release_name})]}),s.jsx("button",{onClick:()=>_e(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsx(Mt,{className:"overflow-y-auto flex-1",children:s.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:Yt.release_notes})}),s.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[Yt.release_url&&s.jsx("a",{href:Yt.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:s.jsxs(Te,{variant:"secondary",className:"w-full",children:[s.jsx(Kr,{className:"w-4 h-4"}),"View on GitHub"]})}),s.jsx(Te,{onClick:()=>_e(!1),className:"flex-1",children:"Close"})]})]})}),be==="users"&&s.jsxs("div",{className:"space-y-6",children:[s.jsx(_t,{children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.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?s.jsx(nT,{className:"w-5 h-5 text-green-400"}):s.jsx(tT,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&s.jsxs(Te,{variant:"secondary",onClick:()=>re(!0),children:[s.jsx(tT,{className:"w-4 h-4"}),i("common.disable")]}):s.jsxs(Te,{onClick:()=>e("/setup"),children:[s.jsx(nT,{className:"w-4 h-4"}),i("common.enable")]})]})})}),l&&s.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[s.jsxs("div",{className:"space-y-6",children:[c&&s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(mg,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),s.jsxs(Te,{size:"sm",variant:"ghost",onClick:()=>He(!0),children:[s.jsx($o,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),s.jsx(Mt,{children:s.jsx("div",{className:"flex items-center justify-between",children:s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),s.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&s.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=>s.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))]})]})})})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(mg,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),qt("users:create")&&s.jsxs(Te,{size:"sm",onClick:()=>{Se(!0),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),s.jsx(Mt,{children:wn?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):yt.length===0?s.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):s.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:yt.map(oe=>s.jsxs("div",{className:"py-3 flex items-center justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-white font-medium truncate",children:oe.username}),s.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[oe.is_admin&&s.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(wt=>s.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${wt.name==="Administrators"?"bg-purple-500/20 text-purple-300":wt.name==="Operators"?"bg-blue-500/20 text-blue-300":wt.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:wt.name},wt.id))]})]}),s.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[qt("users:update")&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>Si(oe),children:s.jsx(fg,{className:"w-4 h-4"})}),qt("users:delete")&&oe.id!==c?.id&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>_i(oe.id),children:s.jsx(rn,{className:"w-4 h-4"})})]})]},oe.id))})})]})]}),s.jsx("div",{children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(rT,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),qt("groups:create")&&s.jsxs(Te,{size:"sm",onClick:()=>{vn(!0),la()},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),s.jsx(Mt,{children:Yr?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Fr.length===0?s.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):s.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Fr.map(oe=>s.jsxs("div",{className:"py-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rT,{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"}`}),s.jsx("span",{className:"text-white font-medium",children:oe.name}),oe.is_system&&s.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[qt("groups:update")&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>$h(oe),children:s.jsx(fg,{className:"w-4 h-4"})}),qt("groups:delete")&&!oe.is_system&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>Dn(oe.id),children:s.jsx(rn,{className:"w-4 h-4"})})]})]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:oe.description||i("settings.noDescription")}),s.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[s.jsx("span",{children:i("settings.userCount",{count:oe.user_count})}),s.jsx("span",{children:i("settings.permissionCount",{count:oe.permissions.length})})]})]},oe.id))})})]})})]}),!l&&s.jsx(_t,{children:s.jsx(Mt,{className:"py-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx(tT,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),s.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:i("settings.authDisabledFeature1")})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:i("settings.authDisabledFeature2")})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),s.jsxs(Te,{onClick:()=>e("/setup"),children:[s.jsx(nT,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),Be&&s.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mg,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),s.jsx("input",{type:"text",value:ft.username,onChange:oe=>Bt({...ft,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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),s.jsx("input",{type:"password",value:ft.password,onChange:oe=>Bt({...ft,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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),s.jsx("input",{type:"password",value:ft.confirmPassword,onChange:oe=>Bt({...ft,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 ${ft.confirmPassword&&ft.password!==ft.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),ft.confirmPassword&&ft.password!==ft.confirmPassword&&s.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),s.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:[Fr.map(oe=>s.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ft.group_ids.includes(oe.id),onChange:()=>Ks(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"}),s.jsx("span",{className:"text-sm text-white",children:oe.name}),oe.is_system&&s.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},oe.id)),Fr.length===0&&s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),s.jsx(Te,{onClick:Mo,disabled:Ws.isPending||!ft.username||!ft.password||ft.password!==ft.confirmPassword||ft.password.length<6,children:Ws.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):s.jsxs(s.Fragment,{children:[s.jsx(dr,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),Xe&&tt!==null&&s.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fg,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),s.jsx("input",{type:"text",value:ft.username,onChange:oe=>Bt({...ft,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"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:["Password ",s.jsx("span",{className:"text-bambu-gray font-normal",children:"(leave blank to keep current)"})]}),s.jsx("input",{type:"password",value:ft.password,onChange:oe=>Bt({...ft,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})]}),ft.password&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),s.jsx("input",{type:"password",value:ft.confirmPassword,onChange:oe=>Bt({...ft,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 ${ft.confirmPassword&&ft.password!==ft.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),ft.confirmPassword&&ft.password!==ft.confirmPassword&&s.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),s.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:Fr.map(oe=>s.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ft.group_ids.includes(oe.id),onChange:()=>Ks(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"}),s.jsx("span",{className:"text-sm text-white",children:oe.name}),oe.is_system&&s.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},oe.id))})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),s.jsx(Te,{onClick:()=>Ms(tt),disabled:tn.isPending||!ft.username||!!(ft.password&&(ft.password!==ft.confirmPassword||ft.password.length<6)),children:tn.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):s.jsxs(s.Fragment,{children:[s.jsx(hs,{className:"w-4 h-4"}),"Save Changes"]})})]})]})]})}),We!==null&&s.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{ze(null),De(null)},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[s.jsx(rn,{className:"w-5 h-5"}),s.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),s.jsx(Mt,{className:"space-y-4",children:Ye?s.jsx("div",{className:"flex items-center justify-center py-4",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):W&&W.archives+W.queue_items+W.library_files>0?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),s.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[W.archives>0&&s.jsxs("li",{children:[W.archives," archive",W.archives!==1?"s":""]}),W.queue_items>0&&s.jsxs("li",{children:[W.queue_items," queue item",W.queue_items!==1?"s":""]}),W.library_files>0&&s.jsxs("li",{children:[W.library_files," library file",W.library_files!==1?"s":""]})]}),s.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Te,{variant:"danger",onClick:()=>on.mutate({id:We,deleteItems:!0}),disabled:on.isPending,className:"justify-center",children:"Delete user AND their items"}),s.jsx(Te,{variant:"secondary",onClick:()=>on.mutate({id:We,deleteItems:!1}),disabled:on.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),s.jsx(Te,{variant:"ghost",onClick:()=>{ze(null),De(null)},disabled:on.isPending,className:"justify-center",children:"Cancel"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),s.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx(Te,{variant:"ghost",onClick:()=>{ze(null),De(null)},disabled:on.isPending,children:"Cancel"}),s.jsx(Te,{variant:"danger",onClick:()=>on.mutate({id:We,deleteItems:!1}),disabled:on.isPending,children:"Delete User"})]})]})})]})}),(Lt||Jt)&&s.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{vn(!1),ir(null),la()},children:s.jsxs(_t,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rT,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:Jt?"Edit Group":"Create Group"})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{vn(!1),ir(null),la()},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groupName")}),s.jsx("input",{type:"text",value:ln.name,onChange:oe=>mr({...ln,name:oe.target.value}),disabled:Jt?.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")}),Jt?.is_system&&s.jsx("p",{className:"text-xs text-yellow-400 mt-1",children:i("settings.systemGroupWarning")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Description"}),s.jsx("textarea",{value:ln.description,onChange:oe=>mr({...ln,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")})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:["Permissions (",ln.permissions.length," selected)"]}),s.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:Br?.categories.map(oe=>s.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[s.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:()=>$l(oe.name),children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",onClick:wt=>{wt.stopPropagation(),Dm(oe,!Rm(oe))},className:`w-5 h-5 rounded border flex items-center justify-center transition-colors ${Rm(oe)?"bg-bambu-green border-bambu-green":Vh(oe)?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:(Rm(oe)||Vh(oe))&&s.jsx(Ia,{className:"w-3 h-3 text-white"})}),s.jsx("span",{className:"text-white font-medium",children:oe.name}),s.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",oe.permissions.filter(wt=>ln.permissions.includes(wt.value)).length,"/",oe.permissions.length,")"]})]}),Fn.has(oe.name)?s.jsx(ei,{className:"w-4 h-4 text-bambu-gray"}):s.jsx(gs,{className:"w-4 h-4 text-bambu-gray"})]}),Fn.has(oe.name)&&s.jsx("div",{className:"p-3 bg-bambu-dark space-y-2",children:oe.permissions.map(wt=>s.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ln.permissions.includes(wt.value),onChange:()=>zx(wt.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"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:wt.label})]},wt.value))})]},oe.name))})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{vn(!1),ir(null),la()},children:"Cancel"}),s.jsx(Te,{onClick:Jt?Ux:Hr,disabled:Ss.isPending||_o.isPending||!ln.name.trim(),children:Ss.isPending||_o.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),Jt?"Saving...":"Creating..."]}):s.jsxs(s.Fragment,{children:[s.jsx(hs,{className:"w-4 h-4"}),Jt?"Save Changes":"Create Group"]})})]})]})]})}),fr!==null&&s.jsx(Zn,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{So.mutate(fr),Dn(null)},onCancel:()=>Dn(null)}),be==="backup"&&s.jsx(vKe,{}),we&&s.jsx(Zn,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ue.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await u(),re(!1),window.location.href="/"}catch(oe){const wt=oe instanceof Error?oe.message:i("settings.toast.authDisableFailed");o(wt,"error")}},onCancel:()=>re(!1)}),Fe&&s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($o,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),s.jsx("input",{type:"password",value:Ve.currentPassword,onChange:oe=>$e({...Ve,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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),s.jsx("input",{type:"password",value:Ve.newPassword,onChange:oe=>$e({...Ve,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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),s.jsx("input",{type:"password",value:Ve.confirmPassword,onChange:oe=>$e({...Ve,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 ${Ve.confirmPassword&&Ve.newPassword!==Ve.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Ve.confirmPassword&&Ve.newPassword!==Ve.confirmPassword&&s.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),s.jsx(Te,{onClick:async()=>{if(Ve.newPassword!==Ve.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ve.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}je(!0);try{await ue.changePassword(Ve.currentPassword,Ve.newPassword),o(i("settings.toast.passwordChanged"),"success"),He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})}catch(oe){const wt=oe instanceof Error?oe.message:"Failed to change password";o(wt,"error")}finally{je(!1)}},disabled:ye||!Ve.currentPassword||!Ve.newPassword||Ve.newPassword!==Ve.confirmPassword||Ve.newPassword.length<6,children:ye?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):s.jsxs(s.Fragment,{children:[s.jsx($o,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const Ore=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},EKe=t=>t.startsWith("HH")?"HF":"S",TKe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},uR=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 $j({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:a,note:o}){const l=EKe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&a?a():e()};return s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?s.jsx(ol,{className:"w-4 h-4 text-bambu-green"}):s.jsx(ll,{className:"w-4 h-4"})}),s.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:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:Ore(t.k_value)}),s.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&s.jsx("span",{title:"Has note",children:s.jsx(kW,{className:"w-3 h-3 text-yellow-500"})}),s.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&s.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&&s.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:s.jsx(Fl,{className:"w-4 h-4"})})]})}function Vj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],isDualNozzle:i=!1,initialNote:a="",initialNoteKey:o=null,onClose:l,onSave:c,onSaveNote:u,hasPermission:d}){const{t:f}=Hn(),{showToast:p}=$n(),[m,x]=_.useState(t?.name||""),[b,y]=_.useState(t?.k_value?Ore(t.k_value):"0.020"),[v,S]=_.useState(t?.filament_id||""),[N,T]=_.useState(t?.nozzle_id?TKe(t.nozzle_id):"HH00"),[k,C]=_.useState(t?.nozzle_diameter||n),[E,D]=_.useState(t?[t.extruder_id]:i?[0,1]:[0]),[A,R]=_.useState(!1),[U,F]=_.useState({current:0,total:0}),[$,j]=_.useState(a),H=Jr.useMemo(()=>{const X=new Map;for(const ne of r)if(ne.filament_id&&!X.has(ne.filament_id)){const se=uR(ne.name||"");X.set(ne.filament_id,{id:ne.filament_id,name:se||ne.filament_id})}return Array.from(X.values()).sort((ne,se)=>ne.name.localeCompare(se.name))},[r]),K=mt({mutationFn:X=>(console.log("[KProfile] Calling API..."),ue.setKProfile(e,X)),onSuccess:X=>{if(console.log("[KProfile] Save success:",X),p(f("kProfiles.toast.profileSaved")),u&&$!==a){let ne;$===""&&o?ne=o:t&&t.slot_id>0?ne=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:ne=`name_${m}_${v}`,u(ne,$)}R(!0),setTimeout(()=>{R(!1),c()},2500)},onError:X=>{console.error("[KProfile] Save error:",X),p(X.message,"error"),R(!1)}}),V=mt({mutationFn:X=>(console.log("[KProfile] Deleting profile..."),ue.deleteKProfile(e,X)),onSuccess:X=>{console.log("[KProfile] Delete success:",X),p(f("kProfiles.toast.profileDeleted")),R(!0),setTimeout(()=>{R(!1),l()},4e3)},onError:X=>{console.error("[KProfile] Delete error:",X),p(X.message,"error"),R(!1)}}),[Q,Z]=_.useState(!1),ae=()=>{t&&V.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})},B=async X=>{if(X.preventDefault(),i&&!t&&E.length===0){p(f("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const ne=parseFloat(b).toFixed(6),se=`${N}-${k}`;if(t||E.length===1){const xe={name:m,k_value:ne,filament_id:v,nozzle_id:se,nozzle_diameter:k,extruder_id:t?t.extruder_id:E[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",xe),K.mutate(xe);return}R(!0),F({current:1,total:E.length});const be=E.map(xe=>({name:m,k_value:ne,filament_id:v,nozzle_id:se,nozzle_diameter:k,extruder_id:xe,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${be.length} profiles in batch:`,be);try{if(await ue.setKProfilesBatch(e,be),p(f("kProfiles.toast.profilesSaved",{count:E.length})),u&&$){const xe=`name_${m}_${v}`;u(xe,$)}}catch(xe){console.error("[KProfile] Failed to save batch:",xe),p(f("kProfiles.toast.failedToSaveBatch"),"error"),R(!1),F({current:0,total:0});return}F({current:E.length,total:E.length}),setTimeout(()=>{R(!1),F({current:0,total:0}),c()},3e3)};return s.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[s.jsxs(_t,{className:"w-full max-w-md relative",children:[A&&s.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:U.total>1?f("kProfiles.modal.savingExtruder",{current:U.current,total:U.total}):f("kProfiles.modal.syncing")}),s.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:f("kProfiles.modal.pleaseWait")})]}),s.jsxs(Mt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-xl font-semibold text-white",children:f(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),s.jsx("button",{onClick:l,className:"text-bambu-gray hover:text-white transition-colors",disabled:A,children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:B,className:"p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.profileName")}),s.jsx("input",{type:"text",value:m,onChange:X=>x(X.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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.kValue")}),s.jsx("input",{type:"text",inputMode:"decimal",value:b,onChange:X=>{const ne=X.target.value;(ne===""||/^\d*\.?\d*$/.test(ne))&&y(ne)},onBlur:X=>{const ne=parseFloat(X.target.value);isNaN(ne)||y((Math.trunc(ne*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}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.kValueHelp")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.filament")}),s.jsxs("select",{value:v,onChange:X=>{const ne=X.target.value;if(S(ne),!t&&ne&&!m){const se=H.find(be=>be.id===ne);se&&x(`${N==="HH00"?"HF":"S"} ${se.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:[s.jsx("option",{value:"",children:f("kProfiles.modal.selectFilament")}),t?.filament_id&&s.jsx("option",{value:t.filament_id,children:H.find(X=>X.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&H.map(X=>s.jsx("option",{value:X.id,children:X.name},X.id))]}),!t&&H.length===0&&s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.noFilamentsHelp")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.flowType")}),s.jsxs("select",{value:N,onChange:X=>{const ne=X.target.value;if(T(ne),!t&&v&&!m){const se=H.find(be=>be.id===v);se&&x(`${ne==="HS00"?"HF":"S"} ${se.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:[s.jsx("option",{value:"HH00",children:f("kProfiles.modal.highFlow")}),s.jsx("option",{value:"HS00",children:f("kProfiles.modal.standard")})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.nozzleSize")}),s.jsxs("select",{value:k,onChange:X=>C(X.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:[s.jsx("option",{value:"0.2",children:"0.2mm"}),s.jsx("option",{value:"0.4",children:"0.4mm"}),s.jsx("option",{value:"0.6",children:"0.6mm"}),s.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),i&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?s.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")}):s.jsxs("div",{className:"flex gap-4",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.includes(1),onChange:X=>{X.target.checked?D([...E,1]):D(E.filter(ne=>ne!==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"}),s.jsx("span",{className:"text-white",children:f("kProfiles.modal.left")})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.includes(0),onChange:X=>{X.target.checked?D([...E,0]):D(E.filter(ne=>ne!==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"}),s.jsx("span",{className:"text-white",children:f("kProfiles.modal.right")})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.notes")}),s.jsx("textarea",{value:$,onChange:X=>j(X.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.notesHelp")})]}),s.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&s.jsx(Te,{type:"button",variant:"secondary",onClick:()=>Z(!0),disabled:V.isPending||A||!d("kprofiles:delete"),title:d("kprofiles:delete")?void 0:f("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:V.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"})}),s.jsx(Te,{type:"button",variant:"secondary",onClick:l,disabled:A,className:"flex-1",children:f("common.cancel")}),s.jsxs(Te,{type:"submit",disabled:K.isPending||A||!d(t?"kprofiles:update":"kprofiles:create"),title:d(t?"kprofiles:update":"kprofiles:create")?void 0:f(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[K.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(dN,{className:"w-4 h-4"}),f("common.save")]})]})]})]})]}),Q&&s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:s.jsx(_t,{className:"w-full max-w-sm",children:s.jsxs(Mt,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:s.jsx(rn,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:f("kProfiles.deleteConfirm.title")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:f("kProfiles.deleteConfirm.cannotUndo")})]})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:f("kProfiles.deleteConfirm.message",{name:t?.name})}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>Z(!1),className:"flex-1",children:f("common.cancel")}),s.jsxs(Te,{onClick:()=>{Z(!1),ae()},disabled:V.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[V.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"}),f("common.delete")]})]})]})})})]})}const h1={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function AKe(){const{t}=Hn(),{showToast:e}=$n(),{hasPermission:n}=Ai(),[r,i]=_.useState(null),[a,o]=_.useState(()=>localStorage.getItem(h1.NOZZLE_DIAMETER)||"0.4"),[l,c]=_.useState(null),[u,d]=_.useState(!1),[f,p]=_.useState(null),[m,x]=_.useState(""),[b,y]=_.useState("all"),[v,S]=_.useState("all"),[N,T]=_.useState(()=>localStorage.getItem(h1.SORT_OPTION)||"name"),[k,C]=_.useState(!1),[E,D]=_.useState(new Set),[A,R]=_.useState(!1),[U,F]=_.useState(!1),$=_.useCallback(I=>`${I.slot_id}_${I.extruder_id}`,[]);_.useEffect(()=>{localStorage.setItem(h1.NOZZLE_DIAMETER,a)},[a]),_.useEffect(()=>{localStorage.setItem(h1.SORT_OPTION,N)},[N]);const{data:j,isLoading:H}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:K,isLoading:V,isFetching:Q,error:Z,refetch:ae}=at({queryKey:["kprofiles",r,a],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",a);const I=await ue.getKProfiles(r,a);return console.log("[KProfiles] Received profiles:",I?.profiles?.length||0,"profiles"),I},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:B}=at({queryKey:["kprofiles",r,"0.4"],queryFn:()=>ue.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:X,refetch:ne}=at({queryKey:["kprofile-notes",r],queryFn:()=>ue.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),se=Z?.message?.includes("not connected");_.useEffect(()=>{if(!r&&j&&j.length>0){const I=j.find(fe=>fe.is_active);I&&i(I.id)}},[r,j]),_.useEffect(()=>{if(r){const I=setTimeout(()=>{ae()},150);return()=>clearTimeout(I)}},[r,a]);const be=j?.filter(I=>I.is_active)||[],xe=Jr.useMemo(()=>K?.profiles?K.profiles.filter(fe=>{const me=m.toLowerCase(),Ee=!me||fe.name.toLowerCase().includes(me)||fe.filament_id.toLowerCase().includes(me),z=b==="all"||b==="left"&&fe.extruder_id===1||b==="right"&&fe.extruder_id===0,O=v==="all"||v==="hf"&&fe.nozzle_id.startsWith("HH")||v==="s"&&fe.nozzle_id.startsWith("HS");return Ee&&z&&O}).sort((fe,me)=>{switch(N){case"k_value":return parseFloat(fe.k_value)-parseFloat(me.k_value);case"filament":return uR(fe.name).localeCompare(uR(me.name));case"name":default:return fe.name.localeCompare(me.name)}}):[],[K?.profiles,m,b,v,N]),de=j?.find(I=>I.id===r),Pe=de?.nozzle_count===2;_.useEffect(()=>{const I=fe=>{fe.target instanceof HTMLInputElement||fe.target instanceof HTMLTextAreaElement||fe.target instanceof HTMLSelectElement||l||u||f||(fe.key==="r"||fe.key==="R"?(fe.preventDefault(),ae()):fe.key==="n"||fe.key==="N"?(fe.preventDefault(),d(!0)):fe.key==="Escape"&&k&&(fe.preventDefault(),C(!1),D(new Set)))};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[l,u,f,k,ae]);const ie=_.useCallback(()=>{if(!K?.profiles||K.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const I={version:1,exported_at:new Date().toISOString(),printer:de?.name||"Unknown",nozzle_diameter:a,profiles:K.profiles.map(z=>({name:z.name,k_value:z.k_value,filament_id:z.filament_id,nozzle_id:z.nozzle_id,nozzle_diameter:z.nozzle_diameter,extruder_id:z.extruder_id}))},fe=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),me=URL.createObjectURL(fe),Ee=document.createElement("a");Ee.href=me,Ee.download=`kprofiles_${de?.name||"printer"}_${a}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(Ee),Ee.click(),document.body.removeChild(Ee),URL.revokeObjectURL(me),e(t("kProfiles.toast.exportedProfiles",{count:K.profiles.length}))},[K?.profiles,de,a,e,t]),Ne=_.useCallback(()=>{const I=document.createElement("input");I.type="file",I.accept=".json",I.onchange=async fe=>{const me=fe.target.files?.[0];if(me)try{const Ee=await me.text(),z=JSON.parse(Ee);if(!z.profiles||!Array.isArray(z.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let O=0;for(const ee of z.profiles)if(!(!ee.name||!ee.k_value||!ee.filament_id))try{await ue.setKProfile(r,{name:ee.name,k_value:parseFloat(ee.k_value).toFixed(6),filament_id:ee.filament_id,nozzle_id:ee.nozzle_id||`HH00-${a}`,nozzle_diameter:ee.nozzle_diameter||a,extruder_id:ee.extruder_id??0,slot_id:0}),O++,await new Promise(le=>setTimeout(le,500))}catch(le){console.error("Failed to import profile:",ee.name,le)}e(t("kProfiles.toast.importedProfiles",{count:O,total:z.profiles.length})),ae()}catch(Ee){console.error("Import error:",Ee),e(t("kProfiles.toast.failedToParseImport"),"error")}},I.click()},[r,a,e,ae,t]),Oe=_.useCallback(I=>{D(fe=>{const me=new Set(fe);return me.has(I)?me.delete(I):me.add(I),me})},[]),ge=_.useCallback(()=>{D(new Set(xe.map(I=>$(I))))},[xe,$]),Ke=_.useCallback(()=>{E.size!==0&&R(!0)},[E.size]),G=_.useCallback(async()=>{const I=xe.filter(me=>E.has($(me)));F(!0);let fe=0;for(const me of I)try{await ue.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}),fe++,await new Promise(Ee=>setTimeout(Ee,300))}catch(Ee){console.error("Failed to delete profile:",me.name,Ee)}e(t("kProfiles.toast.profilesDeleted",{count:fe})),F(!1),R(!1),C(!1),D(new Set),ae()},[r,E,xe,e,ae,$,t]),Y=_.useCallback(I=>{const fe=[];return I.setting_id&&fe.push(I.setting_id),fe.push(`slot_${I.slot_id}_${I.filament_id}_${I.extruder_id}`),fe.push(`name_${I.name}_${I.filament_id}`),fe},[]),ce=_.useCallback(async(I,fe)=>{if(r)try{await ue.setKProfileNote(r,I,fe),ne()}catch(me){console.error("Failed to save note:",me),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,ne,e,t]),q=_.useCallback(I=>{if(!X?.notes)return{note:"",key:null};const fe=Y(I);for(const me of fe)if(X.notes[me])return{note:X.notes[me],key:me};return{note:"",key:null}},[X,Y]),te=_.useCallback(I=>q(I).note,[q]);return H?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!j||j.length===0?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(Hi,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),s.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):be.length===0?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(Ur,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),s.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):s.jsxs(s.Fragment,{children:[Q&&!V&&s.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[s.jsx(ht,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),s.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[s.jsxs("div",{className:"flex-1 min-w-48",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),s.jsx("select",{value:r||"",onChange:I=>i(parseInt(I.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:be.map(I=>s.jsx("option",{value:I.id,children:I.name},I.id))})]}),s.jsxs("div",{className:"w-32",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),s.jsxs("select",{value:a,onChange:I=>o(I.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:[s.jsx("option",{value:"0.2",children:"0.2mm"}),s.jsx("option",{value:"0.4",children:"0.4mm"}),s.jsx("option",{value:"0.6",children:"0.6mm"}),s.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsxs(Te,{variant:"secondary",onClick:()=>ae(),disabled:Q||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[s.jsx(Dr,{className:`w-4 h-4 ${Q?"animate-spin":""}`}),t("kProfiles.refresh")]}),s.jsxs(Te,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[s.jsx(dr,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[s.jsxs("div",{className:"flex-1 min-w-48 relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),s.jsx("input",{type:"text",value:m,onChange:I=>x(I.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"})]}),Pe&&s.jsx("div",{className:"w-36",children:s.jsxs("select",{value:b,onChange:I=>y(I.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:[s.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),s.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),s.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:v,onChange:I=>S(I.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:[s.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),s.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),s.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:N,onChange:I=>T(I.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:[s.jsx("option",{value:"name",children:t("kProfiles.sortName")}),s.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),s.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[s.jsxs(Te,{variant:"secondary",onClick:ie,disabled:!K?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[s.jsx(yi,{className:"w-4 h-4"}),t("kProfiles.export")]}),s.jsxs(Te,{variant:"secondary",onClick:Ne,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[s.jsx(Ua,{className:"w-4 h-4"}),t("kProfiles.import")]}),s.jsx("div",{className:"flex-1"}),k?s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"secondary",onClick:ge,children:[s.jsx(ol,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),s.jsxs(Te,{variant:"secondary",onClick:Ke,disabled:E.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:[s.jsx(rn,{className:"w-4 h-4"}),t("kProfiles.delete")," (",E.size,")"]}),s.jsxs(Te,{variant:"secondary",onClick:()=>{C(!1),D(new Set)},children:[s.jsx(Rt,{className:"w-4 h-4"}),t("common.cancel")]})]}):s.jsxs(Te,{variant:"secondary",onClick:()=>C(!0),disabled:!xe.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[s.jsx(ol,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),V?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):se?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(sm,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),s.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),s.jsxs(Te,{variant:"secondary",onClick:()=>ae(),children:[s.jsx(Dr,{className:"w-4 h-4"}),t("common.refresh")]})]})}):xe.length>0?Pe?s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),s.jsx("div",{className:"space-y-1",children:xe.filter(I=>I.extruder_id===1).map(I=>s.jsx($j,{profile:I,onEdit:()=>c(I),onCopy:()=>p(I),selectionMode:k,isSelected:E.has($(I)),onToggleSelect:()=>Oe($(I)),note:te(I)},$(I)))})]}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),s.jsx("div",{className:"space-y-1",children:xe.filter(I=>I.extruder_id===0).map(I=>s.jsx($j,{profile:I,onEdit:()=>c(I),onCopy:()=>p(I),selectionMode:k,isSelected:E.has($(I)),onToggleSelect:()=>Oe($(I)),note:te(I)},$(I)))})]})]}):s.jsx("div",{className:"space-y-1",children:xe.map(I=>s.jsx($j,{profile:I,onEdit:()=>c(I),onCopy:()=>p(I),selectionMode:k,isSelected:E.has($(I)),onToggleSelect:()=>Oe($(I)),note:te(I)},$(I)))}):m||b!=="all"||v!=="all"?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(ba,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),s.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(dN,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),s.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:a})}),s.jsxs(Te,{onClick:()=>d(!0),children:[s.jsx(dr,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:I,key:fe}=q(l);return s.jsx(Vj,{profile:l,printerId:r,nozzleDiameter:a,existingProfiles:B?.profiles||K?.profiles,isDualNozzle:Pe,initialNote:I,initialNoteKey:fe,onSaveNote:ce,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),ae()},onSave:()=>{c(null),ae()}})})(),u&&r&&s.jsx(Vj,{printerId:r,nozzleDiameter:a,existingProfiles:B?.profiles||K?.profiles,isDualNozzle:Pe,onSaveNote:ce,hasPermission:n,onClose:()=>{d(!1),ae()},onSave:()=>{d(!1),ae()}}),f&&r&&s.jsx(Vj,{printerId:r,nozzleDiameter:a,existingProfiles:B?.profiles||K?.profiles,isDualNozzle:Pe,onSaveNote:ce,hasPermission:n,profile:{...f,slot_id:0,name:`${f.name} (Copy)`},onClose:()=>{p(null),ae()},onSave:()=>{p(null),ae()}}),A&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(_t,{className:"w-full max-w-sm",children:s.jsxs(Mt,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:s.jsx(rn,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:E.size})}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>R(!1),disabled:U,className:"flex-1",children:t("common.cancel")}),s.jsxs(Te,{onClick:G,disabled:U,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[U?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}function cF(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,a=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=a?(a[1]||a[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 Ry(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function CKe(t,e){const n=Ii(t);if(!n)return"";const i=new Date().getTime()-n.getTime(),a=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return a<1?e("profiles.time.justNow"):a<60?e("profiles.time.minsAgo",{count:a}):o<24?e("profiles.time.hoursAgo",{count:o}):l<7?e("profiles.time.daysAgo",{count:l}):n.toLocaleDateString()}function jKe({onSuccess:t,t:e}){const{showToast:n}=$n(),[r,i]=_.useState("email"),[a,o]=_.useState(""),[l,c]=_.useState(""),[u,d]=_.useState(""),[f,p]=_.useState(""),[m,x]=_.useState("global"),[b,y]=_.useState(null),[v,S]=_.useState(null),N=mt({mutationFn:()=>ue.cloudLogin(a,l,m),onSuccess:D=>{D.success?(n(e("profiles.login.toast.loggedIn")),t()):D.needs_verification?(y(D.verification_type||"email"),S(D.tfa_key||null),D.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),i("code")):n(D.message,"error")},onError:D=>n(D.message,"error")}),T=mt({mutationFn:()=>ue.cloudVerify(a,u,v||void 0),onSuccess:D=>{D.success?(n(e("profiles.login.toast.loggedIn")),t()):n(D.message,"error")},onError:D=>n(D.message,"error")}),k=mt({mutationFn:()=>ue.cloudSetToken(f),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:D=>n(D.message,"error")}),C=D=>{D.preventDefault(),r==="email"?N.mutate():r==="code"?T.mutate():r==="token"&&k.mutate()},E=N.isPending||T.isPending||k.isPending;return s.jsx(_t,{className:"max-w-md mx-auto",children:s.jsxs(Mt,{children:[s.jsxs("div",{className:"text-center mb-6",children:[s.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:s.jsx(oN,{className:"w-6 h-6 text-bambu-green"})}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),s.jsxs("form",{onSubmit:C,className:"space-y-4",children:[r==="email"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),s.jsx("input",{type:"email",value:a,onChange:D=>o(D.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"your@email.com",required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),s.jsx("input",{type:"password",value:l,onChange:D=>c(D.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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),s.jsxs("select",{value:m,onChange:D=>x(D.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[s.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),s.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(b==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:b==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:a})}),s.jsx("input",{type:"text",value:u,onChange:D=>d(D.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"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),s.jsx("textarea",{value:f,onChange:D=>p(D.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})]}),s.jsxs("div",{className:"flex gap-2",children:[r==="code"&&s.jsx(Te,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),s.jsxs(Te,{type:"submit",disabled:E,className:"flex-1",children:[E?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dz,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx($o,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx(Dz,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function rg({label:t,value:e,options:n,onChange:r}){const[i,a]=_.useState(!1),o=n.find(l=>l.value===e);return s.jsxs("div",{className:"relative",children:[s.jsxs("button",{onClick:()=>a(!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:[s.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),s.jsx("span",{children:o?.label||"All"}),s.jsx(ei,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>a(!1)}),s.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=>s.jsxs("button",{onClick:()=>{r(l.value),a(!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:[s.jsx("span",{children:l.label}),l.count!==void 0&&s.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function PKe(){const[t,e]=_.useState(!1);_.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?s.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:s.jsx(Ig,{className:"w-5 h-5"})}):null}function Gj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:a,compareDisabled:o,t:l}){const c=cF(t.name),u=Ry(t.setting_id);return s.jsxs("div",{className:"flex items-center gap-2 group",children:[s.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:s.jsxs("div",{className:"flex items-center gap-2",children:[i&&a!==void 0&&s.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:a+1}),!i&&u&&s.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),s.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),s.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:s.jsx(Fl,{className:"w-4 h-4"})})]})}function dR(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(` + `,children:s.jsxs("div",{className:"flex items-center gap-4 p-4",children:[E&&d&&s.jsx("button",{onClick:A=>{A.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&&s.jsx(Ia,{className:"w-4 h-4"})}),E?s.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:s.jsx(zg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}):e!==void 0?s.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]}):s.jsx("div",{className:"w-8"}),s.jsx("div",{className:"w-14 h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?s.jsx("img",{src:t.plate_id!=null?ue.getArchivePlateThumbnail(t.archive_id,t.plate_id):ue.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?s.jsx("img",{src:t.plate_id!=null?ue.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ue.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):s.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:s.jsx(sl,{className:"w-6 h-6"})})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.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?s.jsx(Ds,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:m("queue.viewArchive"),children:s.jsx(Kr,{className:"w-3.5 h-3.5"})}):t.library_file_id?s.jsx(Ds,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:m("queue.viewInFileManager"),children:s.jsx(Kr,{className:"w-3.5 h-3.5"})}):null]}),s.jsxs("div",{className:"flex items-center gap-3 text-sm text-bambu-gray",children:[s.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:[s.jsx(Ur,{className:"w-3.5 h-3.5"}),t.target_model?`${m("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?m("queue.filter.unassigned"):t.printer_name||`${m("common.printer")} #${t.printer_id}`]}),t.print_time_seconds&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xu,{className:"w-3.5 h-3.5"}),Rre(t.print_time_seconds)]}),t.created_by_username&&s.jsxs("span",{className:"flex items-center gap-1.5",title:m("queue.addedBy",{name:t.created_by_username}),children:[s.jsx(am,{className:"w-3.5 h-3.5"}),t.created_by_username]}),E&&!t.manual_start&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(er,{className:"w-3.5 h-3.5"}),UWe(t.scheduled_time,c,m)]})]}),s.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[t.manual_start&&s.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:[s.jsx(bW,{className:"w-3 h-3"}),m("queue.badges.staged")]}),t.require_previous_success&&s.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:m("queue.badges.requiresPrevious")}),t.auto_off_after&&s.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:[s.jsx(Gu,{className:"w-3 h-3"}),m("queue.badges.autoPowerOff")]})]}),C&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"h-2 bg-bambu-dark rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-gradient-to-r from-blue-500 to-blue-400 animate-pulse w-full opacity-50"})}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:m("queue.printingInProgress")})]}),t.waiting_reason&&t.status==="pending"&&s.jsxs("p",{className:"text-xs text-purple-400 mt-2 flex items-start gap-1",children:[s.jsx(Hi,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),s.jsx("span",{children:t.waiting_reason})]}),t.error_message&&s.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[s.jsx(Hi,{className:"w-3 h-3"}),t.error_message]})]}),s.jsx(zWe,{status:t.status,waitingReason:t.waiting_reason,t:m}),s.jsxs("div",{className:"flex items-center gap-1",children:[C&&s.jsx(Te,{variant:"ghost",size:"sm",onClick:a,disabled:!f("printers:control"),title:f("printers:control")?m("queue.actions.stopPrint"):m("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Xce,{className:"w-4 h-4"})}),E&&s.jsxs(s.Fragment,{children:[t.manual_start&&s.jsx(Te,{variant:"ghost",size:"sm",onClick:l,disabled:!f("printers:control"),title:f("printers:control")?m("queue.actions.startPrint"):m("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:s.jsx(Is,{className:"w-4 h-4"})}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:n,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?m("common.edit"):m("queue.permissions.noEdit"),children:s.jsx(Qi,{className:"w-4 h-4"})}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?m("common.cancel"):m("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Rt,{className:"w-4 h-4"})})]}),D&&s.jsxs(s.Fragment,{children:[s.jsx(Te,{variant:"ghost",size:"sm",onClick:o,disabled:!f("queue:create"),title:f("queue:create")?m("queue.actions.requeue"):m("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:s.jsx(Dr,{className:"w-4 h-4"})}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?m("common.remove"):m("queue.permissions.noRemove"),children:s.jsx(rn,{className:"w-4 h-4"})})]})]})]})})}function HWe(){const{t}=Hn(),e=an(),{showToast:n}=$n(),{hasPermission:r,hasAnyPermission:i,canModify:a}=Ai(),[o,l]=_.useState(null),[c,u]=_.useState(""),[d,f]=_.useState(""),[p,m]=_.useState(!1),[x,b]=_.useState(null),[y,v]=_.useState(null),[S,N]=_.useState(null),[T,k]=_.useState([]),[C,E]=_.useState(!1),[D,A]=_.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[R,U]=_.useState(()=>{const I=localStorage.getItem("queue.historySortAsc");return I!==null?I==="true":!1}),[F,$]=_.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[j,H]=_.useState(()=>{const I=localStorage.getItem("queue.pendingSortAsc");return I!==null?I==="true":!0});_.useEffect(()=>{localStorage.setItem("queue.historySortBy",D)},[D]),_.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(R))},[R]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",F)},[F]),_.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(j))},[j]);const K=cre(ZM(B2,{activationConstraint:{distance:8}}),ZM(z2,{coordinateGetter:Pre})),{data:V}=at({queryKey:["settings"],queryFn:ue.getSettings}),Q=V?.time_format||"system",{data:Z,isLoading:ae}=at({queryKey:["queue",o,c],queryFn:()=>ue.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:B}=at({queryKey:["printers"],queryFn:()=>ue.getPrinters()}),X=mt({mutationFn:I=>ue.cancelQueueItem(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.cancelled"))},onError:()=>n(t("queue.toast.cancelFailed"),"error")}),ne=mt({mutationFn:I=>ue.removeFromQueue(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.removed"))},onError:()=>n(t("queue.toast.removeFailed"),"error")}),se=mt({mutationFn:I=>ue.stopQueueItem(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.stopped"))},onError:()=>n(t("queue.toast.stopFailed"),"error")}),be=mt({mutationFn:I=>ue.startQueueItem(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.released"))},onError:()=>n(t("queue.toast.startFailed"),"error")}),xe=mt({mutationFn:I=>ue.reorderQueue(I),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>n(t("queue.toast.reorderFailed"),"error")}),de=mt({mutationFn:async()=>{const I=Z?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];for(const fe of I)await ue.removeFromQueue(fe.id);return I.length},onSuccess:I=>{e.invalidateQueries({queryKey:["queue"]}),n(t("queue.toast.historyCleared",{count:I}))},onError:()=>n(t("queue.toast.clearHistoryFailed"),"error")}),Pe=mt({mutationFn:I=>ue.bulkUpdateQueue(I),onSuccess:I=>{e.invalidateQueries({queryKey:["queue"]}),k([]),E(!1),n(I.message)},onError:()=>n(t("queue.toast.updateFailed"),"error")}),ie=mt({mutationFn:async I=>{for(const fe of I)await ue.cancelQueueItem(fe);return I.length},onSuccess:I=>{e.invalidateQueries({queryKey:["queue"]}),k([]),n(t("queue.toast.bulkCancelled",{count:I}))},onError:()=>n(t("queue.toast.bulkCancelFailed"),"error")}),Ne=I=>{k(fe=>fe.includes(I)?fe.filter(me=>me!==I):[...fe,I])},Oe=_.useMemo(()=>{const I=new Set;return B?.forEach(fe=>{fe.location&&I.add(fe.location)}),Z?.forEach(fe=>{fe.target_location&&I.add(fe.target_location)}),Array.from(I).sort()},[B,Z]),ge=_.useCallback(I=>d?I.target_location?I.target_location===d:I.printer_id?B?.find(me=>me.id===I.printer_id)?.location===d:!1:!0,[d,B]),Ke=_.useMemo(()=>{let I=Z?.filter(me=>me.status==="pending")||[];d&&(I=I.filter(ge));const fe=me=>{if(!me.scheduled_time)return 0;const Ee=new Date(me.scheduled_time).getTime(),z=Date.now()+4320*60*60*1e3;return Ee>z?0:Ee};return[...I].sort((me,Ee)=>{let z;if(F==="name"){const O=me.archive_name||me.library_file_name||"",ee=Ee.archive_name||Ee.library_file_name||"";z=O.localeCompare(ee)}else F==="printer"?z=(me.printer_name||"").localeCompare(Ee.printer_name||""):F==="time"?z=fe(me)-fe(Ee):z=me.position-Ee.position;return j?z:-z})},[Z,F,j,ge,d]),G=()=>{const I=Ke.map(fe=>fe.id);T.length===I.length?k([]):k(I)},Y=_.useMemo(()=>{let I=Z?.filter(fe=>fe.status==="printing")||[];return d&&(I=I.filter(ge)),I},[Z,d,ge]),ce=_.useMemo(()=>{let I=Z?.filter(fe=>["completed","failed","skipped","cancelled"].includes(fe.status))||[];return d&&(I=I.filter(ge)),[...I].sort((fe,me)=>{let Ee;if(D==="name"){const z=fe.archive_name||fe.library_file_name||"",O=me.archive_name||me.library_file_name||"";Ee=z.localeCompare(O)}else D==="printer"?Ee=(fe.printer_name||"").localeCompare(me.printer_name||""):Ee=new Date(me.completed_at||me.created_at).getTime()-new Date(fe.completed_at||fe.created_at).getTime();return R?-Ee:Ee})},[Z,D,R,ge,d]),q=_.useMemo(()=>Ke.reduce((I,fe)=>I+(fe.print_time_seconds||0),0),[Ke]),te=I=>{const{active:fe,over:me}=I;if(!me||fe.id===me.id)return;const Ee=Ke.findIndex(O=>O.id===fe.id),z=Ke.findIndex(O=>O.id===me.id);if(Ee!==-1&&z!==-1){const ee=V2(Ke,Ee,z).map((le,_e)=>({id:le.id,position:_e+1}));xe.mutate(ee)}};return s.jsxs("div",{className:"p-4 md:p-8",children:[s.jsx("div",{className:"flex items-center justify-between mb-8",children:s.jsxs("div",{children:[s.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[s.jsx(yW,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),s.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[s.jsx(_t,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:s.jsx(Is,{className:"w-5 h-5 text-blue-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Y.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.printing")})]})]})})}),s.jsx(_t,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center",children:s.jsx(er,{className:"w-5 h-5 text-yellow-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Ke.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.queued")})]})]})})}),s.jsx(_t,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-bambu-green/20 flex items-center justify-center",children:s.jsx(xu,{className:"w-5 h-5 text-bambu-green"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Rre(q)}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.totalTime")})]})]})})}),s.jsx(_t,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:s.jsx(Mt,{className:"p-4",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-gray-500/20 flex items-center justify-center",children:s.jsx(Ar,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:ce.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("queue.summary.history")})]})]})})})]}),s.jsxs("div",{className:"flex items-center gap-4 mb-6",children:[s.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:I=>{const fe=I.target.value;l(fe==="unassigned"?-1:fe===""?null:Number(fe))},children:[s.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),s.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),B?.map(I=>s.jsx("option",{value:I.id,children:I.name},I.id))]}),s.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:I=>u(I.target.value),children:[s.jsx("option",{value:"",children:t("queue.filter.allStatus")}),s.jsx("option",{value:"pending",children:t("queue.status.pending")}),s.jsx("option",{value:"printing",children:t("queue.status.printing")}),s.jsx("option",{value:"completed",children:t("queue.status.completed")}),s.jsx("option",{value:"failed",children:t("queue.status.failed")}),s.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),s.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),Oe.length>0&&s.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:I=>f(I.target.value),children:[s.jsx("option",{value:"",children:t("queue.filter.allLocations")}),Oe.map(I=>s.jsx("option",{value:I,children:I},I))]}),s.jsx("div",{className:"flex-1"}),ce.length>0&&s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>m(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[s.jsx(rn,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),ae?s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):Z?.length===0?s.jsxs(_t,{className:"p-12 text-center border-dashed",children:[s.jsx(si,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),s.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),s.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):s.jsxs("div",{className:"space-y-8",children:[Y.length>0&&s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white mb-4 flex items-center gap-2",children:[s.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),s.jsx("div",{className:"space-y-3",children:Y.map(I=>s.jsx(Hj,{item:I,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:I}),onRequeue:()=>{},onStart:()=>{},timeFormat:Q,hasPermission:r,canModify:a,t},I.id))})]}),Ke.length>0&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(er,{className:"w-5 h-5 text-yellow-400"}),t("queue.sections.queued"),s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:Ke.length}),")"]}),s.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.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:F,onChange:I=>$(I.target.value),children:[s.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),s.jsx("option",{value:"name",children:t("queue.sort.byName")}),s.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),s.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>H(!j),title:t(j?"common.ascending":"common.descending"),className:"px-2",children:j?s.jsx(Ig,{className:"w-4 h-4"}):s.jsx(G0,{className:"w-4 h-4"})})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 bg-bambu-dark rounded-lg",children:[s.jsxs(Te,{variant:"ghost",size:"sm",onClick:G,className:"flex items-center gap-2",children:[T.length===Ke.length&&Ke.length>0?s.jsx(ol,{className:"w-4 h-4 text-bambu-green"}):s.jsx(ll,{className:"w-4 h-4"}),T.length===Ke.length&&Ke.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),T.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:T.length})}),s.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),s.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>E(!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:[s.jsx(Qi,{className:"w-4 h-4"}),t("queue.bulkEdit.editSelected")]}),s.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>ie.mutate(T),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:ie.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?void 0:t("queue.permissions.noCancelItems"),children:[s.jsx(Rt,{className:"w-4 h-4"}),t("queue.bulkEdit.cancelSelected")]})]})]}),s.jsx(kre,{sensors:K,collisionDetection:fre,onDragEnd:te,children:s.jsx(Are,{items:Ke.map(I=>I.id),strategy:TWe,children:s.jsx("div",{className:"space-y-3",children:Ke.map((I,fe)=>s.jsx(Hj,{item:I,position:fe+1,onEdit:()=>b(I),onCancel:()=>N({type:"cancel",item:I}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>be.mutate(I.id),timeFormat:Q,isSelected:T.includes(I.id),onToggleSelect:()=>Ne(I.id),hasPermission:r,canModify:a,t},I.id))})})})]}),ce.length>0&&s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Ar,{className:"w-5 h-5 text-bambu-gray"}),t("queue.sections.history"),s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:ce.length}),")"]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.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:D,onChange:I=>A(I.target.value),children:[s.jsx("option",{value:"date",children:t("queue.sort.byDate")}),s.jsx("option",{value:"name",children:t("queue.sort.byName")}),s.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>U(!R),title:t(R?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:R?s.jsx(Ig,{className:"w-4 h-4"}):s.jsx(G0,{className:"w-4 h-4"})})]})]}),s.jsx("div",{className:"space-y-3",children:ce.slice(0,20).map((I,fe)=>s.jsx(Hj,{item:I,position:fe+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>N({type:"remove",item:I}),onStop:()=>{},onRequeue:()=>v(I),onStart:()=>{},timeFormat:Q,hasPermission:r,canModify:a,t},I.id))})]})]}),x&&s.jsx(jh,{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:()=>b(null)}),y&&s.jsx(jh,{mode:"add-to-queue",archiveId:y.archive_id??void 0,libraryFileId:y.library_file_id??void 0,archiveName:y.archive_name||y.library_file_name||`File #${y.archive_id||y.library_file_id}`,onClose:()=>v(null)}),S&&s.jsx(Zn,{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"?X.mutate(S.item.id):S.type==="stop"?se.mutate(S.item.id):ne.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),p&&s.jsx(Zn,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:ce.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{de.mutate(),m(!1)},onCancel:()=>m(!1)}),C&&s.jsx(BWe,{selectedCount:T.length,printers:B?.map(I=>({id:I.id,name:I.name}))||[],onSave:I=>{Object.keys(I).length>0&&Pe.mutate({item_ids:T,...I})},onClose:()=>E(!1),isSaving:Pe.isPending,t})]})}function $We({printDates:t,months:e=3}){const n=_.useRef(null),[r,i]=_.useState(0);_.useEffect(()=>{const S=n.current;if(!S)return;const N=new ResizeObserver(T=>{const k=T[0]?.contentRect.width||0;i(k)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:a,monthLabels:o,printCounts:l}=_.useMemo(()=>{const S={};t.forEach(U=>{const F=U.split("T")[0];S[F]=(S[F]||0)+1});const N=new Date,T=new Date(N);T.setMonth(T.getMonth()-e),T.setDate(T.getDate()-T.getDay());const k=[],C=[];let E=[],D=-1;const A=new Date(T);let R=0;for(;A<=N;)A.getDay()===0&&E.length>0&&(k.push(E),E=[],R++),A.getMonth()!==D&&(C.push({month:A.toLocaleDateString("en-US",{month:"short"}),weekIndex:R}),D=A.getMonth()),E.push(new Date(A)),A.setDate(A.getDate()+1);return E.length>0&&k.push(E),{weeks:k,monthLabels:C,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"],f=a.length,p=32,m=2,x=r-p-16,b=f>0?Math.floor((x-(f-1)*m)/f):12,y=Math.max(8,Math.min(20,b)),v=y<=10?10:12;return s.jsx("div",{ref:n,className:"w-full flex justify-center",children:r>0&&s.jsxs("div",{children:[s.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:S,weekIndex:N},T)=>s.jsx("div",{className:"text-bambu-gray",style:{fontSize:v,marginLeft:T===0?0:`${(N-(o[T-1]?.weekIndex||0))*(y+m)-24}px`},children:S},T))}),s.jsxs("div",{className:"flex",style:{gap:m},children:[s.jsx("div",{className:"flex flex-col",style:{gap:m,marginRight:4,width:p},children:d.map((S,N)=>s.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:y,fontSize:v,visibility:N%2===1?"visible":"hidden"},children:S},S))}),a.map((S,N)=>s.jsx("div",{className:"flex flex-col",style:{gap:m},children:[0,1,2,3,4,5,6].map(T=>{const k=S.find(A=>A.getDay()===T);if(!k)return s.jsx("div",{style:{width:y,height:y}},T);const C=k.toISOString().split("T")[0],E=l[C]||0,D=C===new Date().toISOString().split("T")[0];return s.jsx("div",{className:`rounded-sm ${u(E)} ${D?"ring-1 ring-white":""}`,style:{width:y,height:y},title:`${k.toLocaleDateString()}: ${E} print${E!==1?"s":""}`},T)})},N))]}),s.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:v},children:[s.jsx("span",{children:"Less"}),s.jsxs("div",{className:"flex",style:{gap:m},children:[s.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:y,height:y}}),s.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:y,height:y}})]}),s.jsx("span",{children:"More"})]})]})})}const d1=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function VWe(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 GWe({archives:t,currency:e="$"}){const[n,r]=_.useState("30d"),i=_.useMemo(()=>{const m=VWe(n);return t.filter(x=>(Ii(x.completed_at||x.created_at)||new Date(0))>=m)},[t,n]),a=_.useMemo(()=>{const m=new Map;return i.forEach(x=>{const b=Ii(x.completed_at||x.created_at)||new Date,y=`${b.getFullYear()}-${String(b.getMonth()+1).padStart(2,"0")}-${String(b.getDate()).padStart(2,"0")}`,v=m.get(y)||{date:y,filament:0,cost:0,prints:0},S=x.quantity||1;v.filament+=(x.filament_used_grams||0)*S,v.cost+=x.cost||0,v.prints+=S,m.set(y,v)}),Array.from(m.values()).sort((x,b)=>x.date.localeCompare(b.date)).map(x=>({...x,dateLabel:new Date(x.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=_.useMemo(()=>{if(n==="7d"||n==="30d")return a;const m=new Map;return i.forEach(x=>{const b=Ii(x.completed_at||x.created_at)||new Date,y=new Date(b);y.setDate(b.getDate()-b.getDay());const v=`${y.getFullYear()}-${String(y.getMonth()+1).padStart(2,"0")}-${String(y.getDate()).padStart(2,"0")}`,S=m.get(v)||{week:v,filament:0,cost:0,prints:0},N=x.quantity||1;S.filament+=(x.filament_used_grams||0)*N,S.cost+=x.cost||0,S.prints+=N,m.set(v,S)}),Array.from(m.values()).sort((x,b)=>x.week.localeCompare(b.week)).map(x=>({date:x.week,dateLabel:`Week of ${new Date(x.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...x}))},[i,a,n]),l=_.useMemo(()=>{const m=new Map;return i.forEach(x=>{const b=x.filament_type||"Unknown",y=x.quantity||1,v=b.split(", ");v.forEach(S=>{const N=(x.filament_used_grams||0)*y/v.length;m.set(S,(m.get(S)||0)+N)})}),Array.from(m.entries()).map(([x,b])=>({name:x,value:Math.round(b)})).sort((x,b)=>b.value-x.value)},[i]),c=_.useMemo(()=>{const m=new Date,x=[];for(let b=5;b>=0;b--){const y=new Date(m.getFullYear(),m.getMonth()-b,1),v=new Date(m.getFullYear(),m.getMonth()-b+1,0),S=y.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(T=>{const k=Ii(T.completed_at||T.created_at)||new Date(0);return k>=y&&k<=v});x.push({month:S,filament:Math.round(N.reduce((T,k)=>T+(k.filament_used_grams||0)*(k.quantity||1),0)),cost:N.reduce((T,k)=>T+(k.cost||0),0),prints:N.reduce((T,k)=>T+(k.quantity||1),0)})}return x},[t]),u=n==="7d"||n==="30d"?a:o,d=i.reduce((m,x)=>m+(x.filament_used_grams||0)*(x.quantity||1),0),f=i.reduce((m,x)=>m+(x.cost||0),0),p=i.reduce((m,x)=>m+(x.quantity||1),0);return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:"Filament Usage Trends"}),s.jsx("div",{className:"flex gap-1 bg-bambu-dark rounded-lg p-1",children:["7d","30d","90d","365d","all"].map(m=>s.jsx("button",{onClick:()=>r(m),className:`px-3 py-1 text-sm rounded-md transition-colors ${n===m?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:m==="all"?"All":m.replace("d","D")},m))})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Filament"}),s.jsxs("p",{className:"text-2xl font-bold text-white",children:[(d/1e3).toFixed(2),"kg"]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[d.toFixed(0),"g total"]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Period Cost"}),s.jsxs("p",{className:"text-2xl font-bold text-white",children:[e,f.toFixed(2)]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[p," prints"]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Avg per Print"}),s.jsxs("p",{className:"text-2xl font-bold text-white",children:[p>0?(d/p).toFixed(0):0,"g"]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,p>0?(f/p).toFixed(2):"0.00"," avg"]})]})]}),u.length>0?s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Usage Over Time"}),s.jsx(v1,{width:"100%",height:250,children:s.jsxs(zCe,{data:u,children:[s.jsx("defs",{children:s.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[s.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),s.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),s.jsx(BS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx($S,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),s.jsx(VS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),s.jsx(_1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:m=>[`${Number(m??0).toFixed(0)}g`,"Filament"]}),s.jsx(PZ,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):s.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:"No data for selected time range"}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"By Filament Type"}),l.length>0?s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsx(v1,{width:160,height:160,children:s.jsxs(ICe,{children:[s.jsx(nZ,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((m,x)=>s.jsx(cv,{fill:d1[x%d1.length]},`cell-${x}`))}),s.jsx(_1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:m=>[`${m??0}g`,"Usage"]})]})}),s.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:l.map((m,x)=>{const b=l.reduce((v,S)=>v+S.value,0),y=b>0?(m.value/b*100).toFixed(0):0;return s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:d1[x%d1.length]}}),s.jsx("span",{className:"text-white truncate flex-1",children:m.name}),s.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[y,"%"]})]},m.name)})})]}):s.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:"No filament data"})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[s.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:"Monthly Comparison"}),s.jsx(v1,{width:"100%",height:200,children:s.jsxs(kCe,{data:c,children:[s.jsx(BS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx($S,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),s.jsx(VS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),s.jsx(_1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(m,x)=>[x==="filament"?`${m??0}g`:x==="cost"?`${e}${Number(m??0).toFixed(2)}`:m??0,x==="filament"?"Filament":x==="cost"?"Cost":"Prints"]}),s.jsx(dO,{}),s.jsx(lZ,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function qWe({id:t,title:e,component:n,isHidden:r,size:i,onToggleVisibility:a,onToggleSize:o}){const{attributes:l,listeners:c,setNodeRef:u,transform:d,transition:f,isDragging:p}=jre({id:t}),m={transform:mx.Transform.toString(d),transition:f,opacity:p?.5:1};return r?null:s.jsxs("div",{ref:u,style:{...m,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${p?"ring-2 ring-bambu-green shadow-lg":""}`,children:[s.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.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:s.jsx(zg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),s.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.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?s.jsx(wW,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):s.jsx(vW,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),s.jsx("button",{onClick:a,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:s.jsx(lN,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),s.jsx("div",{className:"p-4",children:typeof n=="function"?n(i):n})]})}function WWe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:a}){const o=()=>{const T={};return t.forEach(k=>{T[k.id]=k.defaultSize||4}),T},[l,c]=_.useState(()=>{const T=localStorage.getItem(e);if(T)try{const k=JSON.parse(T);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]=_.useState(!1);_.useEffect(()=>{const T=()=>d(k=>!k);return window.addEventListener("toggle-hidden-panel",T),()=>window.removeEventListener("toggle-hidden-panel",T)},[]),_.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),_.useEffect(()=>{const k=t.map(C=>C.id).filter(C=>!l.order.includes(C));k.length>0&&c(C=>({...C,order:[...C.order,...k]}))},[t,l.order]);const f=cre(ZM(B2,{activationConstraint:{distance:8}}),ZM(z2,{coordinateGetter:Pre})),p=T=>{const{active:k,over:C}=T;C&&k.id!==C.id&&c(E=>{const D=E.order.indexOf(k.id),A=E.order.indexOf(C.id);return{...E,order:V2(E.order,D,A)}})},m=T=>{c(k=>({...k,hidden:k.hidden.includes(T)?k.hidden.filter(C=>C!==T):[...k.hidden,T]}))},x=T=>{c(k=>{const C=k.sizes[T]||4,E=C===1?2:C===2?4:1;return{...k,sizes:{...k.sizes,[T]:E}}})},b=()=>{const T={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:o()};c(T),i?.()},y=l.order.map(T=>t.find(k=>k.id===T)).filter(Boolean),v=y.filter(T=>!l.hidden.includes(T.id)),S=y.filter(T=>l.hidden.includes(T.id)),N=a?.({hiddenCount:S.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:b});return s.jsxs("div",{className:"space-y-4",children:[N,!r&&!a&&s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsxs(Te,{variant:"secondary",size:"sm",onClick:b,children:[s.jsx(Rh,{className:"w-4 h-4"}),"Reset Layout"]}),S.length>0&&s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[s.jsx(Ru,{className:"w-4 h-4"}),S.length," Hidden"]})]}),u&&S.length>0&&s.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(T=>s.jsxs("button",{onClick:()=>m(T.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:[s.jsx(Ru,{className:"w-3 h-3"}),T.title]},T.id))})]}),s.jsx(kre,{sensors:f,collisionDetection:fre,onDragEnd:p,children:s.jsx(Are,{items:v.map(T=>T.id),strategy:lF,children:s.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:v.map(T=>s.jsx(qWe,{id:T.id,title:T.title,component:T.component,isHidden:l.hidden.includes(T.id),size:l.sizes[T.id]||2,onToggleVisibility:()=>m(T.id),onToggleSize:()=>x(T.id)},T.id))})})}),v.length===0&&s.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[s.jsx("p",{children:"All widgets are hidden."}),s.jsx(Te,{className:"mt-4",onClick:b,children:"Reset Layout"})]})]})}function KWe({stats:t,currency:e,t:n}){return s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-bambu-green",children:s.jsx(mc,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.totalPrints")}),s.jsx("p",{className:"text-xl font-bold text-white",children:t?.total_prints||0})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-blue-400",children:s.jsx(er,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.printTime")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_print_time_hours.toFixed(1)||0,"h"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-orange-400",children:s.jsx(mc,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentUsed")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[((t?.total_filament_grams||0)/1e3).toFixed(2),"kg"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-green-400",children:s.jsx(hP,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.filamentCost")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_cost.toFixed(2)||"0.00"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-400",children:s.jsx(vh,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyUsed")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[t?.total_energy_kwh.toFixed(2)||"0.00"," kWh"]})]})]}),s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark text-yellow-500",children:s.jsx(hP,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:n("stats.energyCost")}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function XWe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,a=n===1?112:n===2?128:144,o=a/2-8,l=o*2*Math.PI;return s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"relative flex-shrink-0",style:{width:a,height:a},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:a/2,cy:a/2,r:o,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:a/2,cy:a/2,r:o,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${i/100*l} ${l}`})]}),s.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:s.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i,"%"]})})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),s.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Yi,{className:"w-4 h-4 text-status-error flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),s.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&&s.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),s.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])=>s.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[s.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(c)||`${r("common.printer")} ${c}`}),s.jsx("span",{className:"text-white font-medium",children:u})]},c))})]})]})]})}function YWe({stats:t,printerMap:e,size:n=1,t:r}){const i=t?.average_time_accuracy;if(i==null)return s.jsx("div",{className:"flex items-center justify-center h-full",children:s.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=(b=>b>=95&&b<=105?"#00ae42":b>105?"#3b82f6":"#f97316")(i),u=i-100,d=n===1?112:n===2?128:144,f=d/2-8,p=f*2*Math.PI,m=n===1?3:n===2?6:999,x=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,m):[];return s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"relative flex-shrink-0",style:{width:d,height:d},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:d/2,cy:d/2,r:f,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:d/2,cy:d/2,r:f,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[s.jsxs("span",{className:`font-bold text-white ${n>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),s.jsxs("span",{className:`text-xs ${u>=0?"text-blue-400":"text-orange-400"}`,children:[u>=0?"+":"",u.toFixed(0),"%"]})]})]}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[s.jsx(EW,{className:"w-3 h-3 flex-shrink-0"}),s.jsx("span",{children:r("stats.perfectEstimate")})]}),x.length>0&&s.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(([b,y])=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(b)||`${r("common.printer")} ${b}`}),s.jsxs("span",{className:`font-medium ${y>=95&&y<=105?"text-status-ok":y>105?"text-blue-400":"text-status-warning"}`,children:[y.toFixed(0),"%"]})]},b))})]})]})}function QWe({stats:t,size:e=1,t:n}){if(!t?.prints_by_filament_type||Object.keys(t.prints_by_filament_type).length===0)return s.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,a=r.slice(0,i),o=r.length>i;return e===4&&a.length>4?s.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[s.jsx("span",{className:"text-white truncate max-w-[120px]",children:l}),s.jsx("span",{className:"text-bambu-gray",children:c})]}),s.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:s.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)})}):s.jsxs("div",{className:"space-y-3",children:[a.map(([l,c])=>{const u=Math.round(c/(t.total_prints||1)*100);return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[s.jsx("span",{className:"text-white",children:l}),s.jsxs("span",{className:"text-bambu-gray",children:[c," ",n("common.prints")]})]}),s.jsx("div",{className:"h-2 bg-bambu-dark rounded-full",children:s.jsx("div",{className:"h-full bg-bambu-green rounded-full transition-all",style:{width:`${u}%`}})})]},l)}),o&&s.jsx("p",{className:"text-xs text-bambu-gray text-center pt-1",children:n("common.more",{count:r.length-i})})]})}function ZWe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return s.jsx($We,{printDates:t,months:n})}function JWe({stats:t,printerMap:e,t:n}){return!t?.prints_by_printer||Object.keys(t.prints_by_printer).length===0?s.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrinterData")}):s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([r,i])=>s.jsxs("div",{className:"flex items-center gap-3 p-3 bg-bambu-dark rounded-lg",children:[s.jsx("div",{className:"p-2 bg-bambu-dark-tertiary rounded-lg",children:s.jsx(Ur,{className:"w-4 h-4 text-bambu-green"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium text-sm",children:e.get(r)||`${n("common.printer")} ${r}`}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[i," ",n("common.prints")]})]})]},r))})}function eKe({archives:t,currency:e,t:n}){return!t||t.length===0?s.jsx("p",{className:"text-bambu-gray text-center py-4",children:n("stats.noPrintData")}):s.jsx(GWe,{archives:t,currency:e})}function tKe({size:t=1,t:e}){const{data:n,isLoading:r}=at({queryKey:["failureAnalysis"],queryFn:()=>ue.getFailureAnalysis({days:30})});if(r)return s.jsx("div",{className:"flex justify-center py-4",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!n||n.total_prints===0)return s.jsx("p",{className:"text-bambu-gray text-center py-4",children:e("stats.noPrintDataLast30Days")});const i=t===1?5:t===2?8:999,a=Object.entries(n.failures_by_reason).sort(([,c],[,u])=>u-c),o=a.slice(0,i),l=a.length>i;return s.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[s.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[s.jsx("div",{className:"flex items-center gap-4",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Cn,{className:`w-5 h-5 ${n.failure_rate>20?"text-status-error":n.failure_rate>10?"text-status-warning":"text-status-ok"}`}),s.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[n.failure_rate.toFixed(1),"%"]})]})}),s.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&&s.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx(AW,{className:`w-4 h-4 ${n.trend[n.trend.length-1].failure_rate0&&s.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[s.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?e("stats.failureReasons"):e("stats.topFailureReasons")}),s.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:o.map(([c,u])=>s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:c||e("common.unknown")}),s.jsx("span",{className:"text-bambu-gray ml-2",children:u})]},c))}),l&&s.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("common.more",{count:a.length-i})})]})]})}function nKe(){const{t}=Hn(),{showToast:e}=$n(),{hasPermission:n}=Ai(),[r,i]=_.useState(!1),[a,o]=_.useState(!1),[l,c]=_.useState(0),[u,d]=_.useState(0),[f,p]=_.useState(!1);_.useEffect(()=>{const A=()=>{try{const U=localStorage.getItem("bambusy-dashboard-layout");if(U){const F=JSON.parse(U);d(F.hidden?.length||0)}}catch{d(0)}};A(),window.addEventListener("storage",A);const R=setInterval(A,500);return()=>{window.removeEventListener("storage",A),clearInterval(R)}},[l]);const{data:m,isLoading:x,refetch:b}=at({queryKey:["archiveStats"],queryFn:ue.getArchiveStats}),{data:y}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:v}=at({queryKey:["archives"],queryFn:()=>ue.getArchives(void 0,void 0,1e3,0)}),{data:S}=at({queryKey:["settings"],queryFn:ue.getSettings}),N=async A=>{o(!1),i(!0);try{const{blob:R,filename:U}=await ue.exportStats({format:A,days:90}),F=URL.createObjectURL(R),$=document.createElement("a");$.href=F,$.download=U,$.click(),URL.revokeObjectURL(F),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{i(!1)}},T=async()=>{p(!0);try{const A=await ue.recalculateCosts();await b(),e(t("stats.recalculatedCosts",{count:A.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{p(!1)}},k=S?.currency||"$",C=new Map(y?.map(A=>[String(A.id),A.name])||[]),E=v?.map(A=>A.created_at)||[];if(x)return s.jsx("div",{className:"p-4 md:p-8",children:s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const D=[{id:"quick-stats",title:t("stats.quickStats"),component:s.jsx(KWe,{stats:m,currency:k,t}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:A=>s.jsx(XWe,{stats:m,printerMap:C,size:A,t}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:A=>s.jsx(YWe,{stats:m,printerMap:C,size:A,t}),defaultSize:1},{id:"filament-types",title:t("stats.filamentTypes"),component:A=>s.jsx(QWe,{stats:m,size:A,t}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:A=>s.jsx(tKe,{size:A,t}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:A=>s.jsx(ZWe,{printDates:E,size:A}),defaultSize:2},{id:"prints-by-printer",title:t("stats.printsByPrinter"),component:s.jsx(JWe,{stats:m,printerMap:C,t}),defaultSize:2},{id:"filament-trends",title:t("stats.filamentTrends"),component:s.jsx(eKe,{archives:v||[],currency:k,t}),defaultSize:4}];return s.jsxs("div",{className:"p-4 md:p-8",children:[s.jsxs("div",{className:"flex items-center justify-between mb-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold text-white",children:t("stats.title")}),s.jsx("p",{className:"text-bambu-gray",children:t("stats.subtitle")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u>0&&s.jsxs(Te,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[s.jsx(Ru,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),s.jsxs(Te,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),c(A=>A+1),e(t("stats.layoutReset"))},disabled:!n("settings:update"),title:n("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[s.jsx(Rh,{className:"w-4 h-4"}),t("stats.resetLayout")]}),s.jsxs(Te,{variant:"secondary",onClick:T,disabled:f||!n("archives:update_all"),title:n("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[f?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Tce,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),s.jsxs("div",{className:"relative",children:[s.jsxs(Te,{variant:"secondary",onClick:()=>o(!a),disabled:r,children:[r?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(q1,{className:"w-4 h-4"}),t("stats.exportStats")]}),a&&s.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:[s.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:[s.jsx(Ls,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),s.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:[s.jsx(q1,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]})]})]}),s.jsx(WWe,{widgets:D,storageKey:"bambusy-dashboard-layout",hideControls:!0},l)]})}function rKe({plug:t,onEdit:e}){const n=an(),{showToast:r}=$n(),[i,a]=_.useState(!1),[o,l]=_.useState(!1),[c,u]=_.useState(!1),[d,f]=_.useState(!1),{data:p,isLoading:m}=at({queryKey:["smart-plug-status",t.id],queryFn:()=>ue.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:x}=at({queryKey:["printers"],queryFn:ue.getPrinters}),b=x?.find(A=>A.id===t.printer_id),y=mt({mutationFn:A=>ue.controlSmartPlug(t.id,A),onMutate:async A=>{await n.cancelQueries({queryKey:["smart-plug-status",t.id]});const R=n.getQueryData(["smart-plug-status",t.id]),U=A==="on"?"ON":A==="off"||p?.state==="ON"?"OFF":"ON";return n.setQueryData(["smart-plug-status",t.id],F=>({...F,state:U})),{previousStatus:R}},onError:(A,R,U)=>{U?.previousStatus&&n.setQueryData(["smart-plug-status",t.id],U.previousStatus),r(`Failed to turn ${R} "${t.name}"`,"error")},onSettled:()=>{setTimeout(()=>{n.invalidateQueries({queryKey:["smart-plug-status",t.id]}),n.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),v=mt({mutationFn:A=>ue.updateSmartPlug(t.id,A),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&n.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]})}}),S=mt({mutationFn:()=>ue.deleteSmartPlug(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]})}}),N=p?.state==="ON",T=t.plug_type==="mqtt"&&p?.energy?.power!==null&&p?.energy?.power!==void 0,k=(p?.reachable??!1)||T,C=y.isPending,D=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const A=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${A}/`:`http://${A}/`})();return s.jsxs(s.Fragment,{children:[s.jsx(_t,{className:"relative",children:s.jsxs(Mt,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[s.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?k?"bg-teal-500/20":"bg-red-500/20":k?N?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?s.jsx(jR,{className:`w-5 h-5 ${k?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?s.jsx(fN,{className:`w-5 h-5 ${k?N?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):s.jsx(tl,{className:`w-5 h-5 ${k?N?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),s.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})]})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[m?s.jsx(ht,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?s.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[s.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"}),k&&s.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?s.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[s.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),s.jsx("span",{className:k?N?"text-status-ok":"text-bambu-gray":"text-status-error",children:k?p?.state||"?":"Offline"})]}):k?s.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[s.jsx(Sg,{className:"w-4 h-4 text-status-ok"}),s.jsx("span",{className:N?"text-status-ok":"text-bambu-gray",children:p?.state||"Unknown"})]}):s.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[s.jsx(sm,{className:"w-4 h-4"}),s.jsx("span",{children:"Offline"})]}),D&&s.jsxs("a",{href:D,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:"Open plug admin page",children:[s.jsx(Kr,{className:"w-3 h-3"}),"Admin"]})]})]}),b&&s.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Linked to: "}),s.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&s.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&s.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:[s.jsx(Ru,{className:"w-3 h-3"}),"Monitor Only"]}),t.power_alert_enabled&&s.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:[s.jsx(wg,{className:"w-3 h-3"}),"Alerts"]}),t.schedule_enabled&&s.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:[s.jsx(si,{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"&&s.jsxs("div",{className:"flex gap-2 mb-3",children:[s.jsxs(Te,{size:"sm",variant:N?"primary":"secondary",disabled:!k||C,onClick:()=>l(!0),className:"flex-1",children:[C?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Gu,{className:"w-4 h-4"}),"On"]}),s.jsxs(Te,{size:"sm",variant:N?"secondary":"primary",disabled:!k||C,onClick:()=>u(!0),className:"flex-1",children:[C?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(gN,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&p?.energy&&s.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&&s.jsxs("div",{className:"flex-1 text-center",children:[s.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(p.energy.power),"W"]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),p.energy.today!==null&&p.energy.today!==void 0&&s.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-lg font-semibold text-white",children:p.energy.today.toFixed(2)}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"kWh Today"})]})]}),s.jsxs("button",{onClick:()=>f(!d),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(bh,{className:"w-4 h-4"}),t.plug_type==="mqtt"?"Settings":"Automation Settings"]}),s.jsx("span",{children:d?"-":"+"})]}),d&&s.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mN,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Show in Switchbar"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:A=>v.mutate({show_in_switchbar:A.target.checked}),className:"sr-only peer"}),s.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"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Enabled"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Enable automation for this plug"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.enabled,onChange:A=>v.mutate({enabled:A.target.checked}),className:"sr-only peer"}),s.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"})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Auto On"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn on when print starts"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:A=>v.mutate({auto_on:A.target.checked}),className:"sr-only peer"}),s.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"})]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Auto Off"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Turn off when print completes (one-shot)"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:A=>v.mutate({auto_off:A.target.checked}),className:"sr-only peer"}),s.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&&s.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white mb-2",children:"Turn Off Delay Mode"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("button",{onClick:()=>v.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:[s.jsx(er,{className:"w-4 h-4"}),"Time"]}),s.jsxs("button",{onClick:()=>v.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:[s.jsx(bN,{className:"w-4 h-4"}),"Temp"]})]})]}),t.off_delay_mode==="time"?s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Delay (minutes)"}),s.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:A=>v.mutate({off_delay_minutes:parseInt(A.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"})]}):s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Temperature threshold (C)"}),s.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:A=>v.mutate({off_temp_threshold:parseInt(A.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Turns off when nozzle cools below this temperature"})]})]})]}),s.jsxs("div",{className:"flex gap-2 pt-2",children:[s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx(fg,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>a(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(rn,{className:"w-4 h-4"})})]})]})]})}),i&&s.jsx(Zn,{title:"Delete Smart Plug",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{S.mutate(),a(!1)},onCancel:()=>a(!1)}),o&&s.jsx(Zn,{title:"Turn On Smart Plug",message:`Are you sure you want to turn on "${t.name}"?`,confirmText:"Turn On",variant:"default",onConfirm:()=>{y.mutate("on"),l(!1)},onCancel:()=>l(!1)}),c&&s.jsx(Zn,{title:"Turn Off Smart Plug",message:`Are you sure you want to turn off "${t.name}"? This will cut power to the connected device.`,confirmText:"Turn Off",variant:"danger",onConfirm:()=>{y.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function iKe({plug:t,onClose:e}){const n=an(),r=!!t,[i,a]=_.useState(t?.plug_type||"tasmota"),[o,l]=_.useState(t?.name||""),[c,u]=_.useState(t?.ip_address||""),[d,f]=_.useState(t?.username||""),[p,m]=_.useState(t?.password||""),[x,b]=_.useState(t?.ha_entity_id||""),[y,v]=_.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[S,N]=_.useState(t?.mqtt_power_path||""),[T,k]=_.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,E]=_.useState(t?.mqtt_energy_topic||""),[D,A]=_.useState(t?.mqtt_energy_path||""),[R,U]=_.useState((t?.mqtt_energy_multiplier??1).toString()),[F,$]=_.useState(t?.mqtt_state_topic||""),[j,H]=_.useState(t?.mqtt_state_path||""),[K,V]=_.useState(t?.mqtt_state_on_value||""),[Q,Z]=_.useState(t?.ha_power_entity||""),[ae,B]=_.useState(t?.ha_energy_today_entity||""),[X,ne]=_.useState(t?.ha_energy_total_entity||""),[se,be]=_.useState(""),[xe,de]=_.useState(""),[Pe,ie]=_.useState(!1),Ne=_.useRef(null),[Oe,ge]=_.useState(""),[Ke,G]=_.useState(!1),Y=_.useRef(null),[ce,q]=_.useState(""),[te,I]=_.useState(!1),fe=_.useRef(null),[me,Ee]=_.useState(""),[z,O]=_.useState(!1),ee=_.useRef(null),[le,_e]=_.useState(t?.printer_id||null),[we,re]=_.useState(null),[Fe,He]=_.useState(null),[Ve,$e]=_.useState(t?.power_alert_enabled||!1),[ye,je]=_.useState(t?.power_alert_high?.toString()||""),[Be,Se]=_.useState(t?.power_alert_low?.toString()||""),[Xe,Me]=_.useState(t?.schedule_enabled||!1),[tt,ke]=_.useState(t?.schedule_on_time||""),[We,ze]=_.useState(t?.schedule_off_time||""),[W,De]=_.useState(t?.show_in_switchbar||!1),[Ye,xt]=_.useState(!1),[ft,Bt]=_.useState({scanned:0,total:0}),[Lt,vn]=_.useState([]),Jt=_.useRef(null),{data:ir}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:fr}=at({queryKey:["smart-plugs"],queryFn:ue.getSmartPlugs}),{data:Dn}=at({queryKey:["settings"],queryFn:ue.getSettings}),ln=!!(Dn?.ha_enabled&&Dn?.ha_url&&Dn?.ha_token);_.useEffect(()=>{const pe=setTimeout(()=>{de(se)},300);return()=>clearTimeout(pe)},[se]),_.useEffect(()=>{const pe=Ie=>{Ne.current&&!Ne.current.contains(Ie.target)&&ie(!1),Y.current&&!Y.current.contains(Ie.target)&&G(!1),fe.current&&!fe.current.contains(Ie.target)&&I(!1),ee.current&&!ee.current.contains(Ie.target)&&O(!1)};return document.addEventListener("mousedown",pe),()=>document.removeEventListener("mousedown",pe)},[]);const{data:mr,isLoading:Fn,error:Xn}=at({queryKey:["ha-entities",xe],queryFn:()=>ue.getHAEntities(xe||void 0),enabled:i==="homeassistant"&&ln,retry:!1,staleTime:0}),{data:bn}=at({queryKey:["ha-sensor-entities"],queryFn:ue.getHASensorEntities,enabled:i==="homeassistant"&&ln,retry:!1,staleTime:0});_.useEffect(()=>{const pe=Ie=>{Ie.key==="Escape"&&e()};return window.addEventListener("keydown",pe),()=>{window.removeEventListener("keydown",pe),Jt.current&&clearInterval(Jt.current)}},[e]);const wi=async()=>{xt(!0),vn([]),Bt({scanned:0,total:0}),He(null);try{await ue.startTasmotaScan();const pe=async()=>{try{const Ie=await ue.getTasmotaScanStatus();Bt({scanned:Ie.scanned,total:Ie.total});const Le=await ue.getDiscoveredTasmotaDevices();vn(Le),Ie.running||(xt(!1),Jt.current&&(clearInterval(Jt.current),Jt.current=null))}catch(Ie){console.error("Polling error:",Ie)}};await pe(),Jt.current=setInterval(pe,500)}catch(pe){xt(!1);const Ie=pe instanceof Error?pe.message:typeof pe=="string"?pe:JSON.stringify(pe);He(Ie||"Failed to start scan")}},Ba=async()=>{try{await ue.stopTasmotaScan()}catch{}xt(!1),Jt.current&&(clearInterval(Jt.current),Jt.current=null)},Ae=pe=>{u(pe.ip_address),l(pe.name),re(null)},Ze=mt({mutationFn:()=>ue.testSmartPlugConnection(c,d||null,p||null),onSuccess:pe=>{re(pe),He(null),!o&&pe.device_name&&l(pe.device_name)},onError:pe=>{re(null),He(pe.message)}}),st=mt({mutationFn:pe=>ue.createSmartPlug(pe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:pe=>{He(pe.message)}}),lt=mt({mutationFn:pe=>ue.updateSmartPlug(t.id,pe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:pe=>{He(pe.message)}}),ot=ir?.filter(pe=>!fr?.some(Le=>Le.printer_id===pe.id&&Le.id!==t?.id)),Et=pe=>{if(pe.preventDefault(),He(null),!o.trim()){He("Name is required");return}if(i==="tasmota"&&!c.trim()){He("IP address is required for Tasmota plugs");return}if(i==="homeassistant"&&!x){He("Entity is required for Home Assistant plugs");return}if(i==="mqtt"){const Le=y.trim(),Ce=C.trim(),ut=F.trim();if(!Le&&!Ce&&!ut){He("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const Ie={name:o.trim(),plug_type:i,ip_address:i==="tasmota"?c.trim():null,ha_entity_id:i==="homeassistant"?x:null,ha_power_entity:i==="homeassistant"&&Q||null,ha_energy_today_entity:i==="homeassistant"&&ae||null,ha_energy_total_entity:i==="homeassistant"&&X||null,mqtt_power_topic:i==="mqtt"&&y.trim()||null,mqtt_power_path:i==="mqtt"&&S.trim()||null,mqtt_power_multiplier:i==="mqtt"&&parseFloat(T)||1,mqtt_energy_topic:i==="mqtt"&&C.trim()||null,mqtt_energy_path:i==="mqtt"&&D.trim()||null,mqtt_energy_multiplier:i==="mqtt"&&parseFloat(R)||1,mqtt_state_topic:i==="mqtt"&&F.trim()||null,mqtt_state_path:i==="mqtt"&&j.trim()||null,mqtt_state_on_value:i==="mqtt"&&K.trim()||null,username:i==="tasmota"&&d.trim()||null,password:i==="tasmota"&&p.trim()||null,printer_id:le,power_alert_enabled:Ve,power_alert_high:ye?parseFloat(ye):null,power_alert_low:Be?parseFloat(Be):null,schedule_enabled:Xe,schedule_on_time:tt||null,schedule_off_time:We||null,show_in_switchbar:W};r?lt.mutate(Ie):st.mutate(Ie)},he=st.isPending||lt.isPending;return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:s.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:pe=>pe.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Smart Plug":"Add Smart Plug"}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:Et,className:"p-6 space-y-4 overflow-y-auto",children:[Fe&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:Fe}),!r&&s.jsxs("div",{className:"flex gap-2 mb-2",children:[s.jsxs("button",{type:"button",onClick:()=>{a("tasmota"),re(null),He(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${i==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[s.jsx(tl,{className:"w-4 h-4"}),"Tasmota"]}),s.jsxs("button",{type:"button",onClick:()=>{a("homeassistant"),re(null),He(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${i==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[s.jsx(fN,{className:"w-4 h-4"}),"HA"]}),s.jsxs("button",{type:"button",onClick:()=>{a("mqtt"),re(null),He(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${i==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[s.jsx(jR,{className:"w-4 h-4"}),"MQTT"]})]}),!r&&i==="tasmota"&&s.jsxs("div",{className:"space-y-3",children:[Ye?s.jsxs(Te,{type:"button",variant:"secondary",onClick:Ba,className:"w-full",children:[s.jsx(Rt,{className:"w-4 h-4"}),"Stop Scanning"]}):s.jsxs(Te,{type:"button",variant:"primary",onClick:wi,className:"w-full",children:[s.jsx(ba,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),Ye&&ft.total>0&&s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[s.jsx("span",{children:"Scanning network..."}),s.jsxs("span",{children:[ft.scanned," / ",ft.total]})]}),s.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:s.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${ft.scanned/ft.total*100}%`}})})]}),Lt.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("p",{className:"text-xs text-bambu-gray",children:["Found ",Lt.length," device(s) - click to select:"]}),s.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Lt.map(pe=>s.jsxs("button",{type:"button",onClick:()=>Ae(pe),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:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(tl,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:pe.name}),s.jsx("p",{className:"text-xs text-bambu-gray",children:pe.ip_address})]})]}),pe.state&&s.jsxs("span",{className:`flex items-center gap-1 text-xs ${pe.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[s.jsx(Gu,{className:"w-3 h-3"}),pe.state]})]},pe.ip_address))})]}),!Ye&&Lt.length===0&&ft.total>0&&s.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:"No Tasmota devices found on your network"})]}),i==="homeassistant"&&s.jsxs("div",{className:"space-y-3",children:[!ln&&s.jsxs("div",{className:"space-y-3",children:[s.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"," ",s.jsx("span",{className:"font-medium",children:"Settings → Network → Home Assistant"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:"Select Entity *"}),s.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:s.jsx("option",{children:"Choose an entity..."})})]})]}),ln&&s.jsxs(s.Fragment,{children:[Fn&&s.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[s.jsx(ht,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Xn&&s.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: ",Xn.message]}),(()=>{const pe=fr?.filter(Ce=>Ce.ha_entity_id&&Ce.id!==t?.id).map(Ce=>Ce.ha_entity_id)||[],Ie=(mr||[]).filter(Ce=>!pe.includes(Ce.entity_id)),Le=mr?.find(Ce=>Ce.entity_id===x);return s.jsxs("div",{ref:Ne,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Select Entity *"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:Pe?se:Le?`${Le.friendly_name} (${Le.entity_id})`:"",onChange:Ce=>{be(Ce.target.value),Pe||ie(!0)},onFocus:()=>{ie(!0),be("")},placeholder:"Search entities...",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"}),x&&!Pe&&s.jsx("button",{type:"button",onClick:()=>{b(""),be("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Fn&&s.jsx(ht,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),Pe&&s.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:[Fn&&s.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Fn&&Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:xe?`No entities found matching "${xe}"`:"No entities available"}),!Fn&&Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{b(Ce.entity_id),ie(!1),be(""),o||l(Ce.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Ce.entity_id===x?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[s.jsx("span",{children:Ce.entity_id}),s.jsx("span",{className:Ce.state==="on"?"text-bambu-green":"",children:Ce.state})]})]},Ce.entity_id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:xe?`Searching all entities (${Ie.length} found)`:`Showing switch, light, input_boolean (${Ie.length} available)`})]})})(),x&&bn&&bn.length>0&&s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium mb-1",children:"Energy Monitoring (Optional)"}),s.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:"Search and select sensors that provide power/energy data."})]}),(()=>{const pe=bn.filter(Ce=>Ce.unit_of_measurement==="W"||Ce.unit_of_measurement==="kW"||Ce.unit_of_measurement==="mW"),Ie=Oe?pe.filter(Ce=>Ce.entity_id.toLowerCase().includes(Oe.toLowerCase())||Ce.friendly_name.toLowerCase().includes(Oe.toLowerCase())):pe,Le=bn.find(Ce=>Ce.entity_id===Q);return s.jsxs("div",{ref:Y,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Power Sensor (W)"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:Ke?Oe:Le?`${Le.friendly_name} (${Le.state} ${Le.unit_of_measurement})`:"",onChange:Ce=>{ge(Ce.target.value),Ke||G(!0)},onFocus:()=>{G(!0),ge("")},placeholder:"Search power sensors...",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&&!Ke&&s.jsx("button",{type:"button",onClick:()=>{Z(""),ge("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Ke&&s.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:[s.jsx("button",{type:"button",onClick:()=>{Z(""),G(!1),ge("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{Z(Ce.entity_id),G(!1),ge("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ce.entity_id===Q?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ce.entity_id," • ",Ce.state," ",Ce.unit_of_measurement]})]},Ce.entity_id)),Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const pe=bn.filter(Ce=>Ce.unit_of_measurement==="kWh"||Ce.unit_of_measurement==="Wh"||Ce.unit_of_measurement==="MWh"),Ie=ce?pe.filter(Ce=>Ce.entity_id.toLowerCase().includes(ce.toLowerCase())||Ce.friendly_name.toLowerCase().includes(ce.toLowerCase())):pe,Le=bn.find(Ce=>Ce.entity_id===ae);return s.jsxs("div",{ref:fe,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy Today (kWh)"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:te?ce:Le?`${Le.friendly_name} (${Le.state} ${Le.unit_of_measurement})`:"",onChange:Ce=>{q(Ce.target.value),te||I(!0)},onFocus:()=>{I(!0),q("")},placeholder:"Search energy sensors...",className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),ae&&!te&&s.jsx("button",{type:"button",onClick:()=>{B(""),q("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),te&&s.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:[s.jsx("button",{type:"button",onClick:()=>{B(""),I(!1),q("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{B(Ce.entity_id),I(!1),q("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ce.entity_id===ae?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ce.entity_id," • ",Ce.state," ",Ce.unit_of_measurement]})]},Ce.entity_id)),Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const pe=bn.filter(Ce=>Ce.unit_of_measurement==="kWh"||Ce.unit_of_measurement==="Wh"||Ce.unit_of_measurement==="MWh"),Ie=me?pe.filter(Ce=>Ce.entity_id.toLowerCase().includes(me.toLowerCase())||Ce.friendly_name.toLowerCase().includes(me.toLowerCase())):pe,Le=bn.find(Ce=>Ce.entity_id===X);return s.jsxs("div",{ref:ee,className:"relative",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Total Energy (kWh)"}),s.jsxs("div",{className:"relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),s.jsx("input",{type:"text",value:z?me:Le?`${Le.friendly_name} (${Le.state} ${Le.unit_of_measurement})`:"",onChange:Ce=>{Ee(Ce.target.value),z||O(!0)},onFocus:()=>{O(!0),Ee("")},placeholder:"Search energy sensors...",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"}),X&&!z&&s.jsx("button",{type:"button",onClick:()=>{ne(""),Ee("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Rt,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),z&&s.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:[s.jsx("button",{type:"button",onClick:()=>{ne(""),O(!1),Ee("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Ie.map(Ce=>s.jsxs("button",{type:"button",onClick:()=>{ne(Ce.entity_id),O(!1),Ee("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ce.entity_id===X?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ce.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ce.entity_id," • ",Ce.state," ",Ce.unit_of_measurement]})]},Ce.entity_id)),Ie.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})()]})]})]}),i==="mqtt"&&s.jsxs("div",{className:"space-y-3",children:[!Dn?.mqtt_broker&&s.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"," ",s.jsx("span",{className:"font-medium",children:"Settings → Network → MQTT Publishing"})," ","(you don't need to enable publishing, just fill in the broker details)."]}),Dn?.mqtt_broker&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[s.jsx("p",{className:"font-medium mb-1",children:"Monitor Only"}),s.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."})]}),s.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-white font-medium text-sm",children:"Power Monitoring"}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),s.jsx("input",{type:"text",value:y,onChange:pe=>v(pe.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"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),s.jsx("input",{type:"text",value:S,onChange:pe=>N(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),s.jsx("input",{type:"text",value:T,onChange:pe=>k(pe.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"})]})]}),s.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.',s.jsx("br",{}),"Use multiplier 0.001 for mW→W, 1000 for kW→W."]})]}),s.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[s.jsxs("p",{className:"text-white font-medium text-sm",children:["Energy Monitoring ",s.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),s.jsx("input",{type:"text",value:C,onChange:pe=>E(pe.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"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),s.jsx("input",{type:"text",value:D,onChange:pe=>A(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),s.jsx("input",{type:"text",value:R,onChange:pe=>U(pe.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"})]})]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",s.jsx("br",{}),"Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh."]})]}),s.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[s.jsxs("p",{className:"text-white font-medium text-sm",children:["State Monitoring ",s.jsx("span",{className:"text-bambu-gray font-normal",children:"(optional)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic"}),s.jsx("input",{type:"text",value:F,onChange:pe=>$(pe.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"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"JSON Path"}),s.jsx("input",{type:"text",value:j,onChange:pe=>H(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"ON Value"}),s.jsx("input",{type:"text",value:K,onChange:pe=>V(pe.target.value),placeholder:"ON, true, 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"})]})]}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:["JSON path extracts value from JSON payload. Leave empty for raw values.",s.jsx("br",{}),'ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).']})]})]})]}),i==="tasmota"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"IP Address *"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{type:"text",value:c,onChange:pe=>{u(pe.target.value),re(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"}),s.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>Ze.mutate(),disabled:!c.trim()||Ze.isPending,children:[Ze.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Sg,{className:"w-4 h-4"}),"Test"]})]})]}),i==="tasmota"&&we&&s.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${we.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:we.success?s.jsxs(s.Fragment,{children:[s.jsx(Ar,{className:"w-5 h-5"}),s.jsxs("div",{children:[s.jsx("p",{className:"font-medium",children:"Connected!"}),s.jsxs("p",{className:"text-sm opacity-80",children:[we.device_name&&`Device: ${we.device_name} - `,"State: ",we.state]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(sm,{className:"w-5 h-5"}),s.jsx("span",{children:"Connection failed"})]})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),s.jsx("input",{type:"text",value:o,onChange:pe=>l(pe.target.value),placeholder:"Living Room Plug",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),i==="tasmota"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username"}),s.jsx("input",{type:"text",value:d,onChange:pe=>f(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),s.jsx("input",{type:"password",value:p,onChange:pe=>m(pe.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"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:"Leave empty if your Tasmota device doesn't require authentication"})]}),i!=="mqtt"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Link to Printer"}),s.jsxs("select",{value:le??"",onChange:pe=>_e(pe.target.value?Number(pe.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:[s.jsx("option",{value:"",children:"No printer (manual control only)"}),ot?.map(pe=>s.jsx("option",{value:pe.id,children:pe.name},pe.id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Linking enables automatic on/off when prints start/complete"})]}),s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(wg,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"text-white font-medium",children:"Power Alerts"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:Ve,onChange:pe=>$e(pe.target.checked),className:"sr-only peer"}),s.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"})]})]}),Ve&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if above (W)"}),s.jsx("input",{type:"number",value:ye,onChange:pe=>je(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Alert if below (W)"}),s.jsx("input",{type:"number",value:Be,onChange:pe=>Se(pe.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"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Get notified when power consumption crosses these thresholds. Leave empty to disable that direction."})]})]}),i!=="mqtt"&&s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(er,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"text-white font-medium",children:"Daily Schedule"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:Xe,onChange:pe=>Me(pe.target.checked),className:"sr-only peer"}),s.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"})]})]}),Xe&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn On at"}),s.jsx("input",{type:"time",value:tt,onChange:pe=>ke(pe.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Turn Off at"}),s.jsx("input",{type:"time",value:We,onChange:pe=>ze(pe.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"})]})]}),s.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."})]})]}),s.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mN,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white font-medium",children:"Show in Switchbar"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Quick access from sidebar"})]})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:W,onChange:pe=>De(pe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Te,{type:"submit",disabled:he,className:"flex-1",children:[he?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(hs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function On({checked:t,onChange:e,disabled:n}){const r=i=>{i.preventDefault(),i.stopPropagation(),n||e(!t)};return s.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:s.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 aKe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function sKe({provider:t,onEdit:e}){const n=an(),[r,i]=_.useState(!1),[a,o]=_.useState(!1),[l,c]=_.useState(null),{data:u}=at({queryKey:["printers"],queryFn:ue.getPrinters}),d=u?.find(b=>b.id===t.printer_id),f=mt({mutationFn:b=>ue.updateNotificationProvider(t.id,b),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),p=mt({mutationFn:()=>ue.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),m=mt({mutationFn:()=>ue.testNotificationProvider(t.id),onSuccess:b=>{c(b),n.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{c({success:!1,message:b.message})}}),x=b=>b||"";return s.jsxs(s.Fragment,{children:[s.jsx(_t,{className:"relative",children:s.jsxs(Mt,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:s.jsx(wg,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),s.jsxs("div",{children:[s.jsx("h3",{className:"font-medium text-white",children:t.name}),s.jsx("p",{className:"text-sm text-bambu-gray",children:aKe[t.provider_type]||t.provider_type})]})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&s.jsxs("span",{className:"text-xs text-status-ok hidden sm:inline",children:["Last: ",Bg(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(Ii(t.last_error_at)?.getTime()||0)>(Ii(t.last_success)?.getTime()||0))&&s.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),s.jsx(On,{checked:t.enabled,onChange:b=>f.mutate({enabled:b})})]})]}),d&&s.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Printer: "}),s.jsx("span",{className:"text-sm text-white",children:d.name})]}),!d&&!t.printer_id&&s.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:s.jsx("span",{className:"text-xs text-bambu-gray",children:"All printers"})}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&s.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&&s.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&&s.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:"Complete"}),t.on_print_failed&&s.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:"Failed"}),t.on_print_stopped&&s.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:"Stopped"}),t.on_print_progress&&s.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:"Progress"}),t.on_printer_offline&&s.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:"Offline"}),t.on_printer_error&&s.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:"Error"}),t.on_filament_low&&s.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&&s.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&&s.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&&s.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&&s.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&&s.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&&s.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[s.jsx(W1,{className:"w-3 h-3"}),"Quiet"]}),t.daily_digest_enabled&&s.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[s.jsx(si,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),s.jsx("div",{className:"mb-3",children:s.jsxs(Te,{size:"sm",variant:"secondary",disabled:m.isPending,onClick:()=>{c(null),m.mutate()},className:"w-full",children:[m.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(PR,{className:"w-4 h-4"}),"Send Test Notification"]})}),l&&s.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?s.jsx(Ar,{className:"w-4 h-4"}):s.jsx(Yi,{className:"w-4 h-4"}),s.jsx("span",{children:l.message})]}),s.jsxs("button",{onClick:()=>o(!a),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:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(bh,{className:"w-4 h-4"}),"Event Settings"]}),a?s.jsx(xh,{className:"w-4 h-4"}):s.jsx(ei,{className:"w-4 h-4"})]}),a&&s.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Enabled"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Send notifications from this provider"})]}),s.jsx(On,{checked:t.enabled,onChange:b=>f.mutate({enabled:b})})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Events"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Started"}),s.jsx(On,{checked:t.on_print_start,onChange:b=>f.mutate({on_print_start:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Plate Not Empty"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Objects detected before print"})]}),s.jsx(On,{checked:t.on_plate_not_empty??!0,onChange:b=>f.mutate({on_plate_not_empty:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),s.jsx(On,{checked:t.on_print_complete,onChange:b=>f.mutate({on_print_complete:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),s.jsx(On,{checked:t.on_print_failed,onChange:b=>f.mutate({on_print_failed:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),s.jsx(On,{checked:t.on_print_stopped,onChange:b=>f.mutate({on_print_stopped:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Progress Milestones"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify at 25%, 50%, 75%"})]}),s.jsx(On,{checked:t.on_print_progress,onChange:b=>f.mutate({on_print_progress:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Printer Status"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Printer Offline"}),s.jsx(On,{checked:t.on_printer_offline,onChange:b=>f.mutate({on_printer_offline:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),s.jsx(On,{checked:t.on_printer_error,onChange:b=>f.mutate({on_printer_error:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),s.jsx(On,{checked:t.on_filament_low,onChange:b=>f.mutate({on_filament_low:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Maintenance Due"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Notify when maintenance is needed"})]}),s.jsx(On,{checked:t.on_maintenance_due??!1,onChange:b=>f.mutate({on_maintenance_due:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS Alarms"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS Humidity High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS humidity exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_humidity_high??!1,onChange:b=>f.mutate({on_ams_humidity_high:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS Temperature High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Regular AMS temperature exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_temperature_high??!1,onChange:b=>f.mutate({on_ams_temperature_high:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"AMS-HT Alarms"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS-HT Humidity High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT humidity exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>f.mutate({on_ams_ht_humidity_high:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"AMS-HT Temperature High"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"AMS-HT temperature exceeds threshold"})]}),s.jsx(On,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>f.mutate({on_ams_ht_temperature_high:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:"Print Queue"}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Added"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job added to queue"})]}),s.jsx(On,{checked:t.on_queue_job_added??!1,onChange:b=>f.mutate({on_queue_job_added:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Assigned"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Model-based job assigned to printer"})]}),s.jsx(On,{checked:t.on_queue_job_assigned??!1,onChange:b=>f.mutate({on_queue_job_assigned:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Started"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Queue job started printing"})]}),s.jsx(On,{checked:t.on_queue_job_started??!1,onChange:b=>f.mutate({on_queue_job_started:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Waiting"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job waiting for filament"})]}),s.jsx(On,{checked:t.on_queue_job_waiting??!0,onChange:b=>f.mutate({on_queue_job_waiting:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Skipped"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job skipped (previous failed)"})]}),s.jsx(On,{checked:t.on_queue_job_skipped??!0,onChange:b=>f.mutate({on_queue_job_skipped:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Job Failed"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Job failed to start"})]}),s.jsx(On,{checked:t.on_queue_job_failed??!0,onChange:b=>f.mutate({on_queue_job_failed:b})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Queue Complete"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"All queue jobs finished"})]}),s.jsx(On,{checked:t.on_queue_completed??!1,onChange:b=>f.mutate({on_queue_completed:b})})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W1,{className:"w-4 h-4 text-purple-400"}),s.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),s.jsx(On,{checked:t.quiet_hours_enabled,onChange:b=>f.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&s.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"No notifications during these hours"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(er,{className:"w-4 h-4 text-bambu-gray"}),s.jsxs("span",{className:"text-sm text-white",children:[x(t.quiet_hours_start)||"22:00"," - ",x(t.quiet_hours_end)||"07:00"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change quiet hours"})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(si,{className:"w-4 h-4 text-emerald-400"}),s.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),s.jsx(On,{checked:t.daily_digest_enabled,onChange:b=>f.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&s.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(er,{className:"w-4 h-4 text-bambu-gray"}),s.jsxs("span",{className:"text-sm text-white",children:["Send at ",x(t.daily_digest_time)||"08:00"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Edit provider to change digest time"})]})]}),s.jsxs("div",{className:"flex gap-2 pt-2",children:[s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx(fg,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(rn,{className:"w-4 h-4"})})]})]})]})}),r&&s.jsx(Zn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{p.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const hq=[{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 oKe({provider:t,onClose:e}){const n=an(),r=!!t,[i,a]=_.useState(t?.name||""),[o,l]=_.useState(t?.provider_type||"email"),[c,u]=_.useState(t?.printer_id||null),[d,f]=_.useState(t?.quiet_hours_enabled||!1),[p,m]=_.useState(t?.quiet_hours_start||"22:00"),[x,b]=_.useState(t?.quiet_hours_end||"07:00"),[y,v]=_.useState(t?.daily_digest_enabled||!1),[S,N]=_.useState(t?.daily_digest_time||"08:00"),[T,k]=_.useState(t?.on_print_start??!1),[C,E]=_.useState(t?.on_print_complete??!0),[D,A]=_.useState(t?.on_print_failed??!0),[R,U]=_.useState(t?.on_print_stopped??!0),[F,$]=_.useState(t?.on_print_progress??!1),[j,H]=_.useState(t?.on_printer_offline??!1),[K,V]=_.useState(t?.on_printer_error??!1),[Q,Z]=_.useState(t?.on_filament_low??!1),[ae,B]=_.useState(t?.on_maintenance_due??!1),[X,ne]=_.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([q,te])=>[q,String(te)])):{}),[se,be]=_.useState(null),[xe,de]=_.useState(null),{data:Pe}=at({queryKey:["printers"],queryFn:ue.getPrinters});_.useEffect(()=>{const q=te=>{te.key==="Escape"&&e()};return window.addEventListener("keydown",q),()=>window.removeEventListener("keydown",q)},[e]);const ie=mt({mutationFn:()=>ue.testNotificationConfig({provider_type:o,config:X}),onSuccess:q=>{be(q),de(null)},onError:q=>{be({success:!1,message:q.message})}}),Ne=mt({mutationFn:q=>ue.createNotificationProvider(q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),Oe=mt({mutationFn:q=>ue.updateNotificationProvider(t.id,q),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:q=>{de(q.message)}}),ge=q=>{if(q.preventDefault(),de(null),!i.trim()){de("Name is required");return}const te=Y(o);for(const fe of te)if(!X[fe.key]?.trim()){de(`${fe.label} is required`);return}const I={name:i.trim(),provider_type:o,config:X,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?p:null,quiet_hours_end:d?x:null,daily_digest_enabled:y,daily_digest_time:y?S:null,on_print_start:T,on_print_complete:C,on_print_failed:D,on_print_stopped:R,on_print_progress:F,on_printer_offline:j,on_printer_error:K,on_filament_low:Q,on_maintenance_due:ae};r?Oe.mutate(I):Ne.mutate(I)},Ke=Ne.isPending||Oe.isPending,G=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:te=>te.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:te=>te.payload_format!=="slack"}];default:return[]}},Y=q=>G(q).filter(te=>te.required),ce=G(o);return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:s.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:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-lg font-semibold text-white",children:r?"Edit Notification Provider":"Add Notification Provider"}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:ge,className:"p-6 space-y-4",children:[xe&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:xe}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),s.jsx("input",{type:"text",value:i,onChange:q=>a(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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Provider Type *"}),s.jsx("select",{value:o,onChange:q=>{l(q.target.value),ne({}),be(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:hq.map(q=>s.jsx("option",{value:q.value,children:q.label},q.value))}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:hq.find(q=>q.value===o)?.description})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),ce.filter(q=>!("showIf"in q)||q.showIf?.(X)!==!1).map(q=>s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[q.label," ",q.required&&"*"]}),q.type==="select"&&"options"in q&&q.options?s.jsx("select",{value:X[q.key]||q.options[0]?.value||"",onChange:te=>{ne({...X,[q.key]:te.target.value}),be(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(te=>s.jsx("option",{value:te.value,children:te.label},te.value))}):s.jsx("input",{type:q.type,value:X[q.key]||"",onChange:te=>{ne({...X,[q.key]:te.target.value}),be(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))]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Te,{type:"button",variant:"secondary",onClick:()=>{be(null),ie.mutate()},disabled:ie.isPending||!X[Y(o)[0]?.key],className:"flex-1",children:[ie.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(PR,{className:"w-4 h-4"}),"Test Configuration"]})}),se&&s.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${se.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:se.success?s.jsxs(s.Fragment,{children:[s.jsx(Ar,{className:"w-5 h-5"}),s.jsx("span",{children:se.message})]}):s.jsxs(s.Fragment,{children:[s.jsx(Yi,{className:"w-5 h-5"}),s.jsx("span",{children:se.message})]})}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Printer Filter"}),s.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:[s.jsx("option",{value:"",children:"All printers"}),Pe?.map(q=>s.jsx("option",{value:q.id,children:q.name},q.id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Only send notifications for events from this printer"})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("label",{className:"text-sm text-white",children:"Quiet Hours (Do Not Disturb)"}),s.jsx(On,{checked:d,onChange:f})]}),d&&s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Start"}),s.jsx("input",{type:"time",value:p,onChange:q=>m(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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"End"}),s.jsx("input",{type:"time",value:x,onChange:q=>b(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"})]})]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-sm text-white",children:"Daily Digest"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Batch notifications into a single daily summary"})]}),s.jsx(On,{checked:y,onChange:v})]}),y&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Send digest at"}),s.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Events will be collected and sent as a single summary at this time"})]})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Notification Events"}),s.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Print Events"}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Start"}),s.jsx(On,{checked:T,onChange:k})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Complete"}),s.jsx(On,{checked:C,onChange:E})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Failed"}),s.jsx(On,{checked:D,onChange:A})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Stopped"}),s.jsx(On,{checked:R,onChange:U})]}),s.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-white",children:"Progress"}),s.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:"(25%, 50%, 75%)"})]}),s.jsx(On,{checked:F,onChange:$})]})]})]}),s.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[s.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:"Printer Status"}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Offline"}),s.jsx(On,{checked:j,onChange:H})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Error"}),s.jsx(On,{checked:K,onChange:V})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),s.jsx(On,{checked:Q,onChange:Z})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),s.jsx(On,{checked:ae,onChange:B})]})]})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Te,{type:"submit",disabled:Ke,className:"flex-1",children:[Ke?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(hs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function lKe({template:t,onClose:e}){const n=an(),r=_.useRef(null),[i,a]=_.useState(t.title_template),[o,l]=_.useState(t.body_template),[c,u]=_.useState(null),[d,f]=_.useState(!0),{data:p}=at({queryKey:["template-variables"],queryFn:ue.getTemplateVariables}),m=p?.find(k=>k.event_type===t.event_type),{data:x,isLoading:b}=at({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>ue.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});_.useEffect(()=>{const k=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[e]);const y=mt({mutationFn:k=>ue.updateNotificationTemplate(t.id,k),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:k=>{u(k.message)}}),v=mt({mutationFn:()=>ue.resetNotificationTemplate(t.id),onSuccess:k=>{a(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}y.mutate({title_template:i,body_template:o})},N=k=>{const C=r.current;if(!C)return;const E=C.selectionStart,D=C.selectionEnd,A=o,R=A.substring(0,E),U=A.substring(D),F=R+`{${k}}`+U;l(F),setTimeout(()=>{C.focus();const $=E+k.length+2;C.setSelectionRange($,$)},0)},T=i!==t.title_template||o!==t.body_template;return s.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Edit Template: ",t.name]}),s.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:s.jsx(Rt,{className:"w-5 h-5 text-bambu-gray"})})]}),s.jsxs("form",{onSubmit:S,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[c&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:c}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Title"}),s.jsx("input",{type:"text",value:i,onChange:k=>a(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..."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:"Body"}),s.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..."})]}),m&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:"Available Variables"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:m.variables.map(k=>s.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:[s.jsx(dr,{className:"w-3 h-3"}),k]},k))}),s.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:"Click to insert at cursor position in body"})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(Ru,{className:"w-4 h-4"}),"Live Preview"]}),s.jsx("button",{type:"button",onClick:()=>f(!d),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:d?"Hide":"Show"})]}),d&&s.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Loading preview..."]}):x?s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Title:"}),s.jsx("div",{className:"text-white font-medium",children:x.title})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-xs text-bambu-gray",children:"Body:"}),s.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:x.body})]})]}):s.jsx("div",{className:"text-bambu-gray text-sm",children:"Enter template content to see preview"})})]})]}),s.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[s.jsxs(Te,{type:"button",variant:"ghost",onClick:()=>v.mutate(),disabled:v.isPending,className:"text-orange-400 hover:text-orange-300",children:[v.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(Rh,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),s.jsxs(Te,{onClick:S,disabled:y.isPending||!T,children:[y.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(hs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const cKe={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"},uKe={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 dKe({onClose:t}){const e=an(),{showToast:n}=$n(),[r,i]=_.useState(7),[a,o]=_.useState(null),[l,c]=_.useState(!1),{data:u}=at({queryKey:["settings"],queryFn:ue.getSettings}),d=u?.time_format||"system",{data:f,isLoading:p,refetch:m,isRefetching:x}=at({queryKey:["notification-logs",r,l],queryFn:()=>ue.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:b}=at({queryKey:["notification-log-stats",r],queryFn:()=>ue.getNotificationLogStats(r)}),y=mt({mutationFn:()=>ue.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")}}),v=S=>{const N=Ii(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()+" "+Dfe(N,d)};return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.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:[s.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(q0,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Notification Log"})]}),s.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&s.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:s.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[s.jsxs("span",{className:"text-bambu-gray",children:["Last ",r," days: ",s.jsx("span",{className:"text-white font-medium",children:b.total})," notifications"]}),s.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[s.jsx(Ar,{className:"w-4 h-4"}),b.success_count," sent"]}),b.failure_count>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(Yi,{className:"w-4 h-4"}),b.failure_count," failed"]})]})}),s.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[s.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:[s.jsx("option",{value:1,children:"Last 24 hours"}),s.jsx("option",{value:7,children:"Last 7 days"}),s.jsx("option",{value:30,children:"Last 30 days"}),s.jsx("option",{value:90,children:"Last 90 days"})]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[s.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"]}),s.jsx("div",{className:"flex-1"}),s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>m(),disabled:x,children:[x?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Refresh"]}),s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>y.mutate(),disabled:y.isPending,className:"text-red-400 hover:text-red-300",children:[y.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"}),"Clear Old"]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:p?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):f&&f.length>0?s.jsx("div",{className:"space-y-2",children:f.map(S=>s.jsx(hKe,{log:S,isExpanded:a===S.id,onToggle:()=>o(a===S.id?null:S.id),formatDate:v,formatFullDate:N=>Hg(N,d)},S.id))}):s.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[s.jsx(q0,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm",children:l?"No failed notifications":"No notifications logged"})]})})]})})}function hKe({log:t,isExpanded:e,onToggle:n,formatDate:r,formatFullDate:i}){return s.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:[s.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?s.jsx(Ar,{className:"w-4 h-4 text-bambu-green shrink-0"}):s.jsx(Yi,{className:"w-4 h-4 text-red-400 shrink-0"}),s.jsx("span",{className:`text-xs font-medium ${uKe[t.event_type]||"text-bambu-gray"}`,children:cKe[t.event_type]||t.event_type}),s.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||"Unknown Provider"}),t.printer_name&&s.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),s.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?s.jsx(xh,{className:"w-4 h-4 text-bambu-gray shrink-0"}):s.jsx(ei,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&s.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Title"}),s.jsx("p",{className:"text-sm text-white",children:t.title})]}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:"Message"}),s.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-red-400 mb-1",children:"Error"}),s.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),s.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[s.jsxs("span",{children:["Provider: ",t.provider_type]}),s.jsxs("span",{children:["Time: ",i(t.created_at)]})]})]})]})}async function fKe(){const t=await fetch("/api/v1/settings/spoolman");if(!t.ok)throw new Error("Failed to load Spoolman settings");return t.json()}async function mKe(t){const e=await fetch("/api/v1/settings/spoolman",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!e.ok)throw new Error("Failed to save Spoolman settings");return e.json()}function pKe(){const t=an(),[e,n]=_.useState(!1),[r,i]=_.useState(""),[a,o]=_.useState("auto"),[l,c]=_.useState(!1),[u,d]=_.useState("all"),[f,p]=_.useState(!1),[m,x]=_.useState(!1),{data:b,isLoading:y}=at({queryKey:["spoolman-settings"],queryFn:fKe}),{data:v,isLoading:S,refetch:N}=at({queryKey:["spoolman-status"],queryFn:ue.getSpoolmanStatus,refetchInterval:3e4}),{data:T}=at({queryKey:["printers"],queryFn:ue.getPrinters});_.useEffect(()=>{b&&(n(b.spoolman_enabled==="true"),i(b.spoolman_url||""),o(b.spoolman_sync_mode||"auto"),p(!0))},[b]),_.useEffect(()=>{if(!f||!b)return;if(b.spoolman_enabled==="true"!==e||(b.spoolman_url||"")!==r||(b.spoolman_sync_mode||"auto")!==a){const H=setTimeout(()=>{k.mutate()},500);return()=>clearTimeout(H)}},[e,r,a,f]);const k=mt({mutationFn:()=>mKe({spoolman_enabled:e?"true":"false",spoolman_url:r,spoolman_sync_mode:a}),onSuccess:()=>{t.invalidateQueries({queryKey:["spoolman-settings"]}),t.invalidateQueries({queryKey:["spoolman-status"]}),c(!0),setTimeout(()=>c(!1),2e3)}}),C=mt({mutationFn:ue.connectSpoolman,onSuccess:()=>{N()}}),E=mt({mutationFn:ue.disconnectSpoolman,onSuccess:()=>{N()}}),D=mt({mutationFn:ue.syncAllPrintersAms,onSuccess:j=>{j.success}}),A=mt({mutationFn:j=>ue.syncPrinterAms(j),onSuccess:j=>{j.success}}),R=()=>{u==="all"?D.mutate():A.mutate(u)},U=D.isPending||A.isPending,F=u==="all"?D.data:A.data,$=u==="all"?D.isSuccess:A.isSuccess;return y?s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Nu,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]})}),s.jsx(Mt,{children:s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Nu,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]}),k.isPending&&s.jsx(ht,{className:"w-4 h-4 text-bambu-green animate-spin"}),l&&s.jsx(Ia,{className:"w-4 h-4 text-bambu-green"})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Connect to Spoolman for filament inventory tracking. AMS data will sync automatically."}),s.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Zo,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-xs text-blue-300",children:[s.jsx("p",{className:"font-medium mb-1",children:"How Sync Works"}),s.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[s.jsx("li",{children:"Only official Bambu Lab spools with RFID are synced"}),s.jsx("li",{children:"New spools are auto-created in Spoolman on first sync"}),s.jsx("li",{children:"Non-Bambu Lab spools (third-party, refilled) are skipped"})]}),s.jsx("p",{className:"font-medium mt-2 mb-1",children:"Linking Existing Spools"}),s.jsx("p",{className:"text-blue-300/80",children:'To link existing Spoolman spools to your AMS, hover over an AMS slot and click "Link to Spoolman".'})]})]})}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Enable Spoolman"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Sync filament data with Spoolman server"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:e,onChange:j=>n(j.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Spoolman URL"}),s.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:r,onChange:j=>i(j.target.value),disabled:!e,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 disabled:opacity-50"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"URL of your Spoolman server (e.g., http://localhost:7912)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Sync Mode"}),s.jsxs("select",{value:a,onChange:j=>o(j.target.value),disabled:!e,className:"w-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:[s.jsx("option",{value:"auto",children:"Automatic"}),s.jsx("option",{value:"manual",children:"Manual Only"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a==="auto"?"AMS data syncs automatically when changes are detected":"Only sync when manually triggered"})]}),e&&s.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:"Status:"}),S?s.jsx(ht,{className:"w-4 h-4 text-bambu-gray animate-spin"}):v?.connected?s.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[s.jsx(Ia,{className:"w-4 h-4"}),"Connected"]}):s.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[s.jsx(Rt,{className:"w-4 h-4"}),"Disconnected"]})]}),s.jsx("div",{className:"flex gap-2",children:v?.connected?s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(gde,{className:"w-4 h-4"}),"Disconnect"]}):s.jsxs(Te,{size:"sm",onClick:()=>C.mutate(),disabled:C.isPending||!r,children:[C.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(uc,{className:"w-4 h-4"}),"Connect"]})})]}),C.isError&&s.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:C.error.message}),v?.connected&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:"Sync AMS Data"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Manually sync printer AMS data to Spoolman"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsxs("select",{value:u,onChange:j=>d(j.target.value==="all"?"all":Number(j.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:[s.jsx("option",{value:"all",children:"All Printers"}),T?.map(j=>s.jsx("option",{value:j.id,children:j.name},j.id))]}),s.jsx(ei,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:R,disabled:U,children:[U?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Sync"]})]})]}),$&&F&&s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx("div",{className:`p-2 rounded text-sm ${F.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:F.success?`Synced ${F.synced_count} spool${F.synced_count!==1?"s":""} successfully`:`Synced ${F.synced_count} spool${F.synced_count!==1?"s":""} with ${F.errors.length} error${F.errors.length!==1?"s":""}`}),F.skipped_count>0&&s.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[s.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Cn,{className:"w-3.5 h-3.5"}),s.jsxs("span",{className:"font-medium",children:[F.skipped_count," spool",F.skipped_count!==1?"s":""," skipped"]})]}),F.skipped_count>5&&s.jsx("button",{onClick:()=>x(!m),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:m?"Show less":"Show all"})]}),s.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(m?F.skipped:F.skipped.slice(0,5)).map((j,H)=>s.jsxs("li",{className:"flex items-center gap-2",children:[j.color&&s.jsx("span",{className:"w-3 h-3 rounded-full border border-white/20",style:{backgroundColor:`#${j.color}`}}),s.jsx("span",{children:j.location}),s.jsxs("span",{className:"text-amber-300/60",children:["- ",j.reason]})]},H)),!m&&F.skipped_count>5&&s.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",F.skipped_count-5," more"]})]})]}),F.errors.length>0&&s.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[s.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),s.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:F.errors.map((j,H)=>s.jsx("li",{children:j},H))})]})]})]})]})]})}function gKe({link:t,onClose:e}){const n=an(),{mode:r}=Oh(),i=!!t,a=_.useRef(null),[o,l]=_.useState(t?.name||""),[c,u]=_.useState(t?.url||""),[d,f]=_.useState(t?.icon||"link"),[p,m]=_.useState(!!t?.custom_icon),[x,b]=_.useState(t?.custom_icon?ue.getExternalLinkIconUrl(t.id):null),[y,v]=_.useState(null),[S,N]=_.useState(null);_.useEffect(()=>{const U=F=>{F.key==="Escape"&&e()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[e]);const T=mt({mutationFn:async U=>{const F=await ue.createExternalLink(U);return y?await ue.uploadExternalLinkIcon(F.id,y):F},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{N(U.message)}}),k=mt({mutationFn:async U=>{let F=await ue.updateExternalLink(t.id,U);return y?F=await ue.uploadExternalLinkIcon(t.id,y):!p&&t?.custom_icon&&(F=await ue.deleteExternalLinkIcon(t.id)),F},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:U=>{N(U.message)}}),C=U=>{const F=U.target.files?.[0];if(F){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(F.type)){N("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(F.size>1024*1024){N("Image file must be less than 1MB");return}v(F),m(!0);const j=new FileReader;j.onload=H=>{b(H.target?.result)},j.readAsDataURL(F)}},E=()=>{v(null),b(null),m(!1),a.current&&(a.current.value="")},D=U=>{if(U.preventDefault(),N(null),!o.trim()){N("Name is required");return}if(!c.trim()){N("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){N("URL must start with http:// or https://");return}const F={name:o.trim(),url:c.trim(),icon:d};i?k.mutate(F):T.mutate(F)},A=T.isPending||k.isPending,R=yN(d);return s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:U=>U.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:p&&x?s.jsx("img",{src:x,alt:"",className:`w-5 h-5 rounded ${r==="dark"?"invert opacity-[0.65]":"opacity-60"}`}):s.jsx(R,{className:"w-5 h-5"})}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),s.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:D,className:"p-6 space-y-4",children:[S&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:S}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),s.jsx("input",{type:"text",value:o,onChange:U=>l(U.target.value),placeholder:"My Link",maxLength:50,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),s.jsx("input",{type:"text",value:c,onChange:U=>u(U.target.value),placeholder:"https://example.com",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),s.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),s.jsx("input",{ref:a,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:C}),p&&x?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("img",{src:x,alt:"Custom icon",className:`w-8 h-8 rounded border border-bambu-dark-tertiary ${r==="dark"?"invert opacity-[0.65]":"opacity-60"}`}),s.jsx("button",{type:"button",onClick:E,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:s.jsx(rn,{className:"w-4 h-4"})})]}):s.jsxs(Te,{type:"button",variant:"secondary",size:"sm",onClick:()=>a.current?.click(),children:[s.jsx(Ua,{className:"w-4 h-4"}),"Upload"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!p&&s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),s.jsx(Mfe,{value:d,onChange:f})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Te,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Te,{type:"submit",disabled:A,className:"flex-1",children:[A?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(hs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function xKe(){const t=an(),[e,n]=_.useState(!1),[r,i]=_.useState(null),[a,o]=_.useState(null),[l,c]=_.useState(null),{data:u,isLoading:d}=at({queryKey:["external-links"],queryFn:ue.getExternalLinks}),f=mt({mutationFn:S=>ue.deleteExternalLink(S),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),p=mt({mutationFn:S=>ue.reorderExternalLinks(S),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),m=(S,N)=>{c(N),S.dataTransfer.effectAllowed="move"},x=S=>{S.preventDefault(),S.dataTransfer.dropEffect="move"},b=(S,N)=>{if(S.preventDefault(),l===null||l===N||!u)return;const T=u.map(D=>D.id),k=T.indexOf(l),C=T.indexOf(N);if(k===-1||C===-1)return;const E=[...T];E.splice(k,1),E.splice(C,0,l),p.mutate(E),c(null)},y=S=>{o(S)},v=()=>{a&&(f.mutate(a.id),o(null))};return s.jsxs(s.Fragment,{children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(uc,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),s.jsxs(Te,{size:"sm",onClick:()=>n(!0),children:[s.jsx(dr,{className:"w-4 h-4"}),"Add Link"]})]})}),s.jsxs(Mt,{children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),d?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?s.jsx("div",{className:"space-y-2",children:u.map(S=>{const N=yN(S.icon);return s.jsxs("div",{draggable:!0,onDragStart:T=>m(T,S.id),onDragOver:x,onDrop:T=>b(T,S.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${l===S.id?"opacity-50":""}`,children:[s.jsx(zg,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),s.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:s.jsx(N,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-white font-medium truncate",children:S.name}),s.jsx(Kr,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),s.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:S.url})]}),s.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s.jsx("button",{onClick:()=>i(S),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:"Edit",children:s.jsx(Qi,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>y(S),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:"Delete",children:s.jsx(rn,{className:"w-4 h-4"})})]})]},S.id)})}):s.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[s.jsx(uc,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),s.jsx("p",{children:"No external links configured"}),s.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(e||r)&&s.jsx(gKe,{link:r,onClose:()=>{n(!1),i(null)}}),a&&s.jsx(Zn,{title:"Delete Link",message:`Are you sure you want to delete "${a.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:v,onCancel:()=>o(null)})]})}function bKe(){const t=an(),{showToast:e}=$n(),[n,r]=_.useState(!1),[i,a]=_.useState(""),[o,l]=_.useState("immediate"),[c,u]=_.useState("3DPrinter-X1-Carbon"),[d,f]=_.useState(!1),[p,m]=_.useState(null),{data:x,isLoading:b}=at({queryKey:["virtual-printer-settings"],queryFn:p1.getSettings,refetchInterval:1e4}),{data:y}=at({queryKey:["virtual-printer-models"],queryFn:p1.getModels});_.useEffect(()=>{if(x){r(x.enabled);let D=x.mode==="queue"?"review":x.mode;D!=="immediate"&&D!=="review"&&D!=="print_queue"&&(D="immediate"),l(D),u(x.model)}},[x]);const v=mt({mutationFn:D=>p1.updateSettings(D),onSuccess:()=>{t.invalidateQueries({queryKey:["virtual-printer-settings"]}),e("Virtual printer settings updated"),m(null)},onError:D=>{if(e(D.message||"Failed to update settings","error"),x){r(x.enabled);const A=x.mode==="queue"?"review":x.mode;l(A==="print_queue"||A==="review"?A:"immediate"),u(x.model)}m(null)}}),S=()=>{const D=!n;if(D&&!i&&!x?.access_code_set){e("Please set an access code first","error");return}r(D),m("toggle"),v.mutate({enabled:D,access_code:i||void 0,mode:o})},N=()=>{if(!i){e("Access code cannot be empty","error");return}if(i.length!==8){e("Access code must be exactly 8 characters","error");return}m("accessCode"),v.mutate({access_code:i}),a("")},T=D=>{l(D),m("mode"),v.mutate({mode:D})},k=D=>{u(D),m("model"),v.mutate({model:D})};if(b)return s.jsx(_t,{children:s.jsx(Mt,{className:"py-8 flex justify-center",children:s.jsx(ht,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const C=x?.status,E=C?.running||!1;return s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[s.jsx("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ur,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Virtual Printer"})]}),C&&s.jsxs("div",{className:`flex items-center gap-2 text-sm ${E?"text-green-400":"text-bambu-gray"}`,children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${E?"bg-green-400 animate-pulse":"bg-gray-500"}`}),E?"Running":"Stopped"]})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable a virtual printer that appears in Bambu Studio and OrcaSlicer. Files sent to this printer will be archived directly without printing."}),s.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-white font-medium",children:"Enable Virtual Printer"}),s.jsx("div",{className:"text-sm text-bambu-gray",children:E?'Visible as "Bambuddy" in slicer discovery':"Not visible to slicers"})]}),s.jsx("button",{onClick:S,disabled:p==="toggle",className:`relative w-12 h-6 rounded-full transition-colors ${n?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${p==="toggle"?"opacity-50":""}`,children:s.jsx("span",{className:`absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform ${n?"translate-x-6":""}`})})]}),s.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[s.jsx("div",{className:"text-white font-medium mb-2",children:"Printer Model"}),s.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:"Select which printer model to emulate."}),s.jsxs("div",{className:"relative",children:[s.jsx("select",{value:c,onChange:D=>k(D.target.value),disabled:p==="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:y?.models&&Object.entries(y.models).sort(([,D],[,A])=>D.localeCompare(A)).map(([D,A])=>s.jsx("option",{value:D,children:A},D))}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),n&&E&&s.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:[s.jsx(Zo,{className:"w-3 h-3 inline mr-1"}),"Changing the model will restart the virtual printer"]})]}),s.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[s.jsx("div",{className:"text-white font-medium mb-2",children:"Access Code"}),s.jsx("div",{className:"text-sm text-bambu-gray mb-3",children:x?.access_code_set?s.jsxs("span",{className:"flex items-center gap-1 text-green-400",children:[s.jsx(Ia,{className:"w-4 h-4"}),"Access code is set"]}):s.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[s.jsx(Cn,{className:"w-4 h-4"}),"No access code set - required to enable"]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("div",{className:"relative flex-1",children:[s.jsx("input",{type:d?"text":"password",value:i,onChange:D=>a(D.target.value),placeholder:x?.access_code_set?"Enter new code to change":"Enter 8-char code",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"}),s.jsx("button",{onClick:()=>f(!d),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:d?s.jsx(lN,{className:"w-4 h-4"}):s.jsx(Ru,{className:"w-4 h-4"})})]}),s.jsx(Te,{onClick:N,disabled:!i||p==="accessCode",variant:"primary",children:p==="accessCode"?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):"Save"})]}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:["Must be exactly 8 characters. Used by slicers to authenticate.",i&&s.jsxs("span",{className:i.length===8?"text-green-400":"text-yellow-400",children:[" ","(",i.length,"/8)"]})]})]}),s.jsxs("div",{className:"py-3 border-t border-bambu-dark-tertiary",children:[s.jsx("div",{className:"text-white font-medium mb-2",children:"Mode"}),s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsxs("button",{onClick:()=>T("immediate"),disabled:p==="mode",className:`p-3 rounded-lg border text-left transition-colors ${o==="immediate"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[s.jsx("div",{className:"text-white font-medium",children:"Archive"}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Archive files immediately"})]}),s.jsxs("button",{onClick:()=>T("review"),disabled:p==="mode",className:`p-3 rounded-lg border text-left transition-colors ${o==="review"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[s.jsx("div",{className:"text-white font-medium",children:"Review"}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Review and tag before archiving"})]}),s.jsxs("button",{onClick:()=>T("print_queue"),disabled:p==="mode",className:`p-3 rounded-lg border text-left transition-colors ${o==="print_queue"?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[s.jsx("div",{className:"text-white font-medium",children:"Queue"}),s.jsx("div",{className:"text-xs text-bambu-gray",children:"Archive and add to print queue"})]})]})]})]})]})}),s.jsxs("div",{className:"space-y-6 lg:w-[480px] lg:flex-shrink-0",children:[s.jsx(_t,{className:"border-l-4 border-l-yellow-500",children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Cn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm",children:[s.jsx("p",{className:"text-white font-medium mb-2",children:"Setup Required"}),s.jsx("p",{className:"text-bambu-gray mb-3",children:"The virtual printer feature requires additional system configuration before it will work. This includes port forwarding, firewall rules, and platform-specific settings."}),s.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:[s.jsx(Kr,{className:"w-4 h-4"}),"Read the setup guide before enabling"]})]})]})})}),s.jsx(_t,{children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Zo,{className:"w-5 h-5 text-blue-400 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-bambu-gray",children:[s.jsx("p",{className:"mb-2",children:s.jsx("strong",{className:"text-white",children:"How it works:"})}),s.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[s.jsx("li",{children:"Complete the setup guide for your platform"}),s.jsx("li",{children:"Enable the virtual printer and set an access code"}),s.jsx("li",{children:'In Bambu Studio or OrcaSlicer, go to "Add Printer"'}),s.jsx("li",{children:'The "Bambuddy" printer should appear in the discovery list'}),s.jsx("li",{children:"Connect using the access code you set"}),s.jsx("li",{children:'When you "print" to Bambuddy, the 3MF file is archived instead'})]})]})]})})}),C&&E&&s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h3",{className:"text-md font-semibold text-white",children:"Status Details"})}),s.jsx(Mt,{children:s.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Printer Name"}),s.jsx("div",{className:"text-white",children:C.name})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Model"}),s.jsx("div",{className:"text-white",children:C.model_name||C.model})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Serial Number"}),s.jsx("div",{className:"text-white font-mono",children:C.serial})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Mode"}),s.jsx("div",{className:"text-white capitalize",children:C.mode})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-bambu-gray",children:"Pending Files"}),s.jsx("div",{className:"text-white",children:C.pending_files})]})]})})]})]})]})}function fq({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:s.jsx(Ar,{className:"w-3 h-3"}),failed:s.jsx(Yi,{className:"w-3 h-3"}),skipped:s.jsx(DR,{className:"w-3 h-3"}),running:s.jsx(ht,{className:"w-3 h-3 animate-spin"})};return s.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 yKe(t){return t?new Date(t).toLocaleString():"-"}function mq(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 a=Math.abs(i);if(a<60)return`${a}m ago`;const o=Math.floor(a/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}else{if(i<60)return`in ${i}m`;const a=Math.floor(i/60);return a<24?`in ${a}h`:`in ${Math.floor(a/24)}d`}}function vKe(){const t=an(),{showToast:e}=$n(),[n,r]=_.useState(""),[i,a]=_.useState(""),[o,l]=_.useState("main"),[c,u]=_.useState(!1),[d,f]=_.useState("daily"),[p,m]=_.useState(!0),[x,b]=_.useState(!0),[y,v]=_.useState(!1),[S,N]=_.useState(!0),[T,k]=_.useState(!1),[C,E]=_.useState(!1),[D,A]=_.useState(""),[R,U]=_.useState(!1),[F,$]=_.useState(null),[j,H]=_.useState(null),K=_.useRef(null);_.useEffect(()=>{if(T||C){const Ee=z=>(z.preventDefault(),z.returnValue="A backup operation is in progress. Are you sure you want to leave?",z.returnValue);return window.addEventListener("beforeunload",Ee),()=>window.removeEventListener("beforeunload",Ee)}},[T,C]);const[V,Q]=_.useState(!1),[Z,ae]=_.useState(null),B=_.useRef(null),X=_.useRef(!1),{data:ne,isLoading:se}=at({queryKey:["github-backup-config"],queryFn:ue.getGitHubBackupConfig}),{data:be}=at({queryKey:["github-backup-status"],queryFn:ue.getGitHubBackupStatus,refetchInterval:me=>me.state.data?.is_running?500:1e4}),{data:xe}=at({queryKey:["github-backup-logs"],queryFn:()=>ue.getGitHubBackupLogs(20)}),{data:de}=at({queryKey:["cloud-status"],queryFn:ue.getCloudStatus}),{data:Pe}=at({queryKey:["printers"],queryFn:ue.getPrinters}),ie=dW({queries:(Pe??[]).map(me=>({queryKey:["printerStatus",me.id],queryFn:()=>ue.getPrinterStatus(me.id),staleTime:1e4,refetchInterval:3e4}))}),Ne=(Pe??[]).map((me,Ee)=>({printer:me,connected:ie[Ee]?.data?.connected??!1})),Oe=Ne.length,ge=Ne.filter(me=>me.connected).length,Ke=Oe>0&&ge===0,G=ge>0&&ge{ne&&(r(ne.repository_url),l(ne.branch),u(ne.schedule_enabled),f(ne.schedule_type),m(ne.backup_kprofiles),b(ne.backup_cloud_profiles),v(ne.backup_settings),N(ne.enabled),a(""),setTimeout(()=>{X.current=!0},100))},[ne]);const Y=_.useCallback(async(me=!1)=>{if(ne?.has_token)try{me&&i?(await ue.saveGitHubBackupConfig({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:p,backup_cloud_profiles:x,backup_settings:y,enabled:S}),a(""),e("Token updated")):(await ue.updateGitHubBackupConfig({repository_url:n,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:p,backup_cloud_profiles:x,backup_settings:y,enabled:S}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(Ee){e(`Failed to save: ${Ee.message}`,"error")}},[ne?.has_token,n,i,o,c,d,p,x,y,S,t,e]);_.useEffect(()=>{if(!(!X.current||!ne?.has_token))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{Y(!1)},500),()=>{B.current&&clearTimeout(B.current)}},[n,o,c,d,p,x,y,S,Y,ne?.has_token]),_.useEffect(()=>{if(!(!X.current||!ne?.has_token||!i))return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{Y(!0)},1e3),()=>{B.current&&clearTimeout(B.current)}},[i,Y,ne?.has_token]);const ce=mt({mutationFn:me=>ue.saveGitHubBackupConfig(me),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),a(""),X.current=!0},onError:me=>{e(`Failed to save: ${me.message}`,"error")}}),q=mt({mutationFn:ue.triggerGitHubBackup,onSuccess:me=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),me.success?me.files_changed>0?e(`Backup complete - ${me.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${me.message}`,"error")},onError:me=>{e(`Backup failed: ${me.message}`,"error")}}),te=mt({mutationFn:()=>ue.clearGitHubBackupLogs(0),onSuccess:me=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${me.deleted} logs`)},onError:me=>{e(`Failed to clear logs: ${me.message}`,"error")}}),I=async()=>{Q(!0),ae(null);try{let me;if(i){if(!n){e("Enter repository URL","error"),Q(!1);return}me=await ue.testGitHubConnection(n,i)}else if(ne?.has_token)me=await ue.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),Q(!1);return}ae({success:me.success,message:me.message})}catch(me){ae({success:!1,message:me.message})}finally{Q(!1)}},fe=()=>{if(!n){e("Repository URL is required","error");return}if(!i){e("Access token is required","error");return}ce.mutate({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:p,backup_cloud_profiles:x,backup_settings:y,enabled:S})};return se?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 animate-spin text-bambu-green"})}):s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[s.jsxs("div",{className:"space-y-6",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fP,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),ne&&de?.is_authenticated&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:"Enabled"}),s.jsx(On,{checked:S,onChange:N})]})]})}),s.jsx(Mt,{className:"space-y-4",children:de?.is_authenticated?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically sync your profiles to a private GitHub repository for backup and version history."}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Repository URL"}),s.jsx("input",{type:"text",value:n,onChange:me=>{r(me.target.value),ae(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"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:["Personal Access Token ",ne?.has_token&&s.jsx("span",{className:"text-green-400",children:"(saved)"})]}),s.jsx("input",{type:"password",value:i,onChange:me=>{a(me.target.value),ae(null)},placeholder:ne?.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Fine-grained token with Contents read/write permission"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Branch"}),s.jsx("input",{type:"text",value:o,onChange:me=>l(me.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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Auto-backup"}),s.jsxs("select",{value:c?d:"disabled",onChange:me=>{me.target.value==="disabled"?u(!1):(u(!0),f(me.target.value))},className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[s.jsx("option",{value:"disabled",children:"Manual only"}),s.jsx("option",{value:"hourly",children:"Hourly"}),s.jsx("option",{value:"daily",children:"Daily"}),s.jsx("option",{value:"weekly",children:"Weekly"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"Include in backup"}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:`flex items-start gap-2 ${Ke?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[s.jsx("input",{type:"checkbox",checked:p,onChange:me=>m(me.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:Ke}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm ${Ke?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),Ke&&s.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:[s.jsx(Cn,{className:"w-3 h-3"}),"No printers connected"]}),G&&s.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:[s.jsx(Cn,{className:"w-3 h-3"}),ge,"/",Oe," connected"]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Pressure advance calibration from connected printers"})]})]}),s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:x,onChange:me=>b(me.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:!de?.is_authenticated}),s.jsxs("div",{children:[s.jsx("span",{className:`text-sm ${de?.is_authenticated?"text-white":"text-bambu-gray"}`,children:"Cloud Profiles"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament, printer, and process presets from Bambu Cloud"})]})]}),s.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:y,onChange:me=>v(me.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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white text-sm",children:"App Settings"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Bambuddy configuration (excludes sensitive data)"})]})]})]})]}),s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[be?.configured&&s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:be.last_backup_at?s.jsxs(s.Fragment,{children:[s.jsxs("span",{children:["Last backup: ",mq(be.last_backup_at)]}),s.jsx(fq,{status:be.last_backup_status})]}):s.jsx("span",{children:"No backups yet"})}),be.next_scheduled_run&&s.jsxs("span",{className:"text-bambu-gray",children:[s.jsx(er,{className:"w-3 h-3 inline mr-1"}),"Next: ",mq(be.next_scheduled_run)]})]}),Z&&s.jsxs("div",{className:`text-sm flex items-center gap-1 ${Z.success?"text-green-400":"text-red-400"}`,children:[Z.success?s.jsx(Ar,{className:"w-4 h-4"}):s.jsx(Yi,{className:"w-4 h-4"}),Z.message]}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:be?.configured?s.jsx(s.Fragment,{children:q.isPending||be.is_running?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{className:"text-sm",children:be.progress||"Starting backup..."})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"primary",size:"sm",onClick:()=>q.mutate(),disabled:!ne?.enabled,children:[s.jsx(Is,{className:"w-4 h-4"}),"Backup Now"]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:I,disabled:V,children:[V?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Test"]})]})}):s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"primary",size:"sm",onClick:fe,disabled:ce.isPending||!n||!i,children:[ce.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Ar,{className:"w-4 h-4"}),"Enable Backup"]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:I,disabled:V||!n||!i,children:[V?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Test Connection"]})]})})]})]}):s.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[s.jsx(Cn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),s.jsx("p",{className:"text-sm text-yellow-400",children:"Bambu Cloud login required. Sign in under Profiles → Cloud Profiles to enable GitHub backup."})]})})]}),xe&&xe.length>0&&s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(q0,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),s.jsxs(Te,{variant:"ghost",size:"sm",onClick:()=>te.mutate(),disabled:te.isPending,children:[s.jsx(rn,{className:"w-4 h-4"}),"Clear"]})]})}),s.jsx(Mt,{children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[s.jsx("th",{className:"text-left py-2 px-2",children:"Date"}),s.jsx("th",{className:"text-left py-2 px-2",children:"Status"}),s.jsx("th",{className:"text-left py-2 px-2",children:"Commit"})]})}),s.jsx("tbody",{children:xe.slice(0,10).map(me=>s.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[s.jsx("td",{className:"py-2 px-2 text-white",children:yKe(me.started_at)}),s.jsx("td",{className:"py-2 px-2",children:s.jsx(fq,{status:me.status})}),s.jsx("td",{className:"py-2 px-2",children:me.commit_sha?s.jsxs("a",{href:`${ne?.repository_url}/commit/${me.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[me.commit_sha.substring(0,7),s.jsx(Kr,{className:"w-3 h-3"})]}):s.jsx("span",{className:"text-bambu-gray",children:"-"})})]},me.id))})]})})})]})]}),s.jsx("div",{className:"space-y-6",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Nu,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Download Backup"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Complete backup: database + all files (ZIP)"})]}),s.jsxs(Te,{variant:"secondary",size:"sm",disabled:T||C,onClick:async()=>{k(!0),A("Preparing backup...");try{A("Creating backup archive... This may take a while for large archives.");const{blob:me,filename:Ee}=await ue.exportBackup();A("Downloading backup file...");const z=URL.createObjectURL(me),O=document.createElement("a");O.href=z,O.download=Ee,O.click(),URL.revokeObjectURL(z),e("Backup downloaded successfully")}catch(me){e(`Failed to create backup: ${me instanceof Error?me.message:"Unknown error"}`,"error")}finally{k(!1),A("")}},children:[s.jsx(yi,{className:"w-4 h-4"}),"Download"]})]}),s.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Restore Backup"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Replace all data from a backup file"})]}),s.jsx("input",{ref:K,type:"file",accept:".zip",className:"hidden",onChange:me=>{const Ee=me.target.files?.[0];Ee&&($(Ee),U(!0)),me.target.value=""}}),s.jsxs(Te,{variant:"secondary",size:"sm",disabled:C||T,onClick:()=>K.current?.click(),children:[s.jsx(Ua,{className:"w-4 h-4"}),"Restore"]})]}),j&&s.jsx("div",{className:`p-3 rounded-lg ${j.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[j.success?s.jsx(Ar,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):s.jsx(Yi,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:j.success?"text-green-200":"text-red-200",children:[j.message,j.success&&s.jsx("div",{className:"mt-2",children:s.jsxs(Te,{size:"sm",onClick:()=>window.location.reload(),children:[s.jsx(Rh,{className:"w-3 h-3"}),"Reload Now"]})})]})]})}),s.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Cn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-yellow-200",children:[s.jsx("span",{className:"font-medium",children:"Restore replaces all data."})," ",s.jsx("span",{className:"text-yellow-200/70",children:"Your current database and files will be completely replaced. A restart is required after restore."})]})]})})]})]})}),R&&F&&s.jsx(Zn,{title:"Restore Backup",message:`Are you sure you want to restore from "${F.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()=>{U(!1),E(!0),H(null);try{A("Uploading backup file...");const me=await ue.importBackup(F);H(me),me.success?e("Backup restored. Please restart Bambuddy.","success"):e(me.message,"error")}catch(me){const Ee=me instanceof Error?me.message:"Failed to restore backup";H({success:!1,message:Ee}),e(Ee,"error")}finally{E(!1),A(""),$(null)}},onCancel:()=>{U(!1),$(null)}}),(T||C)&&s.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:s.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:[s.jsx("div",{className:"flex justify-center mb-4",children:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),s.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),s.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:T?"Creating Backup":"Restoring Backup"}),s.jsx("p",{className:"text-bambu-gray mb-4",children:D||(T?"Preparing...":"Processing...")}),s.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Cn,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),s.jsx("p",{className:"text-yellow-200 text-left",children:"Please do not close this page or navigate away. This operation may take several minutes for large backups."})]})})]})})]})}const wKe={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 _Ke(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function p0(t,e,n=0){if(n>5)return"...";if(e.$ref)return p0(t,_Ke(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const a=p0(t,i,n+1);typeof a=="object"&&a!==null&&Object.assign(r,a)}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?[p0(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,a]of Object.entries(e.properties))r[i]=p0(t,a,n+1);return r}return{};default:return null}}function SKe({path:t,method:e,spec:n,schema:r,apiKey:i}){const[a,o]=_.useState(!1),[l,c]=_.useState({}),[u,d]=_.useState(""),[f,p]=_.useState(null),[m,x]=_.useState(!1),[b,y]=_.useState(!1);_.useEffect(()=>{if(a&&n.parameters){const D={};for(const A of n.parameters)A.schema?.default!==void 0&&(D[A.name]=String(A.schema.default));c(A=>({...D,...A}))}},[a,n.parameters]),_.useEffect(()=>{if(a&&n.requestBody?.content?.["application/json"]?.schema&&!u){const D=n.requestBody.content["application/json"].schema,A=p0(r,D);d(JSON.stringify(A,null,2))}},[a,n.requestBody,r,u]);const S=(()=>{const D=[];for(const A of n.parameters||[])if(A.in==="path"||A.required){const R=l[A.name];(R===void 0||R==="")&&D.push(A.name)}return D})(),N=async()=>{if(S.length>0){p({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${S.join(", ")}`,duration:0});return}x(!0),p(null);try{let D=t;const A=new URLSearchParams;for(const ae of n.parameters||[]){const B=l[ae.name];B!==void 0&&B!==""&&(ae.in==="path"?D=D.replace(`{${ae.name}}`,encodeURIComponent(B)):ae.in==="query"&&A.append(ae.name,B))}const R=A.toString(),U=`${D}${R?`?${R}`:""}`,F={"Content-Type":"application/json"};i&&(F["X-API-Key"]=i);const $={method:e.toUpperCase(),headers:F};["post","put","patch"].includes(e)&&u&&($.body=u);const j=performance.now(),H=await fetch(U,$),K=Math.round(performance.now()-j),V={};H.headers.forEach((ae,B)=>{V[B]=ae});let Q;H.headers.get("content-type")?.includes("application/json")?Q=await H.json():Q=await H.text(),p({status:H.status,statusText:H.statusText,headers:V,body:Q,duration:K})}catch(D){p({status:0,statusText:"Network Error",headers:{},body:D instanceof Error?D.message:"Unknown error",duration:0})}finally{x(!1)}},T=async()=>{if(f){const D=typeof f.body=="string"?f.body:JSON.stringify(f.body,null,2);try{await navigator.clipboard.writeText(D),y(!0),setTimeout(()=>y(!1),2e3)}catch{const A=document.createElement("textarea");A.value=D,A.style.position="fixed",A.style.left="-999999px",document.body.appendChild(A),A.select(),document.execCommand("copy"),document.body.removeChild(A),y(!0),setTimeout(()=>y(!1),2e3)}}},k=(n.parameters||[]).filter(D=>D.in==="path"),C=(n.parameters||[]).filter(D=>D.in==="query"),E=["post","put","patch"].includes(e)&&n.requestBody;return s.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[s.jsxs("button",{onClick:()=>o(!a),className:"w-full flex items-center gap-3 p-3 hover:bg-bambu-dark-tertiary/50 transition-colors text-left",children:[a?s.jsx(ei,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):s.jsx(gs,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),s.jsx("span",{className:`px-2 py-0.5 text-xs font-mono font-semibold uppercase rounded border ${wKe[e]||"bg-gray-500/20 text-gray-400"}`,children:e}),s.jsx("code",{className:"text-sm text-white font-mono flex-1 truncate",children:t}),n.summary&&s.jsx("span",{className:"text-sm text-bambu-gray truncate max-w-[40%]",children:n.summary})]}),a&&s.jsxs("div",{className:"border-t border-bambu-dark-tertiary p-4 space-y-4 bg-bambu-dark/50",children:[n.description&&s.jsx("p",{className:"text-sm text-bambu-gray",children:n.description}),k.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"text-sm font-medium text-white",children:"Path Parameters"}),s.jsx("div",{className:"space-y-2",children:k.map(D=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[D.name,D.required&&s.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),s.jsx("input",{type:"text",value:l[D.name]||"",onChange:A=>c(R=>({...R,[D.name]:A.target.value})),placeholder:D.description||D.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"})]},D.name))})]}),C.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"text-sm font-medium text-white",children:"Query Parameters"}),s.jsx("div",{className:"space-y-2",children:C.map(D=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("label",{className:"text-sm text-bambu-gray w-32 flex-shrink-0",children:[D.name,D.required&&s.jsx("span",{className:"text-red-400 ml-1",children:"*"})]}),D.schema?.enum?s.jsxs("select",{value:l[D.name]||"",onChange:A=>c(R=>({...R,[D.name]:A.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:[s.jsx("option",{value:"",children:"-- Select --"}),D.schema.enum.map(A=>s.jsx("option",{value:A,children:A},A))]}):s.jsx("input",{type:"text",value:l[D.name]||"",onChange:A=>c(R=>({...R,[D.name]:A.target.value})),placeholder:D.description||D.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"})]},D.name))})]}),E&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("h4",{className:"text-sm font-medium text-white",children:"Request Body"}),s.jsx("textarea",{value:u,onChange:D=>d(D.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..."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Te,{onClick:N,disabled:m,children:[m?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Is,{className:"w-4 h-4"}),"Execute"]}),S.length>0&&s.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[s.jsx(Hi,{className:"w-3 h-3"}),"Fill in: ",S.join(", ")]})]}),f&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h4",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Response",s.jsxs("span",{className:`px-2 py-0.5 text-xs rounded ${f.status>=200&&f.status<300?"bg-green-500/20 text-green-400":f.status>=400?"bg-red-500/20 text-red-400":"bg-yellow-500/20 text-yellow-400"}`,children:[f.status," ",f.statusText]}),s.jsxs("span",{className:"text-xs text-bambu-gray",children:[f.duration,"ms"]})]}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:T,children:b?s.jsx(Ar,{className:"w-3 h-3 text-green-400"}):s.jsx(Fl,{className:"w-3 h-3"})})]}),s.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 f.body=="string"?f.body:JSON.stringify(f.body,null,2)})]})]})]})}function MKe({apiKey:t=""}){const[e,n]=_.useState(null),[r,i]=_.useState(!0),[a,o]=_.useState(null),[l,c]=_.useState(new Set),[u,d]=_.useState("");if(_.useEffect(()=>{async function y(){try{const v=await fetch("/openapi.json");if(!v.ok)throw new Error("Failed to fetch OpenAPI schema");const S=await v.json();n(S)}catch(v){o(v instanceof Error?v.message:"Unknown error")}finally{i(!1)}}y()},[]),r)return s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(a||!e)return s.jsx(_t,{children:s.jsx(Mt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-red-400",children:[s.jsx(Hi,{className:"w-12 h-12 mx-auto mb-3 opacity-50"}),s.jsx("p",{children:"Failed to load API schema"}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a})]})})});const f={};for(const[y,v]of Object.entries(e.paths))for(const[S,N]of Object.entries(v)){if(S==="parameters")continue;const T=N.tags||["Other"];for(const k of T)f[k]||(f[k]=[]),f[k].push({path:y,method:S,spec:N})}const p=Object.entries(f).map(([y,v])=>{if(!u)return{tag:y,endpoints:v};const S=v.filter(({path:N,method:T,spec:k})=>{const C=u.toLowerCase();return N.toLowerCase().includes(C)||T.toLowerCase().includes(C)||(k.summary?.toLowerCase()||"").includes(C)||(k.description?.toLowerCase()||"").includes(C)});return{tag:y,endpoints:S}}).filter(({endpoints:y})=>y.length>0).sort((y,v)=>y.tag.localeCompare(v.tag)),m=y=>{c(v=>{const S=new Set(v);return S.has(y)?S.delete(y):S.add(y),S})},x=()=>{c(new Set(p.map(y=>y.tag)))},b=()=>{c(new Set)};return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsx("div",{className:"flex-1",children:s.jsx("input",{type:"text",value:u,onChange:y=>d(y.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"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Te,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:b,children:"Collapse All"}),s.jsxs("a",{href:"/docs",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-bambu-green hover:underline",children:[s.jsx(Kr,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:[p.reduce((y,v)=>y+v.endpoints.length,0)," endpoints in ",p.length," categories"]}),s.jsx("div",{className:"space-y-3",children:p.map(({tag:y,endpoints:v})=>s.jsxs(_t,{children:[s.jsx("button",{onClick:()=>m(y),className:"w-full flex items-center justify-between p-4 hover:bg-bambu-dark-tertiary/30 transition-colors text-left",children:s.jsxs("div",{className:"flex items-center gap-2",children:[l.has(y)?s.jsx(ei,{className:"w-5 h-5 text-bambu-gray"}):s.jsx(gs,{className:"w-5 h-5 text-bambu-gray"}),s.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:y.replace(/-/g," ")}),s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-2 py-0.5 rounded-full text-bambu-gray",children:v.length})]})}),l.has(y)&&s.jsx(Mt,{className:"pt-0 space-y-2",children:v.map(({path:S,method:N,spec:T})=>s.jsx(SKe,{path:S,method:N,spec:T,schema:e,apiKey:t},`${N}-${S}`))})]},y))})]})}const NKe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"];function kKe(){const t=an(),e=Nc(),[n,r]=wR(),{t:i,i18n:a}=Hn(),{showToast:o}=$n(),{authEnabled:l,user:c,refreshAuth:u}=Ai(),{mode:d,darkStyle:f,darkBackground:p,darkAccent:m,lightStyle:x,lightBackground:b,lightAccent:y,setDarkStyle:v,setDarkBackground:S,setDarkAccent:N,setLightStyle:T,setLightBackground:k,setLightAccent:C}=Oh(),[E,D]=_.useState(null),[A,R]=_.useState(!1),[U,F]=_.useState(null),[$,j]=_.useState(!1),[H,K]=_.useState(null),[V,Q]=_.useState(null),[Z,ae]=_.useState(!1),[B,X]=_.useState(OW()),ne=n.get("tab"),se=ne&&NKe.includes(ne)?ne:"general",[be,xe]=_.useState(se),de=oe=>{xe(oe),oe==="general"?n.delete("tab"):n.set("tab",oe),r(n,{replace:!0})},[Pe,ie]=_.useState(!1),[Ne,Oe]=_.useState(""),[ge,Ke]=_.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[G,Y]=_.useState(null),[ce,q]=_.useState(null),[te,I]=_.useState(""),[fe,me]=_.useState(!1),[Ee,z]=_.useState(!1),[O,ee]=_.useState(null),[le,_e]=_.useState(!1),[we,re]=_.useState(!1),[Fe,He]=_.useState(!1),[Ve,$e]=_.useState({currentPassword:"",newPassword:"",confirmPassword:""}),[ye,je]=_.useState(!1),[Be,Se]=_.useState(!1),[Xe,Me]=_.useState(!1),[tt,ke]=_.useState(null),[We,ze]=_.useState(null),[W,De]=_.useState(null),[Ye,xt]=_.useState(!1),[ft,Bt]=_.useState({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]}),[Lt,vn]=_.useState(!1),[Jt,ir]=_.useState(null),[fr,Dn]=_.useState(null),[ln,mr]=_.useState({name:"",description:"",permissions:[]}),[Fn,Xn]=_.useState(new Set),[bn,wi]=_.useState(null),[Ba,Ae]=_.useState(!1),[Ze,st]=_.useState({}),[lt,ot]=_.useState({}),Et=oe=>{X(oe),jfe(oe),o(i("settings.toast.settingsSaved"),"success")},he=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:pe,isLoading:Ie}=at({queryKey:["settings"],queryFn:ue.getSettings}),{data:Le,isLoading:Ce}=at({queryKey:["smart-plugs"],queryFn:ue.getSmartPlugs}),{data:ut,isLoading:St}=at({queryKey:["smart-plugs-energy",Le?.map(oe=>oe.id)],queryFn:async()=>{if(!Le||Le.length===0)return null;const oe=await Promise.all(Le.filter(is=>is.enabled).map(async is=>{try{const as=await ue.getSmartPlugStatus(is.id);return{plug:is,status:as}}catch{return{plug:is,status:null}}}));let wt=0,Rn=0,Jn=0,No=0,Ju=0;for(const{plug:is,status:as}of oe){const $x=is.plug_type==="mqtt"&&as?.energy?.power!=null;(as?.reachable||$x)&&as?.energy&&(Ju++,as.energy?.power!=null&&(wt+=as.energy.power),as.energy?.today!=null&&(Rn+=as.energy.today),as.energy?.yesterday!=null&&(Jn+=as.energy.yesterday),as.energy?.total!=null&&(No+=as.energy.total))}return{totalPower:wt,totalToday:Rn,totalYesterday:Jn,totalLifetime:No,reachableCount:Ju,totalPlugs:Le.filter(is=>is.enabled).length}},enabled:be==="plugs"&&!!Le&&Le.length>0,refetchInterval:be==="plugs"?1e4:!1}),{data:At,isLoading:Tt}=at({queryKey:["notification-providers"],queryFn:ue.getNotificationProviders}),{data:Ft,isLoading:Pt}=at({queryKey:["api-keys"],queryFn:ue.getAPIKeys}),Nt=mt({mutationFn:oe=>ue.createAPIKey(oe),onSuccess:oe=>{Y(oe.key||null),ie(!1),Oe(""),t.invalidateQueries({queryKey:["api-keys"]}),o(i("settings.toast.apiKeyCreated"))},onError:oe=>{o(`Failed to create API key: ${oe.message}`,"error")}}),en=mt({mutationFn:oe=>ue.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:Ht}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:dn,isLoading:cn}=at({queryKey:["notification-templates"],queryFn:ue.getNotificationTemplates}),{data:Sn}=at({queryKey:["virtual-printer-settings"],queryFn:p1.getSettings,refetchInterval:1e4}),Gt=Sn?.status?.running??!1,{data:sn}=at({queryKey:["ffmpeg-status"],queryFn:ue.checkFfmpeg}),{data:un}=at({queryKey:["version"],queryFn:ue.getVersion}),{data:Yt,refetch:nr,isRefetching:jn}=at({queryKey:["updateCheck"],queryFn:ue.checkForUpdates,staleTime:300*1e3}),{data:ii,refetch:rr}=at({queryKey:["updateStatus"],queryFn:ue.getUpdateStatus,refetchInterval:oe=>{const wt=oe.state.data;return wt?.status==="downloading"||wt?.status==="installing"?1e3:!1}}),{data:cr}=at({queryKey:["mqtt-status"],queryFn:ue.getMQTTStatus,refetchInterval:be==="network"?5e3:!1}),{data:et}=at({queryKey:["github-backup-status"],queryFn:ue.getGitHubBackupStatus}),{data:jt}=at({queryKey:["cloud-status"],queryFn:ue.getCloudStatus}),{hasPermission:qt}=Ai(),{data:yt=[],isLoading:wn}=at({queryKey:["users"],queryFn:()=>ue.getUsers(),enabled:l&&qt("users:read")}),{data:Fr=[],isLoading:Yr}=at({queryKey:["groups"],queryFn:()=>ue.getGroups(),enabled:l&&qt("groups:read")}),{data:Br}=at({queryKey:["permissions"],queryFn:()=>ue.getPermissions(),enabled:l&&qt("groups:read")}),Ws=mt({mutationFn:oe=>ue.createUser(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userCreated"))},onError:oe=>{o(oe.message,"error")}}),tn=mt({mutationFn:({id:oe,data:wt})=>ue.updateUser(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),t.invalidateQueries({queryKey:["groups"]}),Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]}),o(i("settings.toast.userUpdated"))},onError:oe=>{o(oe.message,"error")}}),on=mt({mutationFn:({id:oe,deleteItems:wt})=>ue.deleteUser(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["users"]}),o(i("settings.toast.userDeleted")),ze(null),De(null)},onError:oe=>{o(oe.message,"error")}}),_i=async oe=>{ze(oe),xt(!0);try{const wt=await ue.getUserItemsCount(oe);De(wt)}catch{De({archives:0,queue_items:0,library_files:0})}finally{xt(!1)}},Ss=mt({mutationFn:oe=>ue.createGroup(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),vn(!1),la(),o(i("settings.toast.groupCreated"))},onError:oe=>{o(oe.message,"error")}}),_o=mt({mutationFn:({id:oe,data:wt})=>ue.updateGroup(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),ir(null),la(),o(i("settings.toast.groupUpdated"))},onError:oe=>{o(oe.message,"error")}}),So=mt({mutationFn:oe=>ue.deleteGroup(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["groups"]}),o(i("settings.toast.groupDeleted"))},onError:oe=>{o(oe.message,"error")}}),Mo=()=>{if(!ft.username||!ft.password){o(i("settings.toast.fillRequiredFields"),"error");return}if(ft.password!==ft.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(ft.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}Ws.mutate({username:ft.username,password:ft.password,role:ft.role,group_ids:ft.group_ids.length>0?ft.group_ids:void 0})},Ms=oe=>{if(ft.password){if(ft.password!==ft.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(ft.password.length<6){o(i("settings.toast.passwordTooShort"),"error");return}}const wt={username:ft.username||void 0,password:ft.password||void 0,role:ft.role,group_ids:ft.group_ids};wt.password||delete wt.password,tn.mutate({id:oe,data:wt})},Si=oe=>{ke(oe.id),Bt({username:oe.username,password:"",confirmPassword:"",role:oe.role,group_ids:oe.groups?.map(wt=>wt.id)||[]}),Me(!0)},Ks=oe=>{Bt(wt=>({...wt,group_ids:wt.group_ids.includes(oe)?wt.group_ids.filter(Rn=>Rn!==oe):[...wt.group_ids,oe]}))},la=()=>{mr({name:"",description:"",permissions:[]}),Xn(new Set)},Hr=()=>{if(!ln.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}Ss.mutate({name:ln.name,description:ln.description||void 0,permissions:ln.permissions})},Ux=()=>{if(Jt){if(!ln.name.trim()){o(i("settings.toast.enterGroupName"),"error");return}_o.mutate({id:Jt.id,data:{name:ln.name!==Jt.name?ln.name:void 0,description:ln.description,permissions:ln.permissions}})}},$h=oe=>{ir(oe),mr({name:oe.name,description:oe.description||"",permissions:oe.permissions});const wt=new Set;Br?.categories.forEach(Rn=>{Rn.permissions.some(Jn=>oe.permissions.includes(Jn.value))&&wt.add(Rn.name)}),Xn(wt)},$l=oe=>{Xn(wt=>{const Rn=new Set(wt);return Rn.has(oe)?Rn.delete(oe):Rn.add(oe),Rn})},zx=oe=>{mr(wt=>{const Rn=wt.permissions.includes(oe)?wt.permissions.filter(Jn=>Jn!==oe):[...wt.permissions,oe];return{...wt,permissions:Rn}})},Dm=(oe,wt)=>{mr(Rn=>{const Jn=oe.permissions.map(is=>is.value),No=Rn.permissions.filter(is=>!Jn.includes(is)),Ju=wt?[...No,...Jn]:No;return{...Rn,permissions:Ju}})},Rm=oe=>oe.permissions.every(wt=>ln.permissions.includes(wt.value)),Vh=oe=>{const wt=oe.permissions.filter(Rn=>ln.permissions.includes(Rn.value));return wt.length>0&&wt.length{oe.is_docker?o(oe.message,"error"):rr()}}),[Cc,ca]=_.useState(null),pl=mt({mutationFn:ue.testAllNotificationProviders,onSuccess:oe=>{ca(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")}}),Vl=mt({mutationFn:async oe=>{if(!Le)return{success:0,failed:0};const wt=Le.filter(Jn=>Jn.enabled),Rn=await Promise.all(wt.map(async Jn=>{try{return await ue.controlSmartPlug(Jn.id,oe),{success:!0}}catch{return{success:!1}}}));return{success:Rn.filter(Jn=>Jn.success).length,failed:Rn.filter(Jn=>!Jn.success).length}},onSuccess:(oe,wt)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),oe.failed===0?o(`All ${oe.success} plugs turned ${wt}`,"success"):o(`${oe.success} plugs turned ${wt}, ${oe.failed} failed`,"error")},onError:oe=>{o(`Failed: ${oe.message}`,"error")}}),gl=_.useRef(null),Om=_.useRef(!1),Lm=_.useRef(!0);_.useEffect(()=>{if(pe&&!E){const oe={...pe,external_url:pe.external_url||window.location.origin};D(oe),setTimeout(()=>{Lm.current=!1},100)}},[pe,E]);const Fm=mt({mutationFn:ue.updateSettings,onSuccess:oe=>{t.setQueryData(["settings"],oe),D(oe),t.invalidateQueries({queryKey:["archiveStats"]}),o(i("settings.toast.settingsSaved"),"success")},onError:oe=>{o(`Failed to save: ${oe.message}`,"error")},onSettled:()=>{Om.current=!1}}),Zu=mt({mutationFn:({id:oe,data:wt})=>ue.updatePrinter(oe,wt),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o(i("settings.toast.cameraSettingsSaved"),"success")},onError:oe=>{o(`Failed to update printer: ${oe.message}`,"error")}});_.useEffect(()=>{if(!(Lm.current||!E||!pe||!(pe.auto_archive!==E.auto_archive||pe.save_thumbnails!==E.save_thumbnails||pe.capture_finish_photo!==E.capture_finish_photo||pe.default_filament_cost!==E.default_filament_cost||pe.currency!==E.currency||pe.energy_cost_per_kwh!==E.energy_cost_per_kwh||pe.energy_tracking_mode!==E.energy_tracking_mode||pe.check_updates!==E.check_updates||(pe.check_printer_firmware??!0)!==(E.check_printer_firmware??!0)||pe.notification_language!==E.notification_language||pe.ams_humidity_good!==E.ams_humidity_good||pe.ams_humidity_fair!==E.ams_humidity_fair||pe.ams_temp_good!==E.ams_temp_good||pe.ams_temp_fair!==E.ams_temp_fair||pe.ams_history_retention_days!==E.ams_history_retention_days||pe.per_printer_mapping_expanded!==E.per_printer_mapping_expanded||pe.date_format!==E.date_format||pe.time_format!==E.time_format||pe.default_printer_id!==E.default_printer_id||pe.ftp_retry_enabled!==E.ftp_retry_enabled||pe.ftp_retry_count!==E.ftp_retry_count||pe.ftp_retry_delay!==E.ftp_retry_delay||pe.ftp_timeout!==E.ftp_timeout||pe.mqtt_enabled!==E.mqtt_enabled||pe.mqtt_broker!==E.mqtt_broker||pe.mqtt_port!==E.mqtt_port||pe.mqtt_username!==E.mqtt_username||pe.mqtt_password!==E.mqtt_password||pe.mqtt_topic_prefix!==E.mqtt_topic_prefix||pe.mqtt_use_tls!==E.mqtt_use_tls||pe.external_url!==E.external_url||pe.ha_enabled!==E.ha_enabled||pe.ha_url!==E.ha_url||pe.ha_token!==E.ha_token||(pe.library_archive_mode??"ask")!==(E.library_archive_mode??"ask")||Number(pe.library_disk_warning_gb??5)!==Number(E.library_disk_warning_gb??5)||(pe.camera_view_mode??"window")!==(E.camera_view_mode??"window")||pe.prometheus_enabled!==E.prometheus_enabled||pe.prometheus_token!==E.prometheus_token))&&!Om.current)return gl.current&&clearTimeout(gl.current),gl.current=setTimeout(()=>{if(Om.current)return;Om.current=!0;const wt={auto_archive:E.auto_archive,save_thumbnails:E.save_thumbnails,capture_finish_photo:E.capture_finish_photo,default_filament_cost:E.default_filament_cost,currency:E.currency,energy_cost_per_kwh:E.energy_cost_per_kwh,energy_tracking_mode:E.energy_tracking_mode,check_updates:E.check_updates,check_printer_firmware:E.check_printer_firmware,notification_language:E.notification_language,ams_humidity_good:E.ams_humidity_good,ams_humidity_fair:E.ams_humidity_fair,ams_temp_good:E.ams_temp_good,ams_temp_fair:E.ams_temp_fair,ams_history_retention_days:E.ams_history_retention_days,per_printer_mapping_expanded:E.per_printer_mapping_expanded,date_format:E.date_format,time_format:E.time_format,default_printer_id:E.default_printer_id,ftp_retry_enabled:E.ftp_retry_enabled,ftp_retry_count:E.ftp_retry_count,ftp_retry_delay:E.ftp_retry_delay,ftp_timeout:E.ftp_timeout,mqtt_enabled:E.mqtt_enabled,mqtt_broker:E.mqtt_broker,mqtt_port:E.mqtt_port,mqtt_username:E.mqtt_username,mqtt_password:E.mqtt_password,mqtt_topic_prefix:E.mqtt_topic_prefix,mqtt_use_tls:E.mqtt_use_tls,external_url:E.external_url,ha_enabled:E.ha_enabled,ha_url:E.ha_url,ha_token:E.ha_token,library_archive_mode:E.library_archive_mode,library_disk_warning_gb:E.library_disk_warning_gb,camera_view_mode:E.camera_view_mode,prometheus_enabled:E.prometheus_enabled,prometheus_token:E.prometheus_token};Fm.mutate(wt)},500),()=>{gl.current&&clearTimeout(gl.current)}},[E,pe,Fm]);const hn=_.useCallback((oe,wt)=>{D(Rn=>Rn?{...Rn,[oe]:wt}:null)},[]),Sv=async(oe,wt,Rn)=>{if(!wt){o(i("settings.toast.enterCameraUrl"),"error");return}ot(Jn=>({...Jn,[oe]:!0})),st(Jn=>({...Jn,[oe]:null}));try{const Jn=await ue.testExternalCamera(oe,wt,Rn);st(No=>({...No,[oe]:Jn})),Jn.success?o(i("settings.toast.cameraConnected",{resolution:Jn.resolution||""}),"success"):o(Jn.error||i("settings.toast.connectionFailed"),"error")}catch(Jn){const No=Jn instanceof Error?Jn.message:i("settings.toast.testFailed");st(Ju=>({...Ju,[oe]:{success:!1,error:No}})),o(No,"error")}finally{ot(Jn=>({...Jn,[oe]:!1}))}},[Bx,Mv]=_.useState({}),Hx=_.useRef({}),Im=_.useRef(new Set);_.useEffect(()=>{if(Ht){const oe={};Ht.forEach(wt=>{wt.external_camera_url&&!Im.current.has(wt.id)&&(oe[wt.id]=wt.external_camera_url,Im.current.add(wt.id))}),Object.keys(oe).length>0&&Mv(wt=>({...wt,...oe}))}},[Ht]);const G2=(oe,wt)=>{Mv(Rn=>({...Rn,[oe]:wt})),Hx.current[oe]&&clearTimeout(Hx.current[oe]),Hx.current[oe]=setTimeout(()=>{Zu.mutate({id:oe,data:{external_camera_url:wt||null}})},800)},Nv=(oe,wt)=>{const Rn={};wt.type!==void 0&&(Rn.external_camera_type=wt.type||null),wt.enabled!==void 0&&(Rn.external_camera_enabled=wt.enabled),Zu.mutate({id:oe,data:Rn})};return Ie||!E?s.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):s.jsxs("div",{className:"p-4 md:p-8",children:[s.jsxs("div",{className:"mb-8",children:[s.jsx("h1",{className:"text-2xl font-bold text-white",children:i("settings.title")}),s.jsx("p",{className:"text-bambu-gray",children:i("settings.configureBambuddy")})]}),s.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary overflow-x-auto",children:[s.jsx("button",{onClick:()=>de("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${be==="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")}),s.jsxs("button",{onClick:()=>de("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(tl,{className:"w-4 h-4"}),i("settings.tabs.smartPlugs"),Le&&Le.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Le.length})]}),s.jsxs("button",{onClick:()=>de("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(wg,{className:"w-4 h-4"}),i("settings.tabs.notifications"),At&&At.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:At.length})]}),s.jsxs("button",{onClick:()=>de("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(hue,{className:"w-4 h-4"}),i("settings.tabs.filament")]}),s.jsxs("button",{onClick:()=>de("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Sg,{className:"w-4 h-4"}),i("settings.tabs.network"),s.jsx("span",{className:`w-2 h-2 rounded-full ${cr?.enabled?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>de("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx($o,{className:"w-4 h-4"}),i("settings.tabs.apiKeys"),Ft&&Ft.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Ft.length})]}),s.jsxs("button",{onClick:()=>de("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Ur,{className:"w-4 h-4"}),i("settings.tabs.virtualPrinter"),s.jsx("span",{className:`w-2 h-2 rounded-full ${Gt?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>de("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(mg,{className:"w-4 h-4"}),i("settings.tabs.users"),l&&s.jsx("span",{className:`w-2 h-2 rounded-full ${l?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>de("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${be==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Nu,{className:"w-4 h-4"}),i("settings.tabs.backup"),s.jsx("span",{className:`w-2 h-2 rounded-full ${jt?.is_authenticated&&et?.configured&&et?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),be==="general"&&s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[s.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-xl",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(sh,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),s.jsxs("div",{className:"relative",children:[s.jsx("select",{value:a.language,onChange:oe=>{a.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:mz.map(oe=>s.jsxs("option",{value:oe.code,children:[oe.nativeName," (",oe.name,")"]},oe.code))}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.languageDescription")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.defaultView")}),s.jsxs("div",{className:"relative",children:[s.jsx("select",{value:B,onChange:oe=>Et(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:K0.map(oe=>s.jsx("option",{value:oe.to,children:i(oe.labelKey)},oe.id))}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:i("settings.defaultViewDescription")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Date Format"}),s.jsxs("div",{className:"relative",children:[s.jsxs("select",{value:E.date_format||"system",onChange:oe=>hn("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:[s.jsx("option",{value:"system",children:i("settings.systemDefault")}),s.jsx("option",{value:"us",children:"US (MM/DD/YYYY)"}),s.jsx("option",{value:"eu",children:"EU (DD/MM/YYYY)"}),s.jsx("option",{value:"iso",children:"ISO (YYYY-MM-DD)"})]}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),s.jsxs("div",{className:"relative",children:[s.jsxs("select",{value:E.time_format||"system",onChange:oe=>hn("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:[s.jsx("option",{value:"system",children:i("settings.systemDefault")}),s.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),s.jsx("option",{value:"24h",children:"24-hour (15:30)"})]}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),s.jsxs("div",{className:"relative",children:[s.jsxs("select",{value:E.default_printer_id??"",onChange:oe=>hn("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:[s.jsx("option",{value:"",children:i("settings.noDefaultPrinter")}),Ht?.map(oe=>s.jsx("option",{value:oe.id,children:oe.name},oe.id))]}),s.jsx(ei,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Pre-select this printer for uploads, reprints, and other operations."})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.sidebarOrder")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:he,children:[s.jsx(Rh,{className:"w-4 h-4"}),"Reset"]})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(SW,{className:"w-5 h-5"}),"Appearance"]})}),s.jsxs(Mt,{className:"space-y-6",children:[s.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:[s.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Dark Mode",d==="dark"&&s.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),s.jsxs("select",{value:p,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:[s.jsx("option",{value:"neutral",children:"Neutral"}),s.jsx("option",{value:"warm",children:"Warm"}),s.jsx("option",{value:"cool",children:"Cool"}),s.jsx("option",{value:"oled",children:"OLED Black"}),s.jsx("option",{value:"slate",children:"Slate Blue"}),s.jsx("option",{value:"forest",children:"Forest Green"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),s.jsxs("select",{value:m,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:[s.jsx("option",{value:"green",children:"Green"}),s.jsx("option",{value:"teal",children:"Teal"}),s.jsx("option",{value:"blue",children:"Blue"}),s.jsx("option",{value:"orange",children:"Orange"}),s.jsx("option",{value:"purple",children:"Purple"}),s.jsx("option",{value:"red",children:"Red"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),s.jsxs("select",{value:f,onChange:oe=>{v(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:[s.jsx("option",{value:"classic",children:"Classic"}),s.jsx("option",{value:"glow",children:"Glow"}),s.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),s.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:[s.jsxs("h3",{className:"text-sm font-medium text-white flex items-center gap-2",children:["Light Mode",d==="light"&&s.jsx("span",{className:"text-xs text-bambu-green",children:"(active)"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Background"}),s.jsxs("select",{value:b,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:[s.jsx("option",{value:"neutral",children:"Neutral"}),s.jsx("option",{value:"warm",children:"Warm"}),s.jsx("option",{value:"cool",children:"Cool"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Accent"}),s.jsxs("select",{value:y,onChange:oe=>{C(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:[s.jsx("option",{value:"green",children:"Green"}),s.jsx("option",{value:"teal",children:"Teal"}),s.jsx("option",{value:"blue",children:"Blue"}),s.jsx("option",{value:"orange",children:"Orange"}),s.jsx("option",{value:"purple",children:"Purple"}),s.jsx("option",{value:"red",children:"Red"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:"Style"}),s.jsxs("select",{value:x,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:[s.jsx("option",{value:"classic",children:"Classic"}),s.jsx("option",{value:"glow",children:"Glow"}),s.jsx("option",{value:"vibrant",children:"Vibrant"})]})]})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Toggle between dark and light mode using the sun/moon icon in the sidebar."})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.archiveSettings")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Auto-archive prints"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically save 3MF files when prints complete"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.auto_archive,onChange:oe=>hn("auto_archive",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.saveThumbnails")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Extract and save preview images from 3MF files"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.save_thumbnails,onChange:oe=>hn("save_thumbnails",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.captureFinishPhoto")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Take a photo from printer camera when print completes"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.capture_finish_photo,onChange:oe=>hn("capture_finish_photo",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.capture_finish_photo&&sn&&!sn.installed&&s.jsxs("div",{className:"flex items-start gap-2 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg",children:[s.jsx(Cn,{className:"w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm",children:[s.jsx("p",{className:"text-yellow-500 font-medium",children:"ffmpeg not installed"}),s.jsxs("p",{className:"text-bambu-gray mt-1",children:["Camera capture requires ffmpeg. Install it via"," ",s.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"brew install ffmpeg"})," (macOS) or"," ",s.jsx("code",{className:"bg-bambu-dark-tertiary px-1 rounded",children:"apt install ffmpeg"})," (Linux)."]})]})]})]})]})]}),s.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-md",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(OR,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Camera View Mode"}),s.jsxs("select",{value:E.camera_view_mode??"window",onChange:oe=>hn("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:[s.jsx("option",{value:"window",children:i("settings.newWindow")}),s.jsx("option",{value:"embedded",children:i("settings.embeddedOverlay")})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:E.camera_view_mode==="embedded"?"Camera opens in a resizable overlay on the main screen":"Camera opens in a separate browser window"})]}),s.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4",children:[s.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:i("settings.externalCameras")}),s.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."}),Ht&&Ht.length>0?s.jsx("div",{className:"space-y-3",children:Ht.map(oe=>s.jsxs("div",{className:"p-3 bg-bambu-dark rounded-lg",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-white font-medium text-sm",children:oe.name}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:oe.external_camera_enabled,onChange:wt=>Nv(oe.id,{enabled:wt.target.checked}),className:"sr-only peer"}),s.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&&s.jsxs("div",{className:"space-y-2 mt-2",children:[s.jsx("input",{type:"text",placeholder:oe.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Bx[oe.id]??oe.external_camera_url??"",onChange:wt=>G2(oe.id,wt.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"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("select",{value:oe.external_camera_type||"mjpeg",onChange:wt=>Nv(oe.id,{type:wt.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:[s.jsx("option",{value:"mjpeg",children:"MJPEG Stream"}),s.jsx("option",{value:"rtsp",children:"RTSP Stream"}),s.jsx("option",{value:"snapshot",children:"HTTP Snapshot"}),s.jsx("option",{value:"usb",children:"USB Camera (V4L2)"})]}),s.jsx(Te,{size:"sm",variant:"secondary",onClick:()=>Sv(oe.id,Bx[oe.id]??oe.external_camera_url??"",oe.external_camera_type||"mjpeg"),disabled:lt[oe.id]||!(Bx[oe.id]??oe.external_camera_url),children:lt[oe.id]?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):"Test"})]}),Ze[oe.id]&&s.jsx("div",{className:`text-xs flex items-center gap-1 ${Ze[oe.id]?.success?"text-green-500":"text-red-500"}`,children:Ze[oe.id]?.success?s.jsxs(s.Fragment,{children:[s.jsx(Ar,{className:"w-3 h-3"}),"Connected",Ze[oe.id]?.resolution&&` (${Ze[oe.id]?.resolution})`]}):s.jsxs(s.Fragment,{children:[s.jsx(Yi,{className:"w-3 h-3"}),Ze[oe.id]?.error||i("settings.toast.connectionFailed")]})})]})]},oe.id))}):s.jsx("p",{className:"text-xs text-bambu-gray italic",children:i("settings.noPrintersConfigured")})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.costTracking")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default filament cost (per kg)"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:E.default_filament_cost,onChange:oe=>hn("default_filament_cost",parseFloat(oe.target.value)||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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Currency"}),s.jsxs("select",{value:E.currency,onChange:oe=>hn("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:[s.jsx("option",{value:"USD",children:"USD ($)"}),s.jsx("option",{value:"EUR",children:"EUR (€)"}),s.jsx("option",{value:"GBP",children:"GBP (£)"}),s.jsx("option",{value:"CHF",children:"CHF (Fr.)"}),s.jsx("option",{value:"JPY",children:"JPY (¥)"}),s.jsx("option",{value:"CNY",children:"CNY (¥)"}),s.jsx("option",{value:"CAD",children:"CAD ($)"}),s.jsx("option",{value:"AUD",children:"AUD ($)"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Electricity cost per kWh"}),s.jsx("input",{type:"number",step:"0.01",min:"0",value:E.energy_cost_per_kwh,onChange:oe=>hn("energy_cost_per_kwh",parseFloat(oe.target.value)||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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Energy display mode"}),s.jsxs("select",{value:E.energy_tracking_mode||"total",onChange:oe=>hn("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:[s.jsx("option",{value:"print",children:i("settings.printsOnly")}),s.jsx("option",{value:"total",children:i("settings.totalConsumption")})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:E.energy_tracking_mode==="print"?"Dashboard shows sum of energy used during prints":"Dashboard shows lifetime energy from smart plugs"})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Ls,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Create Archive Entry When Printing"}),s.jsxs("select",{value:E.library_archive_mode??"ask",onChange:oe=>hn("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:[s.jsx("option",{value:"always",children:i("settings.archiveMode.always")}),s.jsx("option",{value:"never",children:i("settings.archiveMode.never")}),s.jsx("option",{value:"ask",children:i("settings.archiveMode.ask")})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"When printing from File Manager, optionally create an archive entry"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Low Disk Space Warning"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"0.5",max:"100",step:"0.5",value:E.library_disk_warning_gb??5,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"GB"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Show warning when free disk space falls below this threshold"})]})]})]})]}),s.jsxs("div",{className:"space-y-6 flex-1 lg:max-w-sm",children:[s.jsx(xKe,{}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.checkForUpdatesLabel")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically check for new versions on startup"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.check_updates,onChange:oe=>hn("check_updates",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.checkPrinterFirmware")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Check for printer firmware updates from Bambu Lab"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.check_printer_firmware??!0,onChange:oe=>hn("check_printer_firmware",oe.target.checked),className:"sr-only peer"}),s.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.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.currentVersion")}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",un?.version||"..."]})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>nr(),disabled:jn,children:[jn?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),"Check now"]})]}),Yt?.update_available?s.jsxs("div",{className:"mt-4 p-3 bg-bambu-green/10 border border-bambu-green/30 rounded-lg",children:[s.jsxs("div",{className:"flex items-start justify-between",children:[s.jsxs("div",{children:[s.jsxs("p",{className:"text-bambu-green font-medium",children:["Update available: v",Yt.latest_version]}),Yt.release_name&&Yt.release_name!==Yt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:Yt.release_name})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[Yt.release_notes&&s.jsx("button",{onClick:()=>_e(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),Yt.release_url&&s.jsx("a",{href:Yt.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:i("settings.viewReleaseOnGitHub"),children:s.jsx(Kr,{className:"w-4 h-4"})})]})]}),ii?.status==="downloading"||ii?.status==="installing"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{children:ii.message})]}),s.jsx("div",{className:"mt-2 w-full bg-bambu-dark-tertiary rounded-full h-2",children:s.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${ii.progress}%`}})})]}):ii?.status==="complete"?s.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:ii.message}):ii?.status==="error"?s.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:ii.error||ii.message}):Yt?.is_docker?s.jsxs("div",{className:"mt-3 p-3 bg-bambu-dark-tertiary rounded-lg",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Update via Docker Compose:"}),s.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"})]}):s.jsxs(Te,{className:"mt-3",onClick:()=>Qu.mutate(),disabled:Qu.isPending,children:[Qu.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(yi,{className:"w-4 h-4"}),"Install Update"]})]}):Yt?.error?s.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: ",Yt.error]}):Yt&&!Yt.update_available?s.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.dataManagement")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.clearNotificationLogs")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.clearNotificationLogsDescription")})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>me(!0),children:[s.jsx(rn,{className:"w-4 h-4"}),i("common.clear")]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.resetUiPreferences")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.resetUiPreferencesDescription")})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>z(!0),children:[s.jsx(rn,{className:"w-4 h-4"}),"Reset"]})]}),s.jsxs("div",{className:"flex items-center justify-between pt-4 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Backup & Restore"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Export/import settings and configure GitHub backup"})]}),s.jsxs(Te,{variant:"secondary",size:"sm",onClick:()=>de("backup"),children:[s.jsx(Nu,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),be==="network"&&E&&s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[s.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(sh,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"The external URL where Bambuddy is accessible. Used for notification images and external integrations."}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bambuddy URL"}),s.jsx("input",{type:"text",value:E.external_url??"",onChange:oe=>hn("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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Include protocol and port (e.g., http://192.168.1.100:8000)"})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Dr,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableRetry")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Automatically retry failed FTP operations"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.ftp_retry_enabled??!0,onChange:oe=>hn("ftp_retry_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.ftp_retry_enabled&&s.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry attempts"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"1",max:"10",value:E.ftp_retry_count??3,onChange:oe=>hn("ftp_retry_count",Math.min(10,Math.max(1,parseInt(oe.target.value)||3))),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"}),s.jsx("span",{className:"text-bambu-gray",children:"times"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Number of retry attempts before giving up (1-10)"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Retry delay"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"1",max:"30",value:E.ftp_retry_delay??2,onChange:oe=>hn("ftp_retry_delay",Math.min(30,Math.max(1,parseInt(oe.target.value)||2))),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"}),s.jsx("span",{className:"text-bambu-gray",children:"seconds"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Wait time between retries (1-30)"})]})]}),s.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Connection timeout"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"10",max:"120",value:E.ftp_timeout??30,onChange:oe=>hn("ftp_timeout",Math.min(120,Math.max(10,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"}),s.jsx("span",{className:"text-bambu-gray",children:"seconds"})]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Socket timeout for slow connections. Increase for A1/A1 Mini printers with weak WiFi (10-120)"})]})]})]})]}),s.jsxs("div",{className:"flex-1 lg:max-w-xl space-y-4",children:[s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(fN,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),E.ha_enabled&&bn&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${bn.success?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${bn.success?"text-green-400":"text-red-400"}`,children:bn.success?"Connected":"Disconnected"})]})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableHomeAssistant")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.homeAssistantDescription")})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.ha_enabled??!1,onChange:oe=>hn("ha_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.ha_enabled&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Home Assistant URL"}),s.jsx("input",{type:"text",value:E.ha_url??"",onChange:oe=>hn("ha_url",oe.target.value),placeholder:"http://192.168.1.100:8123",className:"w-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.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Long-Lived Access Token"}),s.jsx("input",{type:"password",value:E.ha_token??"",onChange:oe=>hn("ha_token",oe.target.value),placeholder:"eyJ0eXAiOiJKV1QiLC...",className:"w-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.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Create a token in HA: Profile → Long-Lived Access Tokens → Create Token"})]}),E.ha_url&&E.ha_token&&s.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:s.jsxs(Te,{variant:"secondary",size:"sm",disabled:Ba,onClick:async()=>{Ae(!0),wi(null);try{const oe=await ue.testHAConnection(E.ha_url,E.ha_token);wi(oe)}catch(oe){wi({success:!1,message:null,error:oe instanceof Error?oe.message:i("common.unknownError")})}finally{Ae(!1)}},children:[Ba?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Sg,{className:"w-4 h-4"}),i("settings.testConnection")]})})]})]})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Sg,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),cr?.enabled&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${cr.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${cr.connected?"text-green-400":"text-red-400"}`,children:cr.connected?"Connected":"Disconnected"})]})]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.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."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableMqtt")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Publish events to external MQTT broker"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.mqtt_enabled??!1,onChange:oe=>hn("mqtt_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.mqtt_enabled&&s.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Broker hostname"}),s.jsx("input",{type:"text",value:E.mqtt_broker??"",onChange:oe=>hn("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"})]}),s.jsxs("div",{className:"flex items-end gap-4",children:[s.jsxs("div",{className:"flex-1",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Port"}),s.jsx("input",{type:"number",min:"1",max:"65535",value:E.mqtt_port??1883,onChange:oe=>hn("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"})]}),s.jsxs("div",{className:"flex items-center gap-3 pb-2",children:[s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.mqtt_use_tls??!1,onChange:oe=>{const wt=oe.target.checked;hn("mqtt_use_tls",wt);const Rn=E.mqtt_port??1883;wt&&Rn===1883?hn("mqtt_port",8883):!wt&&Rn===8883&&hn("mqtt_port",1883)},className:"sr-only peer"}),s.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.jsx("span",{className:"text-white text-sm",children:i("settings.useTls")})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Username (optional)"}),s.jsx("input",{type:"text",value:E.mqtt_username??"",onChange:oe=>hn("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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password (optional)"}),s.jsx("input",{type:"password",value:E.mqtt_password??"",onChange:oe=>hn("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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Topic prefix"}),s.jsx("input",{type:"text",value:E.mqtt_topic_prefix??"bambuddy",onChange:oe=>hn("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"}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Topics will be: ",E.mqtt_topic_prefix||"bambuddy","/printers//status, etc."]})]}),cr&&s.jsx("div",{className:"pt-3 mt-3 border-t border-bambu-dark-tertiary",children:s.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${cr.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:"text-bambu-gray",children:cr.connected?s.jsxs(s.Fragment,{children:[i("settings.mqttConnectedTo")," ",s.jsxs("span",{className:"text-white",children:[cr.broker,":",cr.port]})]}):i("settings.spoolmanDisconnected")})]})})]})]})]})]}),s.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(yP,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("p",{className:"text-sm text-bambu-gray",children:["Expose printer metrics at ",s.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"/api/v1/metrics"})," for Prometheus/Grafana monitoring."]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:i("settings.enableMetricsEndpoint")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.prometheusDescription")})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.prometheus_enabled??!1,onChange:oe=>hn("prometheus_enabled",oe.target.checked),className:"sr-only peer"}),s.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"})]})]}),E.prometheus_enabled&&s.jsxs("div",{className:"space-y-4 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Bearer Token (optional)"}),s.jsx("input",{type:"password",value:E.prometheus_token??"",onChange:oe=>hn("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"}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["If set, requests must include ",s.jsx("code",{className:"bg-bambu-dark px-1 rounded",children:"Authorization: Bearer "})]})]}),s.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-sm text-white mb-2",children:i("settings.availableMetrics")}),s.jsxs("div",{className:"text-xs text-bambu-gray space-y-1",children:[s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_connected"})," - Connection status"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_printer_state"})," - Printer state (idle/printing/etc)"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_print_progress"})," - Print progress 0-100%"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_bed_temp_celsius"})," - Bed temperature"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_nozzle_temp_celsius"})," - Nozzle temperature"]}),s.jsxs("p",{children:[s.jsx("code",{className:"text-orange-400",children:"bambuddy_prints_total"})," - Total prints by result"]}),s.jsx("p",{className:"text-bambu-gray/70 italic",children:"...and more (layers, fans, queue, filament usage)"})]})]})]})]})]})})]}),bn&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full mx-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[bn.success?s.jsx(Ar,{className:"w-8 h-8 text-green-400"}):s.jsx(Yi,{className:"w-8 h-8 text-red-400"}),s.jsx("h3",{className:"text-lg font-medium text-white",children:bn.success?"Connection Successful":"Connection Failed"})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:bn.success?bn.message||"Successfully connected to Home Assistant.":bn.error||"Failed to connect to Home Assistant."}),s.jsx("div",{className:"flex justify-end",children:s.jsx(Te,{variant:"primary",onClick:()=>wi(null),children:"OK"})})]})}),be==="plugs"&&s.jsxs("div",{className:"max-w-4xl",children:[s.jsxs("div",{className:"flex items-start justify-between mb-6",children:[s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(tl,{className:"w-5 h-5 text-bambu-green"}),"Smart Plugs"]}),s.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."})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-1 shrink-0",children:[Le&&Le.filter(oe=>oe.enabled).length>1&&s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>ee("on"),disabled:Vl.isPending,title:i("settings.turnAllPlugsOn"),children:[Vl.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Gu,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),s.jsxs(Te,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>ee("off"),disabled:Vl.isPending,title:i("settings.turnAllPlugsOff"),children:[Vl.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(gN,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),s.jsxs(Te,{className:"whitespace-nowrap",onClick:()=>{F(null),R(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Le&&Le.length>0&&s.jsxs(_t,{className:"mb-6",children:[s.jsx(Kn,{children:s.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[s.jsx(vh,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",St&&s.jsx(ht,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),s.jsx(Mt,{children:ut?s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(vh,{className:"w-3 h-3"}),"Current Power"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalPower.toFixed(1),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"W"})]}),s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:[ut.reachableCount,"/",ut.totalPlugs," plugs online"]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(si,{className:"w-3 h-3"}),"Today"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalToday.toFixed(2),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),E&&E.energy_cost_per_kwh>0&&s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(ut.totalToday*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(yP,{className:"w-3 h-3"}),"Yesterday"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalYesterday.toFixed(2),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),E&&E.energy_cost_per_kwh>0&&s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(ut.totalYesterday*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]}),s.jsxs("div",{className:"bg-bambu-dark rounded-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-xs mb-1",children:[s.jsx(hP,{className:"w-3 h-3"}),"Total"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[ut.totalLifetime.toFixed(1),s.jsx("span",{className:"text-sm font-normal text-bambu-gray ml-1",children:"kWh"})]}),E&&E.energy_cost_per_kwh>0&&s.jsxs("div",{className:"text-xs text-bambu-gray mt-1",children:["~",(ut.totalLifetime*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]})]}):St?null:s.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),Ce?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Le&&Le.length>0?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Le.map(oe=>s.jsx(rKe,{plug:oe,onEdit:wt=>{F(wt),R(!0)}},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(tl,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.noSmartPlugsTitle")}),s.jsx("p",{className:"text-sm mb-4",children:i("settings.noSmartPlugsDescription")}),s.jsxs(Te,{onClick:()=>{F(null),R(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addFirstSmartPlug")]})]})})})]}),be==="notifications"&&s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(wg,{className:"w-5 h-5 text-bambu-green"}),i("settings.providers")]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>ae(!0),children:[s.jsx(q0,{className:"w-4 h-4"}),i("settings.log")]}),At&&At.length>0&&s.jsxs(Te,{size:"sm",variant:"secondary",onClick:()=>{ca(null),pl.mutate()},disabled:pl.isPending,children:[pl.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(PR,{className:"w-4 h-4"}),i("settings.testAll")]}),s.jsxs(Te,{size:"sm",onClick:()=>{K(null),j(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),"Add"]})]})]}),s.jsx(_t,{className:"mb-4",children:s.jsx(Mt,{className:"py-3",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white text-sm font-medium",children:i("settings.notificationLanguage")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.notificationLanguageDescription")})]}),s.jsx("select",{value:E.notification_language||"en",onChange:oe=>hn("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:mz.map(oe=>s.jsx("option",{value:oe.code,children:oe.nativeName},oe.code))})]})})}),Cc&&s.jsx(_t,{className:"mb-4",children:s.jsxs(Mt,{className:"py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-sm font-medium text-white",children:i("settings.testResults")}),s.jsx("button",{onClick:()=>ca(null),className:"text-bambu-gray hover:text-white text-xs",children:i("common.dismiss")})]}),s.jsxs("div",{className:"flex items-center gap-4 text-sm mb-2",children:[s.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[s.jsx(Ar,{className:"w-4 h-4"}),i("settings.testPassedCount",{count:Cc.success})]}),Cc.failed>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(Yi,{className:"w-4 h-4"}),i("settings.testFailedCount",{count:Cc.failed})]})]}),Cc.results.filter(oe=>!oe.success).length>0&&s.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:Cc.results.filter(oe=>!oe.success).map(oe=>s.jsxs("div",{className:"text-xs text-red-400",children:[s.jsxs("span",{className:"font-medium",children:[oe.provider_name,":"]})," ",oe.message]},oe.provider_id))})]})}),Tt?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):At&&At.length>0?s.jsx("div",{className:"space-y-3",children:At.map(oe=>s.jsx(sKe,{provider:oe,onEdit:wt=>{K(wt),j(!0)}},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(wg,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm font-medium text-white mb-2",children:i("settings.noProvidersTitle")}),s.jsx("p",{className:"text-xs mb-3",children:i("settings.noProvidersDescription")}),s.jsxs(Te,{size:"sm",onClick:()=>{K(null),j(!0)},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addProvider")]})]})})})]}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[s.jsx(Ls,{className:"w-5 h-5 text-bambu-green"}),i("settings.messageTemplates")]}),s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:i("settings.messageTemplatesDescription")}),cn?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):dn&&dn.length>0?s.jsx("div",{className:"space-y-2",children:dn.map(oe=>s.jsx(_t,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>Q(oe),children:s.jsx(Mt,{className:"py-2.5 px-3",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"text-white font-medium text-sm truncate",children:oe.name}),s.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:oe.title_template})]}),s.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:wt=>{wt.stopPropagation(),Q(oe)},children:s.jsx(fg,{className:"w-4 h-4 text-bambu-gray"})})]})})},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(Ls,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm",children:i("settings.noTemplatesAvailable")})]})})})]})]}),be==="apikeys"&&s.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-6",children:[s.jsxs("div",{className:"flex-1",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx($o,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiKeys")]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiKeysDescription")})]}),s.jsxs(Te,{size:"sm",onClick:()=>ie(!0),className:"flex-shrink-0",children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.createKey")]})]}),G&&s.jsx(_t,{className:"mb-6 border-bambu-green",children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Ar,{className:"w-5 h-5 text-bambu-green flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"flex-1",children:[s.jsx("p",{className:"text-white font-medium mb-1",children:i("settings.apiKeyCreated")}),s.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:i("settings.apiKeyCopyWarning")}),s.jsxs("div",{className:"flex items-center gap-2 bg-bambu-dark rounded-lg p-2",children:[s.jsx("code",{className:"flex-1 text-sm text-bambu-green font-mono break-all",children:G}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(G);else{const oe=document.createElement("textarea");oe.value=G,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:s.jsx(Fl,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>{I(G),o(i("settings.toast.keyAddedToBrowser"))},children:i("settings.useInApiBrowser")}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>Y(null),children:i("common.dismiss")})]})]})]})})}),Pe&&s.jsxs(_t,{className:"mb-6",children:[s.jsx(Kn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.createNewApiKey")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keyName")}),s.jsx("input",{type:"text",value:Ne,onChange:oe=>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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("common.permissions")}),s.jsxs("div",{className:"space-y-2",children:[s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ge.can_read_status,onChange:oe=>Ke(wt=>({...wt,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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white",children:i("settings.readStatus")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.readStatusDescription")})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ge.can_queue,onChange:oe=>Ke(wt=>({...wt,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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white",children:i("settings.manageQueue")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.manageQueueDescription")})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ge.can_control_printer,onChange:oe=>Ke(wt=>({...wt,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"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-white",children:i("settings.controlPrinter")}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.controlPrinterDescription")})]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[s.jsxs(Te,{onClick:()=>Nt.mutate({name:Ne||i("settings.unnamedKey"),...ge}),disabled:Nt.isPending,children:[Nt.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(dr,{className:"w-4 h-4"}),i("settings.createKey")]}),s.jsx(Te,{variant:"secondary",onClick:()=>ie(!1),children:i("common.cancel")})]})]})]}),Pt?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Ft&&Ft.length>0?s.jsx("div",{className:"space-y-3",children:Ft.map(oe=>s.jsx(_t,{children:s.jsx(Mt,{className:"py-3",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx($o,{className:`w-5 h-5 ${oe.enabled?"text-bambu-green":"text-bambu-gray"}`}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium",children:oe.name}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[oe.key_prefix,"••••••••",oe.last_used&&` · ${i("settings.lastUsed")}: ${Bg(oe.last_used)}`]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"flex gap-1 text-xs",children:[oe.can_read_status&&s.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:i("settings.read")}),oe.can_queue&&s.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&&s.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:i("settings.control")})]}),s.jsx(Te,{variant:"secondary",size:"sm",onClick:()=>q(oe.id),children:s.jsx(rn,{className:"w-4 h-4 text-red-400"})})]})]})})},oe.id))}):s.jsx(_t,{children:s.jsx(Mt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx($o,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:i("settings.apiKeysEmptyTitle")}),s.jsx("p",{className:"text-sm mb-4",children:i("settings.apiKeysEmptyDescription")}),s.jsxs(Te,{onClick:()=>ie(!0),children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.createFirstKey")]})]})})}),s.jsxs(_t,{className:"mt-6",children:[s.jsx(Kn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:i("settings.webhookEndpoints")})}),s.jsxs(Mt,{className:"space-y-3 text-sm",children:[s.jsx("p",{className:"text-bambu-gray",children:i("settings.webhookApiKeyHint")}),s.jsxs("div",{className:"space-y-2 font-mono text-xs",children:[s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-blue-400",children:"GET"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/status"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getAllStatus")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-blue-400",children:"GET"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/status/:id"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.getSpecificStatus")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-green-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/queue"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.addToQueue")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-orange-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/pause"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.pausePrint")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-orange-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/resume"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.resumePrint")]})]}),s.jsxs("div",{className:"p-2 bg-bambu-dark rounded",children:[s.jsx("span",{className:"text-red-400",children:"POST"})," ",s.jsx("span",{className:"text-white",children:"/api/v1/webhook/printer/:id/stop"}),s.jsxs("span",{className:"text-bambu-gray",children:[" - ",i("settings.webhook.stopPrint")]})]})]})]})]})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"mb-6",children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(sh,{className:"w-5 h-5 text-bambu-green"}),i("settings.apiBrowser")]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:i("settings.apiBrowserDescription")})]}),s.jsx(_t,{className:"mb-4",children:s.jsxs(Mt,{className:"py-3",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:i("settings.apiKeyForTesting")}),s.jsx("input",{type:"text",value:te,onChange:oe=>I(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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("settings.apiKeyHint")})]})}),s.jsx(MKe,{apiKey:te})]})]}),be==="virtual-printer"&&s.jsx(bKe,{}),be==="filament"&&E&&s.jsxs("div",{className:"flex flex-col lg:flex-row gap-6 lg:gap-8",children:[s.jsx("div",{className:"flex-1 lg:max-w-xl",children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.amsDisplayThresholds")})}),s.jsxs(Mt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.amsThresholdsDescription")}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(AR,{className:"w-4 h-4 text-blue-400"}),s.jsx("span",{className:"font-medium",children:i("settings.humidity")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodGreen")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"0",max:"100",value:E.ams_humidity_good??40,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"%"})]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"0",max:"100",value:E.ams_humidity_fair??60,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"%"})]})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairBad")})]}),s.jsxs("div",{className:"space-y-3 pt-2 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(bN,{className:"w-4 h-4 text-orange-400"}),s.jsx("span",{className:"font-medium",children:i("settings.temperature")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.goodBlue")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:E.ams_temp_good??28,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[i("settings.fairOrange")," ≤"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",step:"0.5",min:"0",max:"60",value:E.ams_temp_fair??35,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:"°C"})]})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.aboveFairHot")})]}),s.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(Nu,{className:"w-4 h-4 text-purple-400"}),s.jsx("span",{className:"font-medium",children:i("settings.historyRetention")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:i("settings.keepSensorHistory")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"number",min:"1",max:"365",value:E.ams_history_retention_days??30,onChange:oe=>hn("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"}),s.jsx("span",{className:"text-bambu-gray",children:i("common.days")})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:i("settings.historyRetentionDescription")})]}),s.jsxs("div",{className:"space-y-3 pt-4 border-t border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(Ur,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"font-medium",children:i("settings.printModal")})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-white",children:i("settings.expandCustomMapping")}),s.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:i("settings.expandCustomMappingDescription")})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.per_printer_mapping_expanded??!1,onChange:oe=>hn("per_printer_mapping_expanded",oe.target.checked),className:"sr-only peer"}),s.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.jsx("div",{className:"flex-1 lg:max-w-xl",children:s.jsx(pKe,{})})]}),ce!==null&&s.jsx(Zn,{title:i("settings.deleteApiKeyTitle"),message:i("settings.deleteApiKeyMessage"),confirmText:i("settings.deleteKey"),variant:"danger",onConfirm:()=>{en.mutate(ce),q(null)},onCancel:()=>q(null)}),A&&s.jsx(iKe,{plug:U,onClose:()=>{R(!1),F(null)}}),$&&s.jsx(oKe,{provider:H,onClose:()=>{j(!1),K(null)}}),V&&s.jsx(lKe,{template:V,onClose:()=>Q(null)}),Z&&s.jsx(dKe,{onClose:()=>ae(!1)}),fe&&s.jsx(Zn,{title:i("settings.clearNotificationLogs"),message:i("settings.clearLogsMessage"),confirmText:i("settings.clearLogs"),variant:"warning",onConfirm:async()=>{me(!1);try{const oe=await ue.clearNotificationLogs(30);o(oe.message,"success")}catch{o(i("settings.toast.clearLogsFailed"),"error")}},onCancel:()=>me(!1)}),Ee&&s.jsx(Zn,{title:i("settings.resetUiPreferences"),message:i("settings.resetUiPreferencesMessage"),confirmText:i("settings.resetPreferences"),variant:"default",onConfirm:()=>{z(!1),localStorage.clear(),o(i("settings.toast.uiPreferencesReset"),"success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>z(!1)}),O&&s.jsx(Zn,{title:`Turn All Plugs ${O==="on"?"On":"Off"}`,message:`This will turn ${O==="on"?"ON":"OFF"} all ${Le?.filter(oe=>oe.enabled).length||0} enabled smart plugs. ${O==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${O==="on"?"On":"Off"}`,variant:O==="off"?"danger":"warning",onConfirm:()=>{const oe=O;ee(null),Vl.mutate(oe)},onCancel:()=>ee(null)}),le&&Yt?.release_notes&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>_e(!1),children:s.jsxs(_t,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:oe=>oe.stopPropagation(),children:[s.jsxs(Kn,{className:"flex flex-row items-center justify-between shrink-0",children:[s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white",children:["Release Notes - v",Yt.latest_version]}),Yt.release_name&&Yt.release_name!==Yt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray",children:Yt.release_name})]}),s.jsx("button",{onClick:()=>_e(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsx(Mt,{className:"overflow-y-auto flex-1",children:s.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:Yt.release_notes})}),s.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[Yt.release_url&&s.jsx("a",{href:Yt.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:s.jsxs(Te,{variant:"secondary",className:"w-full",children:[s.jsx(Kr,{className:"w-4 h-4"}),"View on GitHub"]})}),s.jsx(Te,{onClick:()=>_e(!1),className:"flex-1",children:"Close"})]})]})}),be==="users"&&s.jsxs("div",{className:"space-y-6",children:[s.jsx(_t,{children:s.jsx(Mt,{className:"py-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.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?s.jsx(nT,{className:"w-5 h-5 text-green-400"}):s.jsx(tT,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-white font-medium",children:i("settings.authentication")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:i(l?"settings.authEnabledDescription":"settings.authDisabledDescription")})]})]}),l?c?.is_admin&&s.jsxs(Te,{variant:"secondary",onClick:()=>re(!0),children:[s.jsx(tT,{className:"w-4 h-4"}),i("common.disable")]}):s.jsxs(Te,{onClick:()=>e("/setup"),children:[s.jsx(nT,{className:"w-4 h-4"}),i("common.enable")]})]})})}),l&&s.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6",children:[s.jsxs("div",{className:"space-y-6",children:[c&&s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(mg,{className:"w-5 h-5 text-bambu-green"}),i("settings.currentUser")]}),s.jsxs(Te,{size:"sm",variant:"ghost",onClick:()=>He(!0),children:[s.jsx($o,{className:"w-4 h-4"}),i("settings.changePassword")]})]})}),s.jsx(Mt,{children:s.jsx("div",{className:"flex items-center justify-between",children:s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium text-lg",children:c.username}),s.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[c.is_admin&&s.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=>s.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))]})]})})})]}),s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(mg,{className:"w-5 h-5 text-bambu-green"}),i("settings.users")]}),qt("users:create")&&s.jsxs(Te,{size:"sm",onClick:()=>{Se(!0),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addUser")]})]})}),s.jsx(Mt,{children:wn?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):yt.length===0?s.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noUsersFound")}):s.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:yt.map(oe=>s.jsxs("div",{className:"py-3 flex items-center justify-between",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("p",{className:"text-white font-medium truncate",children:oe.username}),s.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[oe.is_admin&&s.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(wt=>s.jsx("span",{className:`px-2 py-0.5 rounded-full text-xs font-medium ${wt.name==="Administrators"?"bg-purple-500/20 text-purple-300":wt.name==="Operators"?"bg-blue-500/20 text-blue-300":wt.name==="Viewers"?"bg-green-500/20 text-green-300":"bg-gray-500/20 text-gray-300"}`,children:wt.name},wt.id))]})]}),s.jsxs("div",{className:"flex items-center gap-1 ml-4",children:[qt("users:update")&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>Si(oe),children:s.jsx(fg,{className:"w-4 h-4"})}),qt("users:delete")&&oe.id!==c?.id&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>_i(oe.id),children:s.jsx(rn,{className:"w-4 h-4"})})]})]},oe.id))})})]})]}),s.jsx("div",{children:s.jsxs(_t,{children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("h3",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(rT,{className:"w-5 h-5 text-bambu-green"}),i("settings.groups")]}),qt("groups:create")&&s.jsxs(Te,{size:"sm",onClick:()=>{vn(!0),la()},children:[s.jsx(dr,{className:"w-4 h-4"}),i("settings.addGroup")]})]})}),s.jsx(Mt,{children:Yr?s.jsx("div",{className:"flex items-center justify-center py-8",children:s.jsx(ht,{className:"w-6 h-6 text-bambu-green animate-spin"})}):Fr.length===0?s.jsx("p",{className:"text-center text-bambu-gray py-8",children:i("settings.noGroupsFound")}):s.jsx("div",{className:"divide-y divide-bambu-dark-tertiary",children:Fr.map(oe=>s.jsxs("div",{className:"py-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rT,{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"}`}),s.jsx("span",{className:"text-white font-medium",children:oe.name}),oe.is_system&&s.jsx("span",{className:"px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400",children:i("settings.system")})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[qt("groups:update")&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>$h(oe),children:s.jsx(fg,{className:"w-4 h-4"})}),qt("groups:delete")&&!oe.is_system&&s.jsx(Te,{size:"sm",variant:"ghost",onClick:()=>Dn(oe.id),children:s.jsx(rn,{className:"w-4 h-4"})})]})]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1 ml-6",children:oe.description||i("settings.noDescription")}),s.jsxs("div",{className:"flex items-center gap-4 mt-2 ml-6 text-xs text-bambu-gray",children:[s.jsx("span",{children:i("settings.userCount",{count:oe.user_count})}),s.jsx("span",{children:i("settings.permissionCount",{count:oe.permissions.length})})]})]},oe.id))})})]})})]}),!l&&s.jsx(_t,{children:s.jsx(Mt,{className:"py-6",children:s.jsxs("div",{className:"text-center",children:[s.jsx(tT,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-medium text-white mb-2",children:i("settings.authDisabledTitle")}),s.jsx("p",{className:"text-sm text-bambu-gray mb-4 max-w-md mx-auto",children:i("settings.authDisabledMessage")}),s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-6 text-left max-w-xs mx-auto",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:i("settings.authDisabledFeature1")})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:i("settings.authDisabledFeature2")})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Ar,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:i("settings.authDisabledFeature3")})]})]}),s.jsxs(Te,{onClick:()=>e("/setup"),children:[s.jsx(nT,{className:"w-4 h-4"}),i("settings.enableAuthentication")]})]})})})]}),Be&&s.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(mg,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.createUser")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),s.jsx("input",{type:"text",value:ft.username,onChange:oe=>Bt({...ft,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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.password")}),s.jsx("input",{type:"password",value:ft.password,onChange:oe=>Bt({...ft,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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),s.jsx("input",{type:"password",value:ft.confirmPassword,onChange:oe=>Bt({...ft,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 ${ft.confirmPassword&&ft.password!==ft.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmPasswordPlaceholder"),autoComplete:"new-password",minLength:6}),ft.confirmPassword&&ft.password!==ft.confirmPassword&&s.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),s.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:[Fr.map(oe=>s.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ft.group_ids.includes(oe.id),onChange:()=>Ks(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"}),s.jsx("span",{className:"text-sm text-white",children:oe.name}),oe.is_system&&s.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},oe.id)),Fr.length===0&&s.jsx("p",{className:"text-sm text-bambu-gray",children:i("settings.noGroupsAvailable")})]})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{Se(!1),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),s.jsx(Te,{onClick:Mo,disabled:Ws.isPending||!ft.username||!ft.password||ft.password!==ft.confirmPassword||ft.password.length<6,children:Ws.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Creating..."]}):s.jsxs(s.Fragment,{children:[s.jsx(dr,{className:"w-4 h-4"}),"Create User"]})})]})]})]})}),Xe&&tt!==null&&s.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(fg,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.editUser")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.username")}),s.jsx("input",{type:"text",value:ft.username,onChange:oe=>Bt({...ft,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"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:["Password ",s.jsx("span",{className:"text-bambu-gray font-normal",children:"(leave blank to keep current)"})]}),s.jsx("input",{type:"password",value:ft.password,onChange:oe=>Bt({...ft,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})]}),ft.password&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.confirmPassword")}),s.jsx("input",{type:"password",value:ft.confirmPassword,onChange:oe=>Bt({...ft,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 ${ft.confirmPassword&&ft.password!==ft.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),ft.confirmPassword&&ft.password!==ft.confirmPassword&&s.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Groups"}),s.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:Fr.map(oe=>s.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ft.group_ids.includes(oe.id),onChange:()=>Ks(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"}),s.jsx("span",{className:"text-sm text-white",children:oe.name}),oe.is_system&&s.jsx("span",{className:"text-xs text-yellow-400",children:"(System)"})]},oe.id))})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{Me(!1),ke(null),Bt({username:"",password:"",confirmPassword:"",role:"user",group_ids:[]})},children:"Cancel"}),s.jsx(Te,{onClick:()=>Ms(tt),disabled:tn.isPending||!ft.username||!!(ft.password&&(ft.password!==ft.confirmPassword||ft.password.length<6)),children:tn.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Saving..."]}):s.jsxs(s.Fragment,{children:[s.jsx(hs,{className:"w-4 h-4"}),"Save Changes"]})})]})]})]})}),We!==null&&s.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",onClick:()=>{ze(null),De(null)},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center gap-2 text-red-400",children:[s.jsx(rn,{className:"w-5 h-5"}),s.jsx("h3",{className:"text-lg font-semibold",children:i("settings.deleteUserTitle")})]})}),s.jsx(Mt,{className:"space-y-4",children:Ye?s.jsx("div",{className:"flex items-center justify-center py-4",children:s.jsx("div",{className:"animate-spin rounded-full h-6 w-6 border-2 border-bambu-green border-t-transparent"})}):W&&W.archives+W.queue_items+W.library_files>0?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-white",children:i("settings.userHasCreated")}),s.jsxs("ul",{className:"list-disc list-inside text-bambu-gray space-y-1",children:[W.archives>0&&s.jsxs("li",{children:[W.archives," archive",W.archives!==1?"s":""]}),W.queue_items>0&&s.jsxs("li",{children:[W.queue_items," queue item",W.queue_items!==1?"s":""]}),W.library_files>0&&s.jsxs("li",{children:[W.library_files," library file",W.library_files!==1?"s":""]})]}),s.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.userItemsQuestion")}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Te,{variant:"danger",onClick:()=>on.mutate({id:We,deleteItems:!0}),disabled:on.isPending,className:"justify-center",children:"Delete user AND their items"}),s.jsx(Te,{variant:"secondary",onClick:()=>on.mutate({id:We,deleteItems:!1}),disabled:on.isPending,className:"justify-center",children:"Delete user, keep items (become ownerless)"}),s.jsx(Te,{variant:"ghost",onClick:()=>{ze(null),De(null)},disabled:on.isPending,className:"justify-center",children:"Cancel"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-white",children:i("settings.deleteUserConfirm")}),s.jsx("p",{className:"text-bambu-gray text-sm",children:i("settings.actionCannotBeUndone")}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx(Te,{variant:"ghost",onClick:()=>{ze(null),De(null)},disabled:on.isPending,children:"Cancel"}),s.jsx(Te,{variant:"danger",onClick:()=>on.mutate({id:We,deleteItems:!1}),disabled:on.isPending,children:"Delete User"})]})]})})]})}),(Lt||Jt)&&s.jsx("div",{className:"fixed inset-0 bg-black flex items-center justify-center z-50 p-4",onClick:()=>{vn(!1),ir(null),la()},children:s.jsxs(_t,{className:"w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(rT,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:Jt?"Edit Group":"Create Group"})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{vn(!1),ir(null),la()},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:i("settings.groupName")}),s.jsx("input",{type:"text",value:ln.name,onChange:oe=>mr({...ln,name:oe.target.value}),disabled:Jt?.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")}),Jt?.is_system&&s.jsx("p",{className:"text-xs text-yellow-400 mt-1",children:i("settings.systemGroupWarning")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Description"}),s.jsx("textarea",{value:ln.description,onChange:oe=>mr({...ln,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")})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:["Permissions (",ln.permissions.length," selected)"]}),s.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:Br?.categories.map(oe=>s.jsxs("div",{className:"border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[s.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:()=>$l(oe.name),children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",onClick:wt=>{wt.stopPropagation(),Dm(oe,!Rm(oe))},className:`w-5 h-5 rounded border flex items-center justify-center transition-colors ${Rm(oe)?"bg-bambu-green border-bambu-green":Vh(oe)?"bg-bambu-green/50 border-bambu-green":"border-bambu-gray hover:border-white"}`,children:(Rm(oe)||Vh(oe))&&s.jsx(Ia,{className:"w-3 h-3 text-white"})}),s.jsx("span",{className:"text-white font-medium",children:oe.name}),s.jsxs("span",{className:"text-xs text-bambu-gray",children:["(",oe.permissions.filter(wt=>ln.permissions.includes(wt.value)).length,"/",oe.permissions.length,")"]})]}),Fn.has(oe.name)?s.jsx(ei,{className:"w-4 h-4 text-bambu-gray"}):s.jsx(gs,{className:"w-4 h-4 text-bambu-gray"})]}),Fn.has(oe.name)&&s.jsx("div",{className:"p-3 bg-bambu-dark space-y-2",children:oe.permissions.map(wt=>s.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ln.permissions.includes(wt.value),onChange:()=>zx(wt.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"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:wt.label})]},wt.value))})]},oe.name))})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{vn(!1),ir(null),la()},children:"Cancel"}),s.jsx(Te,{onClick:Jt?Ux:Hr,disabled:Ss.isPending||_o.isPending||!ln.name.trim(),children:Ss.isPending||_o.isPending?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),Jt?"Saving...":"Creating..."]}):s.jsxs(s.Fragment,{children:[s.jsx(hs,{className:"w-4 h-4"}),Jt?"Save Changes":"Create Group"]})})]})]})]})}),fr!==null&&s.jsx(Zn,{title:i("settings.deleteGroupTitle"),message:i("settings.deleteGroupMessage"),confirmText:i("settings.deleteGroup"),variant:"danger",onConfirm:()=>{So.mutate(fr),Dn(null)},onCancel:()=>Dn(null)}),be==="backup"&&s.jsx(vKe,{}),we&&s.jsx(Zn,{title:i("settings.disableAuthenticationTitle"),message:i("settings.disableAuthenticationMessage"),confirmText:i("settings.disableAuthentication"),variant:"danger",onConfirm:async()=>{try{await ue.disableAuth(),o(i("settings.toast.authDisabled"),"success"),await u(),re(!1),window.location.href="/"}catch(oe){const wt=oe instanceof Error?oe.message:i("settings.toast.authDisableFailed");o(wt,"error")}},onCancel:()=>re(!1)}),Fe&&s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:()=>{He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:s.jsxs(_t,{className:"w-full max-w-md",onClick:oe=>oe.stopPropagation(),children:[s.jsx(Kn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($o,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.changePassword")})]}),s.jsx(Te,{variant:"ghost",size:"sm",onClick:()=>{He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:s.jsx(Rt,{className:"w-5 h-5"})})]})}),s.jsxs(Mt,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Current Password"}),s.jsx("input",{type:"password",value:Ve.currentPassword,onChange:oe=>$e({...Ve,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"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"New Password"}),s.jsx("input",{type:"password",value:Ve.newPassword,onChange:oe=>$e({...Ve,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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:"Confirm New Password"}),s.jsx("input",{type:"password",value:Ve.confirmPassword,onChange:oe=>$e({...Ve,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 ${Ve.confirmPassword&&Ve.newPassword!==Ve.confirmPassword?"border-red-500":"border-bambu-dark-tertiary"}`,placeholder:i("settings.confirmNewPassword"),autoComplete:"new-password",minLength:6}),Ve.confirmPassword&&Ve.newPassword!==Ve.confirmPassword&&s.jsx("p",{className:"text-red-400 text-xs mt-1",children:i("settings.passwordsDoNotMatch")})]})]}),s.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>{He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})},children:"Cancel"}),s.jsx(Te,{onClick:async()=>{if(Ve.newPassword!==Ve.confirmPassword){o(i("settings.toast.passwordsDoNotMatch"),"error");return}if(Ve.newPassword.length<6){o(i("settings.toast.passwordTooShort"),"error");return}je(!0);try{await ue.changePassword(Ve.currentPassword,Ve.newPassword),o(i("settings.toast.passwordChanged"),"success"),He(!1),$e({currentPassword:"",newPassword:"",confirmPassword:""})}catch(oe){const wt=oe instanceof Error?oe.message:"Failed to change password";o(wt,"error")}finally{je(!1)}},disabled:ye||!Ve.currentPassword||!Ve.newPassword||Ve.newPassword!==Ve.confirmPassword||Ve.newPassword.length<6,children:ye?s.jsxs(s.Fragment,{children:[s.jsx(ht,{className:"w-4 h-4 animate-spin"}),"Changing..."]}):s.jsxs(s.Fragment,{children:[s.jsx($o,{className:"w-4 h-4"}),"Change Password"]})})]})]})]})})]})}const Ore=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},EKe=t=>t.startsWith("HH")?"HF":"S",TKe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},uR=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 $j({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:a,note:o}){const l=EKe(t.nozzle_id),c=t.nozzle_diameter,u=()=>{r&&a?a():e()};return s.jsxs("div",{className:"flex items-center gap-2",children:[r&&s.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors p-1",children:i?s.jsx(ol,{className:"w-4 h-4 text-bambu-green"}):s.jsx(ll,{className:"w-4 h-4"})}),s.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:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-bambu-green font-mono text-sm font-bold whitespace-nowrap",children:Ore(t.k_value)}),s.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name||"Unnamed"}),o&&s.jsx("span",{title:"Has note",children:s.jsx(kW,{className:"w-3 h-3 text-yellow-500"})}),s.jsxs("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:[l," ",c]})]}),o&&s.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&&s.jsx("button",{onClick:d=>{d.stopPropagation(),n()},className:"text-bambu-gray hover:text-white transition-colors p-1",title:"Copy profile",children:s.jsx(Fl,{className:"w-4 h-4"})})]})}function Vj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],isDualNozzle:i=!1,initialNote:a="",initialNoteKey:o=null,onClose:l,onSave:c,onSaveNote:u,hasPermission:d}){const{t:f}=Hn(),{showToast:p}=$n(),[m,x]=_.useState(t?.name||""),[b,y]=_.useState(t?.k_value?Ore(t.k_value):"0.020"),[v,S]=_.useState(t?.filament_id||""),[N,T]=_.useState(t?.nozzle_id?TKe(t.nozzle_id):"HH00"),[k,C]=_.useState(t?.nozzle_diameter||n),[E,D]=_.useState(t?[t.extruder_id]:i?[0,1]:[0]),[A,R]=_.useState(!1),[U,F]=_.useState({current:0,total:0}),[$,j]=_.useState(a),H=Jr.useMemo(()=>{const X=new Map;for(const ne of r)if(ne.filament_id&&!X.has(ne.filament_id)){const se=uR(ne.name||"");X.set(ne.filament_id,{id:ne.filament_id,name:se||ne.filament_id})}return Array.from(X.values()).sort((ne,se)=>ne.name.localeCompare(se.name))},[r]),K=mt({mutationFn:X=>(console.log("[KProfile] Calling API..."),ue.setKProfile(e,X)),onSuccess:X=>{if(console.log("[KProfile] Save success:",X),p(f("kProfiles.toast.profileSaved")),u&&$!==a){let ne;$===""&&o?ne=o:t&&t.slot_id>0?ne=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:ne=`name_${m}_${v}`,u(ne,$)}R(!0),setTimeout(()=>{R(!1),c()},2500)},onError:X=>{console.error("[KProfile] Save error:",X),p(X.message,"error"),R(!1)}}),V=mt({mutationFn:X=>(console.log("[KProfile] Deleting profile..."),ue.deleteKProfile(e,X)),onSuccess:X=>{console.log("[KProfile] Delete success:",X),p(f("kProfiles.toast.profileDeleted")),R(!0),setTimeout(()=>{R(!1),l()},4e3)},onError:X=>{console.error("[KProfile] Delete error:",X),p(X.message,"error"),R(!1)}}),[Q,Z]=_.useState(!1),ae=()=>{t&&V.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})},B=async X=>{if(X.preventDefault(),i&&!t&&E.length===0){p(f("kProfiles.toast.selectAtLeastOneExtruder"),"error");return}const ne=parseFloat(b).toFixed(6),se=`${N}-${k}`;if(t||E.length===1){const xe={name:m,k_value:ne,filament_id:v,nozzle_id:se,nozzle_diameter:k,extruder_id:t?t.extruder_id:E[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",xe),K.mutate(xe);return}R(!0),F({current:1,total:E.length});const be=E.map(xe=>({name:m,k_value:ne,filament_id:v,nozzle_id:se,nozzle_diameter:k,extruder_id:xe,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${be.length} profiles in batch:`,be);try{if(await ue.setKProfilesBatch(e,be),p(f("kProfiles.toast.profilesSaved",{count:E.length})),u&&$){const xe=`name_${m}_${v}`;u(xe,$)}}catch(xe){console.error("[KProfile] Failed to save batch:",xe),p(f("kProfiles.toast.failedToSaveBatch"),"error"),R(!1),F({current:0,total:0});return}F({current:E.length,total:E.length}),setTimeout(()=>{R(!1),F({current:0,total:0}),c()},3e3)};return s.jsxs("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:[s.jsxs(_t,{className:"w-full max-w-md relative",children:[A&&s.jsxs("div",{className:"absolute inset-0 bg-bambu-dark-secondary/90 flex flex-col items-center justify-center z-10 rounded-lg",children:[s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:U.total>1?f("kProfiles.modal.savingExtruder",{current:U.current,total:U.total}):f("kProfiles.modal.syncing")}),s.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:f("kProfiles.modal.pleaseWait")})]}),s.jsxs(Mt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary",children:[s.jsx("h2",{className:"text-xl font-semibold text-white",children:f(t?"kProfiles.modal.editTitle":"kProfiles.modal.addTitle")}),s.jsx("button",{onClick:l,className:"text-bambu-gray hover:text-white transition-colors",disabled:A,children:s.jsx(Rt,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:B,className:"p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.profileName")}),s.jsx("input",{type:"text",value:m,onChange:X=>x(X.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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.kValue")}),s.jsx("input",{type:"text",inputMode:"decimal",value:b,onChange:X=>{const ne=X.target.value;(ne===""||/^\d*\.?\d*$/.test(ne))&&y(ne)},onBlur:X=>{const ne=parseFloat(X.target.value);isNaN(ne)||y((Math.trunc(ne*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}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.kValueHelp")})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.filament")}),s.jsxs("select",{value:v,onChange:X=>{const ne=X.target.value;if(S(ne),!t&&ne&&!m){const se=H.find(be=>be.id===ne);se&&x(`${N==="HH00"?"HF":"S"} ${se.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:[s.jsx("option",{value:"",children:f("kProfiles.modal.selectFilament")}),t?.filament_id&&s.jsx("option",{value:t.filament_id,children:H.find(X=>X.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&H.map(X=>s.jsx("option",{value:X.id,children:X.name},X.id))]}),!t&&H.length===0&&s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.noFilamentsHelp")})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.flowType")}),s.jsxs("select",{value:N,onChange:X=>{const ne=X.target.value;if(T(ne),!t&&v&&!m){const se=H.find(be=>be.id===v);se&&x(`${ne==="HS00"?"HF":"S"} ${se.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:[s.jsx("option",{value:"HH00",children:f("kProfiles.modal.highFlow")}),s.jsx("option",{value:"HS00",children:f("kProfiles.modal.standard")})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.nozzleSize")}),s.jsxs("select",{value:k,onChange:X=>C(X.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:[s.jsx("option",{value:"0.2",children:"0.2mm"}),s.jsx("option",{value:"0.4",children:"0.4mm"}),s.jsx("option",{value:"0.6",children:"0.6mm"}),s.jsx("option",{value:"0.8",children:"0.8mm"})]})]})]}),i&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f(t?"kProfiles.modal.extruder":"kProfiles.modal.extruders")}),t?s.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")}):s.jsxs("div",{className:"flex gap-4",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.includes(1),onChange:X=>{X.target.checked?D([...E,1]):D(E.filter(ne=>ne!==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"}),s.jsx("span",{className:"text-white",children:f("kProfiles.modal.left")})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.includes(0),onChange:X=>{X.target.checked?D([...E,0]):D(E.filter(ne=>ne!==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"}),s.jsx("span",{className:"text-white",children:f("kProfiles.modal.right")})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:f("kProfiles.modal.notes")}),s.jsx("textarea",{value:$,onChange:X=>j(X.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"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:f("kProfiles.modal.notesHelp")})]}),s.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&s.jsx(Te,{type:"button",variant:"secondary",onClick:()=>Z(!0),disabled:V.isPending||A||!d("kprofiles:delete"),title:d("kprofiles:delete")?void 0:f("kProfiles.permission.noDelete"),className:"text-red-500 hover:bg-red-500/10",children:V.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"})}),s.jsx(Te,{type:"button",variant:"secondary",onClick:l,disabled:A,className:"flex-1",children:f("common.cancel")}),s.jsxs(Te,{type:"submit",disabled:K.isPending||A||!d(t?"kprofiles:update":"kprofiles:create"),title:d(t?"kprofiles:update":"kprofiles:create")?void 0:f(t?"kProfiles.permission.noUpdate":"kProfiles.permission.noCreate"),className:"flex-1",children:[K.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(dN,{className:"w-4 h-4"}),f("common.save")]})]})]})]})]}),Q&&s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:s.jsx(_t,{className:"w-full max-w-sm",children:s.jsxs(Mt,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:s.jsx(rn,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:f("kProfiles.deleteConfirm.title")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:f("kProfiles.deleteConfirm.cannotUndo")})]})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:f("kProfiles.deleteConfirm.message",{name:t?.name})}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>Z(!1),className:"flex-1",children:f("common.cancel")}),s.jsxs(Te,{onClick:()=>{Z(!1),ae()},disabled:V.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[V.isPending?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"}),f("common.delete")]})]})]})})})]})}const h1={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function AKe(){const{t}=Hn(),{showToast:e}=$n(),{hasPermission:n}=Ai(),[r,i]=_.useState(null),[a,o]=_.useState(()=>localStorage.getItem(h1.NOZZLE_DIAMETER)||"0.4"),[l,c]=_.useState(null),[u,d]=_.useState(!1),[f,p]=_.useState(null),[m,x]=_.useState(""),[b,y]=_.useState("all"),[v,S]=_.useState("all"),[N,T]=_.useState(()=>localStorage.getItem(h1.SORT_OPTION)||"name"),[k,C]=_.useState(!1),[E,D]=_.useState(new Set),[A,R]=_.useState(!1),[U,F]=_.useState(!1),$=_.useCallback(I=>`${I.slot_id}_${I.extruder_id}`,[]);_.useEffect(()=>{localStorage.setItem(h1.NOZZLE_DIAMETER,a)},[a]),_.useEffect(()=>{localStorage.setItem(h1.SORT_OPTION,N)},[N]);const{data:j,isLoading:H}=at({queryKey:["printers"],queryFn:ue.getPrinters}),{data:K,isLoading:V,isFetching:Q,error:Z,refetch:ae}=at({queryKey:["kprofiles",r,a],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",r,"nozzle",a);const I=await ue.getKProfiles(r,a);return console.log("[KProfiles] Received profiles:",I?.profiles?.length||0,"profiles"),I},enabled:!!r,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:B}=at({queryKey:["kprofiles",r,"0.4"],queryFn:()=>ue.getKProfiles(r,"0.4"),enabled:!!r,staleTime:6e4}),{data:X,refetch:ne}=at({queryKey:["kprofile-notes",r],queryFn:()=>ue.getKProfileNotes(r),enabled:!!r,staleTime:3e4}),se=Z?.message?.includes("not connected");_.useEffect(()=>{if(!r&&j&&j.length>0){const I=j.find(fe=>fe.is_active);I&&i(I.id)}},[r,j]),_.useEffect(()=>{if(r){const I=setTimeout(()=>{ae()},150);return()=>clearTimeout(I)}},[r,a]);const be=j?.filter(I=>I.is_active)||[],xe=Jr.useMemo(()=>K?.profiles?K.profiles.filter(fe=>{const me=m.toLowerCase(),Ee=!me||fe.name.toLowerCase().includes(me)||fe.filament_id.toLowerCase().includes(me),z=b==="all"||b==="left"&&fe.extruder_id===1||b==="right"&&fe.extruder_id===0,O=v==="all"||v==="hf"&&fe.nozzle_id.startsWith("HH")||v==="s"&&fe.nozzle_id.startsWith("HS");return Ee&&z&&O}).sort((fe,me)=>{switch(N){case"k_value":return parseFloat(fe.k_value)-parseFloat(me.k_value);case"filament":return uR(fe.name).localeCompare(uR(me.name));case"name":default:return fe.name.localeCompare(me.name)}}):[],[K?.profiles,m,b,v,N]),de=j?.find(I=>I.id===r),Pe=de?.nozzle_count===2;_.useEffect(()=>{const I=fe=>{fe.target instanceof HTMLInputElement||fe.target instanceof HTMLTextAreaElement||fe.target instanceof HTMLSelectElement||l||u||f||(fe.key==="r"||fe.key==="R"?(fe.preventDefault(),ae()):fe.key==="n"||fe.key==="N"?(fe.preventDefault(),d(!0)):fe.key==="Escape"&&k&&(fe.preventDefault(),C(!1),D(new Set)))};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[l,u,f,k,ae]);const ie=_.useCallback(()=>{if(!K?.profiles||K.profiles.length===0){e(t("kProfiles.toast.noProfilesToExport"),"error");return}const I={version:1,exported_at:new Date().toISOString(),printer:de?.name||"Unknown",nozzle_diameter:a,profiles:K.profiles.map(z=>({name:z.name,k_value:z.k_value,filament_id:z.filament_id,nozzle_id:z.nozzle_id,nozzle_diameter:z.nozzle_diameter,extruder_id:z.extruder_id}))},fe=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),me=URL.createObjectURL(fe),Ee=document.createElement("a");Ee.href=me,Ee.download=`kprofiles_${de?.name||"printer"}_${a}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(Ee),Ee.click(),document.body.removeChild(Ee),URL.revokeObjectURL(me),e(t("kProfiles.toast.exportedProfiles",{count:K.profiles.length}))},[K?.profiles,de,a,e,t]),Ne=_.useCallback(()=>{const I=document.createElement("input");I.type="file",I.accept=".json",I.onchange=async fe=>{const me=fe.target.files?.[0];if(me)try{const Ee=await me.text(),z=JSON.parse(Ee);if(!z.profiles||!Array.isArray(z.profiles)){e(t("kProfiles.toast.invalidFileFormat"),"error");return}let O=0;for(const ee of z.profiles)if(!(!ee.name||!ee.k_value||!ee.filament_id))try{await ue.setKProfile(r,{name:ee.name,k_value:parseFloat(ee.k_value).toFixed(6),filament_id:ee.filament_id,nozzle_id:ee.nozzle_id||`HH00-${a}`,nozzle_diameter:ee.nozzle_diameter||a,extruder_id:ee.extruder_id??0,slot_id:0}),O++,await new Promise(le=>setTimeout(le,500))}catch(le){console.error("Failed to import profile:",ee.name,le)}e(t("kProfiles.toast.importedProfiles",{count:O,total:z.profiles.length})),ae()}catch(Ee){console.error("Import error:",Ee),e(t("kProfiles.toast.failedToParseImport"),"error")}},I.click()},[r,a,e,ae,t]),Oe=_.useCallback(I=>{D(fe=>{const me=new Set(fe);return me.has(I)?me.delete(I):me.add(I),me})},[]),ge=_.useCallback(()=>{D(new Set(xe.map(I=>$(I))))},[xe,$]),Ke=_.useCallback(()=>{E.size!==0&&R(!0)},[E.size]),G=_.useCallback(async()=>{const I=xe.filter(me=>E.has($(me)));F(!0);let fe=0;for(const me of I)try{await ue.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}),fe++,await new Promise(Ee=>setTimeout(Ee,300))}catch(Ee){console.error("Failed to delete profile:",me.name,Ee)}e(t("kProfiles.toast.profilesDeleted",{count:fe})),F(!1),R(!1),C(!1),D(new Set),ae()},[r,E,xe,e,ae,$,t]),Y=_.useCallback(I=>{const fe=[];return I.setting_id&&fe.push(I.setting_id),fe.push(`slot_${I.slot_id}_${I.filament_id}_${I.extruder_id}`),fe.push(`name_${I.name}_${I.filament_id}`),fe},[]),ce=_.useCallback(async(I,fe)=>{if(r)try{await ue.setKProfileNote(r,I,fe),ne()}catch(me){console.error("Failed to save note:",me),e(t("kProfiles.toast.failedToSaveNote"),"error")}},[r,ne,e,t]),q=_.useCallback(I=>{if(!X?.notes)return{note:"",key:null};const fe=Y(I);for(const me of fe)if(X.notes[me])return{note:X.notes[me],key:me};return{note:"",key:null}},[X,Y]),te=_.useCallback(I=>q(I).note,[q]);return H?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!j||j.length===0?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(Hi,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noPrintersConfigured")}),s.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.addPrinterInSettings")})]})}):be.length===0?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(Ur,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noActivePrinters")}),s.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.enablePrinterConnection")})]})}):s.jsxs(s.Fragment,{children:[Q&&!V&&s.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[s.jsx(ht,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:t("kProfiles.loadingProfiles")})]}),s.jsxs("div",{className:"flex flex-wrap gap-4 mb-6",children:[s.jsxs("div",{className:"flex-1 min-w-48",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.printer")}),s.jsx("select",{value:r||"",onChange:I=>i(parseInt(I.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:be.map(I=>s.jsx("option",{value:I.id,children:I.name},I.id))})]}),s.jsxs("div",{className:"w-32",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("kProfiles.nozzle")}),s.jsxs("select",{value:a,onChange:I=>o(I.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:[s.jsx("option",{value:"0.2",children:"0.2mm"}),s.jsx("option",{value:"0.4",children:"0.4mm"}),s.jsx("option",{value:"0.6",children:"0.6mm"}),s.jsx("option",{value:"0.8",children:"0.8mm"})]})]}),s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsxs(Te,{variant:"secondary",onClick:()=>ae(),disabled:Q||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noRead"),children:[s.jsx(Dr,{className:`w-4 h-4 ${Q?"animate-spin":""}`}),t("kProfiles.refresh")]}),s.jsxs(Te,{onClick:()=>d(!0),disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noCreate"),children:[s.jsx(dr,{className:"w-4 h-4"}),t("kProfiles.addProfile")]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-4 mb-4",children:[s.jsxs("div",{className:"flex-1 min-w-48 relative",children:[s.jsx(ba,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),s.jsx("input",{type:"text",value:m,onChange:I=>x(I.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"})]}),Pe&&s.jsx("div",{className:"w-36",children:s.jsxs("select",{value:b,onChange:I=>y(I.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:[s.jsx("option",{value:"all",children:t("kProfiles.allExtruders")}),s.jsx("option",{value:"left",children:t("kProfiles.leftOnly")}),s.jsx("option",{value:"right",children:t("kProfiles.rightOnly")})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:v,onChange:I=>S(I.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:[s.jsx("option",{value:"all",children:t("kProfiles.allFlow")}),s.jsx("option",{value:"hf",children:t("kProfiles.hfOnly")}),s.jsx("option",{value:"s",children:t("kProfiles.sOnly")})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:N,onChange:I=>T(I.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:[s.jsx("option",{value:"name",children:t("kProfiles.sortName")}),s.jsx("option",{value:"k_value",children:t("kProfiles.sortKValue")}),s.jsx("option",{value:"filament",children:t("kProfiles.sortFilament")})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[s.jsxs(Te,{variant:"secondary",onClick:ie,disabled:!K?.profiles?.length||!n("kprofiles:read"),title:n("kprofiles:read")?void 0:t("kProfiles.permission.noExport"),children:[s.jsx(yi,{className:"w-4 h-4"}),t("kProfiles.export")]}),s.jsxs(Te,{variant:"secondary",onClick:Ne,disabled:!n("kprofiles:create"),title:n("kprofiles:create")?void 0:t("kProfiles.permission.noImport"),children:[s.jsx(Ua,{className:"w-4 h-4"}),t("kProfiles.import")]}),s.jsx("div",{className:"flex-1"}),k?s.jsxs(s.Fragment,{children:[s.jsxs(Te,{variant:"secondary",onClick:ge,children:[s.jsx(ol,{className:"w-4 h-4"}),t("kProfiles.selectAll")]}),s.jsxs(Te,{variant:"secondary",onClick:Ke,disabled:E.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:[s.jsx(rn,{className:"w-4 h-4"}),t("kProfiles.delete")," (",E.size,")"]}),s.jsxs(Te,{variant:"secondary",onClick:()=>{C(!1),D(new Set)},children:[s.jsx(Rt,{className:"w-4 h-4"}),t("common.cancel")]})]}):s.jsxs(Te,{variant:"secondary",onClick:()=>C(!0),disabled:!xe.length||!n("kprofiles:delete"),title:n("kprofiles:delete")?void 0:t("kProfiles.permission.noDelete"),children:[s.jsx(ol,{className:"w-4 h-4"}),t("kProfiles.select")]})]}),V?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ht,{className:"w-8 h-8 text-bambu-green animate-spin"})}):se?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(sm,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.printerOffline")}),s.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.printerOfflineDesc")}),s.jsxs(Te,{variant:"secondary",onClick:()=>ae(),children:[s.jsx(Dr,{className:"w-4 h-4"}),t("common.refresh")]})]})}):xe.length>0?Pe?s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.leftExtruder")}),s.jsx("div",{className:"space-y-1",children:xe.filter(I=>I.extruder_id===1).map(I=>s.jsx($j,{profile:I,onEdit:()=>c(I),onCopy:()=>p(I),selectionMode:k,isSelected:E.has($(I)),onToggleSelect:()=>Oe($(I)),note:te(I)},$(I)))})]}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:t("kProfiles.rightExtruder")}),s.jsx("div",{className:"space-y-1",children:xe.filter(I=>I.extruder_id===0).map(I=>s.jsx($j,{profile:I,onEdit:()=>c(I),onCopy:()=>p(I),selectionMode:k,isSelected:E.has($(I)),onToggleSelect:()=>Oe($(I)),note:te(I)},$(I)))})]})]}):s.jsx("div",{className:"space-y-1",children:xe.map(I=>s.jsx($j,{profile:I,onEdit:()=>c(I),onCopy:()=>p(I),selectionMode:k,isSelected:E.has($(I)),onToggleSelect:()=>Oe($(I)),note:te(I)},$(I)))}):m||b!=="all"||v!=="all"?s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(ba,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noMatchingProfiles")}),s.jsx("p",{className:"text-bambu-gray",children:t("kProfiles.noMatchingProfilesDesc")})]})}):s.jsx(_t,{children:s.jsxs(Mt,{className:"py-12 text-center",children:[s.jsx(dN,{className:"w-12 h-12 text-bambu-gray mx-auto mb-4"}),s.jsx("h3",{className:"text-lg font-semibold text-white mb-2",children:t("kProfiles.noKProfiles")}),s.jsx("p",{className:"text-bambu-gray mb-4",children:t("kProfiles.noKProfilesDesc",{diameter:a})}),s.jsxs(Te,{onClick:()=>d(!0),children:[s.jsx(dr,{className:"w-4 h-4"}),t("kProfiles.createFirstProfile")]})]})}),l&&r&&(()=>{const{note:I,key:fe}=q(l);return s.jsx(Vj,{profile:l,printerId:r,nozzleDiameter:a,existingProfiles:B?.profiles||K?.profiles,isDualNozzle:Pe,initialNote:I,initialNoteKey:fe,onSaveNote:ce,hasPermission:n,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),c(null),ae()},onSave:()=>{c(null),ae()}})})(),u&&r&&s.jsx(Vj,{printerId:r,nozzleDiameter:a,existingProfiles:B?.profiles||K?.profiles,isDualNozzle:Pe,onSaveNote:ce,hasPermission:n,onClose:()=>{d(!1),ae()},onSave:()=>{d(!1),ae()}}),f&&r&&s.jsx(Vj,{printerId:r,nozzleDiameter:a,existingProfiles:B?.profiles||K?.profiles,isDualNozzle:Pe,onSaveNote:ce,hasPermission:n,profile:{...f,slot_id:0,name:`${f.name} (Copy)`},onClose:()=>{p(null),ae()},onSave:()=>{p(null),ae()}}),A&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(_t,{className:"w-full max-w-sm",children:s.jsxs(Mt,{className:"p-6",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center",children:s.jsx(rn,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:t("kProfiles.bulkDelete.title")}),s.jsx("p",{className:"text-sm text-bambu-gray",children:t("kProfiles.bulkDelete.cannotUndo")})]})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:t("kProfiles.bulkDelete.message",{count:E.size})}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Te,{variant:"secondary",onClick:()=>R(!1),disabled:U,className:"flex-1",children:t("common.cancel")}),s.jsxs(Te,{onClick:G,disabled:U,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[U?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(rn,{className:"w-4 h-4"}),t("common.delete")]})]})]})})})]})}function cF(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,a=n.match(/(\d+\.?\d*)\s*(?:mm\s*)?nozzle|nozzle\s*(\d+\.?\d*)/i),o=a?(a[1]||a[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 Ry(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function CKe(t,e){const n=Ii(t);if(!n)return"";const i=new Date().getTime()-n.getTime(),a=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return a<1?e("profiles.time.justNow"):a<60?e("profiles.time.minsAgo",{count:a}):o<24?e("profiles.time.hoursAgo",{count:o}):l<7?e("profiles.time.daysAgo",{count:l}):n.toLocaleDateString()}function jKe({onSuccess:t,t:e}){const{showToast:n}=$n(),[r,i]=_.useState("email"),[a,o]=_.useState(""),[l,c]=_.useState(""),[u,d]=_.useState(""),[f,p]=_.useState(""),[m,x]=_.useState("global"),[b,y]=_.useState(null),[v,S]=_.useState(null),N=mt({mutationFn:()=>ue.cloudLogin(a,l,m),onSuccess:D=>{D.success?(n(e("profiles.login.toast.loggedIn")),t()):D.needs_verification?(y(D.verification_type||"email"),S(D.tfa_key||null),D.verification_type==="totp"?n(e("profiles.login.toast.enterTotp")):n(e("profiles.login.toast.codeSent")),i("code")):n(D.message,"error")},onError:D=>n(D.message,"error")}),T=mt({mutationFn:()=>ue.cloudVerify(a,u,v||void 0),onSuccess:D=>{D.success?(n(e("profiles.login.toast.loggedIn")),t()):n(D.message,"error")},onError:D=>n(D.message,"error")}),k=mt({mutationFn:()=>ue.cloudSetToken(f),onSuccess:()=>{n(e("profiles.login.toast.tokenSet")),t()},onError:D=>n(D.message,"error")}),C=D=>{D.preventDefault(),r==="email"?N.mutate():r==="code"?T.mutate():r==="token"&&k.mutate()},E=N.isPending||T.isPending||k.isPending;return s.jsx(_t,{className:"max-w-md mx-auto",children:s.jsxs(Mt,{children:[s.jsxs("div",{className:"text-center mb-6",children:[s.jsx("div",{className:"inline-flex items-center justify-center w-12 h-12 rounded-xl bg-bambu-green/20 mb-3",children:s.jsx(oN,{className:"w-6 h-6 text-bambu-green"})}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:e("profiles.login.title")}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:e("profiles.login.subtitle")})]}),s.jsxs("form",{onSubmit:C,className:"space-y-4",children:[r==="email"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.email")}),s.jsx("input",{type:"email",value:a,onChange:D=>o(D.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray-dark focus:border-bambu-green focus:outline-none",placeholder:"your@email.com",required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.password")}),s.jsx("input",{type:"password",value:l,onChange:D=>c(D.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})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.region")}),s.jsxs("select",{value:m,onChange:D=>x(D.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[s.jsx("option",{value:"global",children:e("profiles.login.regionGlobal")}),s.jsx("option",{value:"china",children:e("profiles.login.regionChina")})]})]})]}),r==="code"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e(b==="totp"?"profiles.login.totpCode":"profiles.login.verificationCode")}),s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:b==="totp"?e("profiles.login.enterTotpHint"):e("profiles.login.checkEmail",{email:a})}),s.jsx("input",{type:"text",value:u,onChange:D=>d(D.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"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:e("profiles.login.accessToken")}),s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:e("profiles.login.accessTokenHint")}),s.jsx("textarea",{value:f,onChange:D=>p(D.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})]}),s.jsxs("div",{className:"flex gap-2",children:[r==="code"&&s.jsx(Te,{type:"button",variant:"secondary",onClick:()=>i("email"),className:"flex-1",children:e("profiles.login.back")}),s.jsxs(Te,{type:"submit",disabled:E,className:"flex-1",children:[E?s.jsx(ht,{className:"w-4 h-4 animate-spin"}):s.jsx(Dz,{className:"w-4 h-4"}),e(r==="email"?"profiles.login.loginButton":r==="code"?"profiles.login.verifyButton":"profiles.login.setTokenButton")]})]}),r==="email"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>i("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx($o,{className:"w-4 h-4"}),e("profiles.login.useToken")]})}),r==="token"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>i("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx(Dz,{className:"w-4 h-4"}),e("profiles.login.useEmail")]})})]})]})})}function rg({label:t,value:e,options:n,onChange:r}){const[i,a]=_.useState(!1),o=n.find(l=>l.value===e);return s.jsxs("div",{className:"relative",children:[s.jsxs("button",{onClick:()=>a(!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:[s.jsxs("span",{className:"text-bambu-gray",children:[t,":"]}),s.jsx("span",{children:o?.label||"All"}),s.jsx(ei,{className:`w-4 h-4 text-bambu-gray transition-transform ${i?"rotate-180":""}`})]}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>a(!1)}),s.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=>s.jsxs("button",{onClick:()=>{r(l.value),a(!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:[s.jsx("span",{children:l.label}),l.count!==void 0&&s.jsx("span",{className:"text-bambu-gray text-xs",children:l.count})]},l.value))})]})]})}function PKe(){const[t,e]=_.useState(!1);_.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?s.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:s.jsx(Ig,{className:"w-5 h-5"})}):null}function Gj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:a,compareDisabled:o,t:l}){const c=cF(t.name),u=Ry(t.setting_id);return s.jsxs("div",{className:"flex items-center gap-2 group",children:[s.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:s.jsxs("div",{className:"flex items-center gap-2",children:[i&&a!==void 0&&s.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:a+1}),!i&&u&&s.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:l("profiles.presets.myPreset")}),s.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),c.filamentType&&t.type==="filament"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.filamentType}),c.layerHeight&&t.type==="process"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.layerHeight}),c.printer&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:c.printer})]})}),s.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:s.jsx(Fl,{className:"w-4 h-4"})})]})}function dR(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(` `);if(i.length>1)return`""" diff --git a/static/index.html b/static/index.html index 939a9d629..52946efeb 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +