From 140087eeb74b04350b728c284711721fcd5786e3 Mon Sep 17 00:00:00 2001 From: maziggy Date: Fri, 30 Jan 2026 17:18:22 +0100 Subject: [PATCH] Make MQTT JSON path optional for smart plug monitoring (#173) - Path is now optional for power, energy, and state topics - When path is empty, raw MQTT payload value is used directly - Energy and state topics no longer fall back to power topic - Added helper text in UI explaining path is optional - Fixes energy monitoring not working with separate topics Closes 173 --- backend/app/api/routes/smart_plugs.py | 57 +++++++------------ backend/app/schemas/smart_plug.py | 14 ++--- backend/app/services/mqtt_smart_plug.py | 29 ++++++---- .../tests/integration/test_smart_plugs_api.py | 20 ++++--- frontend/src/components/AddSmartPlugModal.tsx | 19 ++++--- .../{index-Cry_KMOA.js => index-C7_2Jo_p.js} | 2 +- static/index.html | 2 +- 7 files changed, 68 insertions(+), 75 deletions(-) rename static/assets/{index-Cry_KMOA.js => index-C7_2Jo_p.js} (92%) diff --git a/backend/app/api/routes/smart_plugs.py b/backend/app/api/routes/smart_plugs.py index 42c915347..310ec2c80 100644 --- a/backend/app/api/routes/smart_plugs.py +++ b/backend/app/api/routes/smart_plugs.py @@ -100,39 +100,27 @@ async def create_smart_plug( if plug.plug_type == "mqtt": # Determine effective topics (new fields take priority, fall back to legacy) power_topic = plug.mqtt_power_topic or plug.mqtt_topic - energy_topic = plug.mqtt_energy_topic or plug.mqtt_topic - state_topic = plug.mqtt_state_topic or plug.mqtt_topic + energy_topic = plug.mqtt_energy_topic + state_topic = plug.mqtt_state_topic - # Only subscribe if at least one data source is configured - if ( - (power_topic and plug.mqtt_power_path) - or (energy_topic and plug.mqtt_energy_path) - or (state_topic and plug.mqtt_state_path) - ): + # Only subscribe if at least one topic is configured + if power_topic or energy_topic or state_topic: mqtt_relay.smart_plug_service.subscribe( plug_id=plug.id, - # Power source - power_topic=power_topic if plug.mqtt_power_path else None, + # Power source (path is optional) + power_topic=power_topic, power_path=plug.mqtt_power_path, power_multiplier=plug.mqtt_power_multiplier or plug.mqtt_multiplier or 1.0, - # Energy source - energy_topic=energy_topic if plug.mqtt_energy_path else None, + # Energy source (path is optional) + energy_topic=energy_topic, energy_path=plug.mqtt_energy_path, energy_multiplier=plug.mqtt_energy_multiplier or plug.mqtt_multiplier or 1.0, - # State source - state_topic=state_topic if plug.mqtt_state_path else None, + # State source (path is optional) + state_topic=state_topic, state_path=plug.mqtt_state_path, state_on_value=plug.mqtt_state_on_value, ) - topics = [ - t - for t in [ - power_topic if plug.mqtt_power_path else None, - energy_topic if plug.mqtt_energy_path else None, - state_topic if plug.mqtt_state_path else None, - ] - if t - ] + topics = [t for t in [power_topic, energy_topic, state_topic] if t] logger.info(f"Created MQTT plug '{plug.name}' subscribed to {', '.join(set(topics))}") elif plug.plug_type == "homeassistant": logger.info(f"Created Home Assistant plug '{plug.name}' ({plug.ha_entity_id})") @@ -412,26 +400,23 @@ async def update_smart_plug( # Subscribe to new topics power_topic = plug.mqtt_power_topic or plug.mqtt_topic - energy_topic = plug.mqtt_energy_topic or plug.mqtt_topic - state_topic = plug.mqtt_state_topic or plug.mqtt_topic + energy_topic = plug.mqtt_energy_topic + state_topic = plug.mqtt_state_topic - if ( - (power_topic and plug.mqtt_power_path) - or (energy_topic and plug.mqtt_energy_path) - or (state_topic and plug.mqtt_state_path) - ): + # Only subscribe if at least one topic is configured + if power_topic or energy_topic or state_topic: mqtt_relay.smart_plug_service.subscribe( plug_id=plug.id, - # Power source - power_topic=power_topic if plug.mqtt_power_path else None, + # Power source (path is optional) + power_topic=power_topic, power_path=plug.mqtt_power_path, power_multiplier=plug.mqtt_power_multiplier or plug.mqtt_multiplier or 1.0, - # Energy source - energy_topic=energy_topic if plug.mqtt_energy_path else None, + # Energy source (path is optional) + energy_topic=energy_topic, energy_path=plug.mqtt_energy_path, energy_multiplier=plug.mqtt_energy_multiplier or plug.mqtt_multiplier or 1.0, - # State source - state_topic=state_topic if plug.mqtt_state_path else None, + # State source (path is optional) + state_topic=state_topic, state_path=plug.mqtt_state_path, state_on_value=plug.mqtt_state_on_value, ) diff --git a/backend/app/schemas/smart_plug.py b/backend/app/schemas/smart_plug.py index edb8a1210..1b834165c 100644 --- a/backend/app/schemas/smart_plug.py +++ b/backend/app/schemas/smart_plug.py @@ -71,16 +71,14 @@ class SmartPlugBase(BaseModel): if self.plug_type == "mqtt": # Determine the effective power topic (new field takes priority, fall back to legacy) power_topic = self.mqtt_power_topic or self.mqtt_topic - has_power = power_topic and self.mqtt_power_path - has_energy = self.mqtt_energy_topic and self.mqtt_energy_path - has_state = self.mqtt_state_topic and self.mqtt_state_path + # Path is optional - if not set, raw MQTT payload value will be used + has_power = bool(power_topic) + has_energy = bool(self.mqtt_energy_topic) + has_state = bool(self.mqtt_state_topic) - # At least one data source must be fully configured + # At least one data source must be configured (path is optional) if not has_power and not has_energy and not has_state: - raise ValueError( - "At least one MQTT data source must be configured: " - "power (topic + path), energy (topic + path), or state (topic + path)" - ) + raise ValueError("At least one MQTT topic must be configured for power, energy, or state monitoring") return self diff --git a/backend/app/services/mqtt_smart_plug.py b/backend/app/services/mqtt_smart_plug.py index dfc7fbba0..2ed44ce33 100644 --- a/backend/app/services/mqtt_smart_plug.py +++ b/backend/app/services/mqtt_smart_plug.py @@ -235,12 +235,17 @@ class MQTTSmartPlugService: if not config: continue - # Extract value using path (or use raw payload if no path or not JSON) + # Extract value using path (or use raw payload if no path) if is_json and config.path: raw_value = self._extract_json_path(payload, config.path) elif is_json and not config.path: - # JSON but no path - use the whole payload (shouldn't happen normally) - raw_value = payload + # JSON but no path - if it's a simple value use it, otherwise skip + if isinstance(payload, (int, float, str, bool)): + raw_value = payload + else: + # Can't use a dict/list as a value + logger.debug(f"MQTT plug {plug_id}: JSON payload is object/array but no path configured") + continue else: # Raw value (non-JSON) raw_value = payload @@ -361,31 +366,31 @@ class MQTTSmartPlugService: effective_power_mult = power_multiplier if power_multiplier != 1.0 else multiplier effective_energy_mult = energy_multiplier if energy_multiplier != 1.0 else multiplier - # Configure power subscription - if effective_power_topic and power_path: + # Configure power subscription (path is optional - empty means use raw payload) + if effective_power_topic: config = MQTTDataSourceConfig( topic=effective_power_topic, - path=power_path, + path=power_path or "", multiplier=effective_power_mult, ) self.plug_configs[plug_id]["power"] = config self._add_subscription(plug_id, effective_power_topic, "power") - # Configure energy subscription - if effective_energy_topic and energy_path: + # Configure energy subscription (path is optional - empty means use raw payload) + if effective_energy_topic: config = MQTTDataSourceConfig( topic=effective_energy_topic, - path=energy_path, + path=energy_path or "", multiplier=effective_energy_mult, ) self.plug_configs[plug_id]["energy"] = config self._add_subscription(plug_id, effective_energy_topic, "energy") - # Configure state subscription - if effective_state_topic and state_path: + # Configure state subscription (path is optional - empty means use raw payload) + if effective_state_topic: config = MQTTDataSourceConfig( topic=effective_state_topic, - path=state_path, + path=state_path or "", on_value=state_on_value, ) self.plug_configs[plug_id]["state"] = config diff --git a/backend/tests/integration/test_smart_plugs_api.py b/backend/tests/integration/test_smart_plugs_api.py index 0a6421ae0..c5e917e10 100644 --- a/backend/tests/integration/test_smart_plugs_api.py +++ b/backend/tests/integration/test_smart_plugs_api.py @@ -624,13 +624,12 @@ class TestSmartPlugsAPI: @pytest.mark.asyncio @pytest.mark.integration - async def test_create_mqtt_plug_missing_paths(self, async_client: AsyncClient): - """Verify creating MQTT plug without any JSON paths fails.""" + async def test_create_mqtt_plug_missing_topic(self, async_client: AsyncClient): + """Verify creating MQTT plug without any topic fails.""" data = { "name": "MQTT Plug", "plug_type": "mqtt", - "mqtt_topic": "test/topic", - # Missing both mqtt_power_path and mqtt_state_path + # No topic configured at all "enabled": True, } @@ -781,19 +780,22 @@ class TestSmartPlugsAPI: @pytest.mark.asyncio @pytest.mark.integration - async def test_create_mqtt_plug_no_data_source_fails(self, async_client: AsyncClient): - """Verify creating MQTT plug without any complete data source fails.""" + async def test_create_mqtt_plug_topic_only_succeeds(self, async_client: AsyncClient, mock_mqtt_smart_plug_service): + """Verify creating MQTT plug with topic only (no path) succeeds for raw values.""" data = { - "name": "Invalid MQTT Plug", + "name": "Raw MQTT Plug", "plug_type": "mqtt", - # Has topic but no path - not a complete data source + # Topic only, no path - valid for raw numeric MQTT values "mqtt_power_topic": "zigbee/power", "enabled": True, } response = await async_client.post("/api/v1/smart-plugs/", json=data) - assert response.status_code == 422 # Validation error + assert response.status_code == 200 # Should succeed + result = response.json() + assert result["mqtt_power_topic"] == "zigbee/power" + assert result["mqtt_power_path"] is None @pytest.mark.asyncio @pytest.mark.integration diff --git a/frontend/src/components/AddSmartPlugModal.tsx b/frontend/src/components/AddSmartPlugModal.tsx index f976cab6e..f5436ff35 100644 --- a/frontend/src/components/AddSmartPlugModal.tsx +++ b/frontend/src/components/AddSmartPlugModal.tsx @@ -296,13 +296,13 @@ export function AddSmartPlugModal({ plug, onClose }: AddSmartPlugModalProps) { } if (plugType === 'mqtt') { - // Check that at least one data source is fully configured - const hasPower = mqttPowerTopic.trim() && mqttPowerPath.trim(); - const hasEnergy = mqttEnergyTopic.trim() && mqttEnergyPath.trim(); - const hasState = mqttStateTopic.trim() && mqttStatePath.trim(); + // Check that at least one topic is configured (path is optional) + const hasPower = mqttPowerTopic.trim(); + const hasEnergy = mqttEnergyTopic.trim(); + const hasState = mqttStateTopic.trim(); if (!hasPower && !hasEnergy && !hasState) { - setError('At least one data source must be configured: power (topic + path), energy (topic + path), or state (topic + path)'); + setError('At least one MQTT topic must be configured for power, energy, or state monitoring'); return; } } @@ -971,7 +971,8 @@ export function AddSmartPlugModal({ plug, onClose }: AddSmartPlugModalProps) {

- Use multiplier 0.001 for mW→W, 1000 for kW→W + JSON path extracts value from JSON payload (e.g., "power_l1"). Leave empty if topic publishes raw numeric values.
+ Use multiplier 0.001 for mW→W, 1000 for kW→W.

@@ -1011,7 +1012,8 @@ export function AddSmartPlugModal({ plug, onClose }: AddSmartPlugModalProps) {

- Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh + JSON path extracts value from JSON payload. Leave empty for raw values.
+ Use multiplier 0.001 for Wh→kWh, 1000 for MWh→kWh.

@@ -1051,7 +1053,8 @@ export function AddSmartPlugModal({ plug, onClose }: AddSmartPlugModalProps) {

- ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1) + JSON path extracts value from JSON payload. Leave empty for raw values.
+ ON value: the exact string that means "ON". Leave empty for auto-detect (ON, true, 1).

diff --git a/static/assets/index-Cry_KMOA.js b/static/assets/index-C7_2Jo_p.js similarity index 92% rename from static/assets/index-Cry_KMOA.js rename to static/assets/index-C7_2Jo_p.js index 1082b56e4..7408f8a7c 100644 --- a/static/assets/index-Cry_KMOA.js +++ b/static/assets/index-C7_2Jo_p.js @@ -8648,7 +8648,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${wb(t. transition-all duration-200 hover:border-bambu-dark-tertiary/80 ${b?"opacity-50 scale-[1.02] shadow-xl z-50":""} ${N?"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:[S&&d&&s.jsx("button",{onClick:T=>{T.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(Ya,{className:"w-4 h-4"})}),S?s.jsx("div",{...f,...m,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(ag,{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?fe.getArchivePlateThumbnail(t.archive_id,t.plate_id):fe.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?s.jsx("img",{src:t.plate_id!=null?fe.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):fe.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(ul,{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(ms,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:"View archive",children:s.jsx(Ur,{className:"w-3.5 h-3.5"})}):t.library_file_id?s.jsx(ms,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:"View in File Manager",children:s.jsx(Ur,{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?"text-orange-400":""}`,children:[s.jsx(qr,{className:"w-3.5 h-3.5"}),t.printer_id===null?"Unassigned":t.printer_name||`Printer #${t.printer_id}`]}),t.print_time_seconds&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_d,{className:"w-3.5 h-3.5"}),Sre(t.print_time_seconds)]}),S&&!t.manual_start&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wn,{className:"w-3.5 h-3.5"}),IWe(t.scheduled_time,c)]})]}),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(oW,{className:"w-3 h-3"}),"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:"Requires previous success"}),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(xu,{className:"w-3 h-3"}),"Auto power off"]})]}),N&&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:"Printing in progress..."})]}),t.error_message&&s.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[s.jsx(ra,{className:"w-3 h-3"}),t.error_message]})]}),s.jsx(FWe,{status:t.status}),s.jsxs("div",{className:"flex items-center gap-1",children:[N&&s.jsx(Me,{variant:"ghost",size:"sm",onClick:a,title:"Stop Print",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Kce,{className:"w-4 h-4"})}),S&&s.jsxs(s.Fragment,{children:[t.manual_start&&s.jsx(Me,{variant:"ghost",size:"sm",onClick:l,title:"Start Print",className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:s.jsx(Po,{className:"w-4 h-4"})}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:n,title:"Edit",children:s.jsx(ia,{className:"w-4 h-4"})}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:r,title:"Cancel",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Ut,{className:"w-4 h-4"})})]}),A&&s.jsxs(s.Fragment,{children:[s.jsx(Me,{variant:"ghost",size:"sm",onClick:o,title:"Re-queue",className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:s.jsx(gr,{className:"w-4 h-4"})}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:i,title:"Remove",children:s.jsx(ln,{className:"w-4 h-4"})})]})]})]})})}function zWe(){const t=an(),{showToast:e}=Hn(),[n,r]=w.useState(null),[i,a]=w.useState(""),[o,l]=w.useState(!1),[c,u]=w.useState(null),[d,f]=w.useState(null),[m,g]=w.useState(null),[x,y]=w.useState([]),[b,v]=w.useState(!1),[N,S]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[A,T]=w.useState(()=>{const _e=localStorage.getItem("queue.historySortAsc");return _e!==null?_e==="true":!1}),[C,E]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[D,k]=w.useState(()=>{const _e=localStorage.getItem("queue.pendingSortAsc");return _e!==null?_e==="true":!0});w.useEffect(()=>{localStorage.setItem("queue.historySortBy",N)},[N]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(A))},[A]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",C)},[C]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(D))},[D]);const R=Zne(M2(mM,{activationConstraint:{distance:8}}),M2(fM,{coordinateGetter:_re})),{data:F}=ct({queryKey:["settings"],queryFn:fe.getSettings}),O=F?.time_format||"system",{data:X,isLoading:j}=ct({queryKey:["queue",n,i],queryFn:()=>fe.getQueue(n||void 0,i||void 0),refetchInterval:5e3}),{data:q}=ct({queryKey:["printers"],queryFn:()=>fe.getPrinters()}),Y=ht({mutationFn:_e=>fe.cancelQueueItem(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Queue item cancelled")},onError:()=>e("Failed to cancel item","error")}),W=ht({mutationFn:_e=>fe.removeFromQueue(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Queue item removed")},onError:()=>e("Failed to remove item","error")}),Z=ht({mutationFn:_e=>fe.stopQueueItem(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Print stopped")},onError:()=>e("Failed to stop print","error")}),ee=ht({mutationFn:_e=>fe.startQueueItem(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Print released to queue")},onError:()=>e("Failed to start print","error")}),ne=ht({mutationFn:_e=>fe.reorderQueue(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]})},onError:()=>e("Failed to reorder queue","error")}),z=ht({mutationFn:async()=>{const _e=X?.filter(oe=>["completed","failed","skipped","cancelled"].includes(oe.status))||[];for(const oe of _e)await fe.removeFromQueue(oe.id);return _e.length},onSuccess:_e=>{t.invalidateQueries({queryKey:["queue"]}),e(`Cleared ${_e} history item${_e!==1?"s":""}`)},onError:()=>e("Failed to clear history","error")}),G=ht({mutationFn:_e=>fe.bulkUpdateQueue(_e),onSuccess:_e=>{t.invalidateQueries({queryKey:["queue"]}),y([]),v(!1),e(_e.message)},onError:()=>e("Failed to update items","error")}),ae=ht({mutationFn:async _e=>{for(const oe of _e)await fe.cancelQueueItem(oe);return _e.length},onSuccess:_e=>{t.invalidateQueries({queryKey:["queue"]}),y([]),e(`Cancelled ${_e} item${_e!==1?"s":""}`)},onError:()=>e("Failed to cancel items","error")}),se=_e=>{y(oe=>oe.includes(_e)?oe.filter(ze=>ze!==_e):[...oe,_e])},de=w.useMemo(()=>{const _e=X?.filter(ze=>ze.status==="pending")||[],oe=ze=>{if(!ze.scheduled_time)return 0;const V=new Date(ze.scheduled_time).getTime(),H=Date.now()+4320*60*60*1e3;return V>H?0:V};return[..._e].sort((ze,V)=>{let H;if(C==="name"){const K=ze.archive_name||ze.library_file_name||"",U=V.archive_name||V.library_file_name||"";H=K.localeCompare(U)}else C==="printer"?H=(ze.printer_name||"").localeCompare(V.printer_name||""):C==="time"?H=oe(ze)-oe(V):H=ze.position-V.position;return D?H:-H})},[X,C,D]),me=()=>{const _e=de.map(oe=>oe.id);x.length===_e.length?y([]):y(_e)},ue=X?.filter(_e=>_e.status==="printing")||[],Ae=w.useMemo(()=>[...X?.filter(oe=>["completed","failed","skipped","cancelled"].includes(oe.status))||[]].sort((oe,ze)=>{let V;if(N==="name"){const H=oe.archive_name||oe.library_file_name||"",K=ze.archive_name||ze.library_file_name||"";V=H.localeCompare(K)}else N==="printer"?V=(oe.printer_name||"").localeCompare(ze.printer_name||""):V=new Date(ze.completed_at||ze.created_at).getTime()-new Date(oe.completed_at||oe.created_at).getTime();return A?-V:V}),[X,N,A]),pe=w.useMemo(()=>de.reduce((_e,oe)=>_e+(oe.print_time_seconds||0),0),[de]),Ee=_e=>{const{active:oe,over:ze}=_e;if(!ze||oe.id===ze.id)return;const V=de.findIndex(K=>K.id===oe.id),H=de.findIndex(K=>K.id===ze.id);if(V!==-1&&H!==-1){const U=xM(de,V,H).map((Q,le)=>({id:Q.id,position:le+1}));ne.mutate(U)}};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(lW,{className:"w-7 h-7 text-bambu-green"}),"Print Queue"]}),s.jsx("p",{className:"text-bambu-gray mt-1",children:"Schedule and manage your print jobs"})]})}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[s.jsx(wt,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:s.jsx(Nt,{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(Po,{className:"w-5 h-5 text-blue-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:ue.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Printing"})]})]})})}),s.jsx(wt,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:s.jsx(Nt,{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(Wn,{className:"w-5 h-5 text-yellow-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:de.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Queued"})]})]})})}),s.jsx(wt,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:s.jsx(Nt,{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(_d,{className:"w-5 h-5 text-bambu-green"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Sre(pe)}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Total Queue Time"})]})]})})}),s.jsx(wt,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:s.jsx(Nt,{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(Dn,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Ae.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"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:n===-1?"unassigned":n||"",onChange:_e=>{const oe=_e.target.value;r(oe==="unassigned"?-1:oe===""?null:Number(oe))},children:[s.jsx("option",{value:"",children:"All Printers"}),s.jsx("option",{value:"unassigned",children:"Unassigned"}),q?.map(_e=>s.jsx("option",{value:_e.id,children:_e.name},_e.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:i,onChange:_e=>a(_e.target.value),children:[s.jsx("option",{value:"",children:"All Status"}),s.jsx("option",{value:"pending",children:"Pending"}),s.jsx("option",{value:"printing",children:"Printing"}),s.jsx("option",{value:"completed",children:"Completed"}),s.jsx("option",{value:"failed",children:"Failed"}),s.jsx("option",{value:"skipped",children:"Skipped"}),s.jsx("option",{value:"cancelled",children:"Cancelled"})]}),s.jsx("div",{className:"flex-1"}),Ae.length>0&&s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>l(!0),children:[s.jsx(ln,{className:"w-4 h-4"}),"Clear History"]})]}),j?s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"Loading..."}):X?.length===0?s.jsxs(wt,{className:"p-12 text-center border-dashed",children:[s.jsx(ii,{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:"No prints scheduled"}),s.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:'Schedule a print from the Archives page using the "Schedule" option in the context menu, or drag and drop files to get started.'})]}):s.jsxs("div",{className:"space-y-8",children:[ue.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"}),"Currently Printing"]}),s.jsx("div",{className:"space-y-3",children:ue.map(_e=>s.jsx(_j,{item:_e,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>g({type:"stop",item:_e}),onRequeue:()=>{},onStart:()=>{},timeFormat:O},_e.id))})]}),de.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(Wn,{className:"w-5 h-5 text-yellow-400"}),"Queued",s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",de.length," item",de.length!==1?"s":"",")"]}),s.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:"Position only affects ASAP items. Scheduled items run at their set time.",children:"Drag to reorder (ASAP only)"})]}),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:C,onChange:_e=>E(_e.target.value),children:[s.jsx("option",{value:"position",children:"Sort by Position"}),s.jsx("option",{value:"name",children:"Sort by Name"}),s.jsx("option",{value:"printer",children:"Sort by Printer"}),s.jsx("option",{value:"time",children:"Sort by Schedule"})]}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>k(!D),title:D?"Ascending":"Descending",className:"px-2",children:D?s.jsx(ig,{className:"w-4 h-4"}):s.jsx(h0,{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(Me,{variant:"ghost",size:"sm",onClick:me,className:"flex items-center gap-2",children:[x.length===de.length&&de.length>0?s.jsx(Ro,{className:"w-4 h-4 text-bambu-green"}):s.jsx(Do,{className:"w-4 h-4"}),x.length===de.length&&de.length>0?"Deselect All":"Select All"]}),x.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"text-sm text-bambu-gray",children:[x.length," selected"]}),s.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),s.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>v(!0),className:"flex items-center gap-2 text-bambu-green hover:text-bambu-green-light",children:[s.jsx(ia,{className:"w-4 h-4"}),"Edit Selected"]}),s.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>ae.mutate(x),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:ae.isPending,children:[s.jsx(Ut,{className:"w-4 h-4"}),"Cancel Selected"]})]})]}),s.jsx(pre,{sensors:R,collisionDetection:nre,onDragEnd:Ee,children:s.jsx(bre,{items:de.map(_e=>_e.id),strategy:EWe,children:s.jsx("div",{className:"space-y-3",children:de.map((_e,oe)=>s.jsx(_j,{item:_e,position:oe+1,onEdit:()=>u(_e),onCancel:()=>g({type:"cancel",item:_e}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>ee.mutate(_e.id),timeFormat:O,isSelected:x.includes(_e.id),onToggleSelect:()=>se(_e.id)},_e.id))})})})]}),Ae.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(Dn,{className:"w-5 h-5 text-bambu-gray"}),"History",s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ae.length," item",Ae.length!==1?"s":"",")"]})]}),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:N,onChange:_e=>S(_e.target.value),children:[s.jsx("option",{value:"date",children:"Sort by Date"}),s.jsx("option",{value:"name",children:"Sort by Name"}),s.jsx("option",{value:"printer",children:"Sort by Printer"})]}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>T(!A),title:A?"Ascending (oldest first)":"Descending (newest first)",className:"px-2",children:A?s.jsx(ig,{className:"w-4 h-4"}):s.jsx(h0,{className:"w-4 h-4"})})]})]}),s.jsx("div",{className:"space-y-3",children:Ae.slice(0,20).map((_e,oe)=>s.jsx(_j,{item:_e,position:oe+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>g({type:"remove",item:_e}),onStop:()=>{},onRequeue:()=>f(_e),onStart:()=>{},timeFormat:O},_e.id))})]})]}),c&&s.jsx(th,{mode:"edit-queue-item",archiveId:c.archive_id??void 0,libraryFileId:c.library_file_id??void 0,archiveName:c.archive_name||c.library_file_name||`File #${c.archive_id||c.library_file_id}`,queueItem:c,onClose:()=>u(null)}),d&&s.jsx(th,{mode:"add-to-queue",archiveId:d.archive_id??void 0,libraryFileId:d.library_file_id??void 0,archiveName:d.archive_name||d.library_file_name||`File #${d.archive_id||d.library_file_id}`,onClose:()=>f(null)}),m&&s.jsx(Fn,{title:m.type==="cancel"?"Cancel Scheduled Print":m.type==="stop"?"Stop Print":"Remove from History",message:m.type==="cancel"?`Are you sure you want to cancel "${m.item.archive_name||m.item.library_file_name||"this print"}"?`:m.type==="stop"?`Are you sure you want to stop the current print "${m.item.archive_name||m.item.library_file_name||"this print"}"? This will cancel the print job on the printer.`:`Are you sure you want to remove "${m.item.archive_name||m.item.library_file_name||"this item"}" from the queue history?`,confirmText:m.type==="cancel"?"Cancel Print":m.type==="stop"?"Stop Print":"Remove",variant:"danger",onConfirm:()=>{m.type==="cancel"?Y.mutate(m.item.id):m.type==="stop"?Z.mutate(m.item.id):W.mutate(m.item.id),g(null)},onCancel:()=>g(null)}),o&&s.jsx(Fn,{title:"Clear History",message:`Are you sure you want to remove all ${Ae.length} item${Ae.length!==1?"s":""} from the history?`,confirmText:"Clear History",variant:"danger",onConfirm:()=>{z.mutate(),l(!1)},onCancel:()=>l(!1)}),b&&s.jsx(UWe,{selectedCount:x.length,printers:q?.map(_e=>({id:_e.id,name:_e.name}))||[],onSave:_e=>{Object.keys(_e).length>0&&G.mutate({item_ids:x,..._e})},onClose:()=>v(!1),isSaving:G.isPending})]})}function BWe({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const N=n.current;if(!N)return;const S=new ResizeObserver(A=>{const T=A[0]?.contentRect.width||0;i(T)});return S.observe(N),()=>S.disconnect()},[]);const{weeks:a,monthLabels:o,printCounts:l}=w.useMemo(()=>{const N={};t.forEach(F=>{const O=F.split("T")[0];N[O]=(N[O]||0)+1});const S=new Date,A=new Date(S);A.setMonth(A.getMonth()-e),A.setDate(A.getDate()-A.getDay());const T=[],C=[];let E=[],D=-1;const k=new Date(A);let R=0;for(;k<=S;)k.getDay()===0&&E.length>0&&(T.push(E),E=[],R++),k.getMonth()!==D&&(C.push({month:k.toLocaleDateString("en-US",{month:"short"}),weekIndex:R}),D=k.getMonth()),E.push(new Date(k)),k.setDate(k.getDate()+1);return E.length>0&&T.push(E),{weeks:T,monthLabels:C,printCounts:N}},[t,e]),c=Math.max(1,...Object.values(l)),u=N=>{if(N===0)return"bg-bambu-dark";const S=N/c;return S<=.25?"bg-bambu-green/30":S<=.5?"bg-bambu-green/50":S<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],f=a.length,m=32,g=2,x=r-m-16,y=f>0?Math.floor((x-(f-1)*g)/f):12,b=Math.max(8,Math.min(20,y)),v=b<=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:m+4},children:o.map(({month:N,weekIndex:S},A)=>s.jsx("div",{className:"text-bambu-gray",style:{fontSize:v,marginLeft:A===0?0:`${(S-(o[A-1]?.weekIndex||0))*(b+g)-24}px`},children:N},A))}),s.jsxs("div",{className:"flex",style:{gap:g},children:[s.jsx("div",{className:"flex flex-col",style:{gap:g,marginRight:4,width:m},children:d.map((N,S)=>s.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:m,height:b,fontSize:v,visibility:S%2===1?"visible":"hidden"},children:N},N))}),a.map((N,S)=>s.jsx("div",{className:"flex flex-col",style:{gap:g},children:[0,1,2,3,4,5,6].map(A=>{const T=N.find(k=>k.getDay()===A);if(!T)return s.jsx("div",{style:{width:b,height:b}},A);const C=T.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:b,height:b},title:`${T.toLocaleDateString()}: ${E} print${E!==1?"s":""}`},A)})},S))]}),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:g},children:[s.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),s.jsx("span",{children:"More"})]})]})})}const O1=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function $We(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 HWe({archives:t,currency:e="$"}){const[n,r]=w.useState("30d"),i=w.useMemo(()=>{const m=$We(n);return t.filter(g=>(vi(g.completed_at||g.created_at)||new Date(0))>=m)},[t,n]),a=w.useMemo(()=>{const m=new Map;return i.forEach(g=>{const x=vi(g.completed_at||g.created_at)||new Date,y=`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,b=m.get(y)||{date:y,filament:0,cost:0,prints:0};b.filament+=g.filament_used_grams||0,b.cost+=g.cost||0,b.prints+=1,m.set(y,b)}),Array.from(m.values()).sort((g,x)=>g.date.localeCompare(x.date)).map(g=>({...g,dateLabel:new Date(g.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=w.useMemo(()=>{if(n==="7d"||n==="30d")return a;const m=new Map;return i.forEach(g=>{const x=vi(g.completed_at||g.created_at)||new Date,y=new Date(x);y.setDate(x.getDate()-x.getDay());const b=`${y.getFullYear()}-${String(y.getMonth()+1).padStart(2,"0")}-${String(y.getDate()).padStart(2,"0")}`,v=m.get(b)||{week:b,filament:0,cost:0,prints:0};v.filament+=g.filament_used_grams||0,v.cost+=g.cost||0,v.prints+=1,m.set(b,v)}),Array.from(m.values()).sort((g,x)=>g.week.localeCompare(x.week)).map(g=>({date:g.week,dateLabel:`Week of ${new Date(g.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...g}))},[i,a,n]),l=w.useMemo(()=>{const m=new Map;return i.forEach(g=>{const y=(g.filament_type||"Unknown").split(", ");y.forEach(b=>{const v=(g.filament_used_grams||0)/y.length;m.set(b,(m.get(b)||0)+v)})}),Array.from(m.entries()).map(([g,x])=>({name:g,value:Math.round(x)})).sort((g,x)=>x.value-g.value)},[i]),c=w.useMemo(()=>{const m=new Date,g=[];for(let x=5;x>=0;x--){const y=new Date(m.getFullYear(),m.getMonth()-x,1),b=new Date(m.getFullYear(),m.getMonth()-x+1,0),v=y.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(S=>{const A=vi(S.completed_at||S.created_at)||new Date(0);return A>=y&&A<=b});g.push({month:v,filament:Math.round(N.reduce((S,A)=>S+(A.filament_used_grams||0),0)),cost:N.reduce((S,A)=>S+(A.cost||0),0),prints:N.length})}return g},[t]),u=n==="7d"||n==="30d"?a:o,d=i.reduce((m,g)=>m+(g.filament_used_grams||0),0),f=i.reduce((m,g)=>m+(g.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(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:[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(G1,{width:"100%",height:250,children:s.jsxs(Uke,{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(mS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx(gS,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),s.jsx(xS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),s.jsx(W1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:m=>[`${Number(m??0).toFixed(0)}g`,"Filament"]}),s.jsx(_Z,{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(G1,{width:160,height:160,children:s.jsxs(Ike,{children:[s.jsx(GQ,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((m,g)=>s.jsx(jy,{fill:O1[g%O1.length]},`cell-${g}`))}),s.jsx(W1,{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,g)=>{const x=l.reduce((b,v)=>b+v.value,0),y=x>0?(m.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:O1[g%O1.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(G1,{width:"100%",height:200,children:s.jsxs(Mke,{data:c,children:[s.jsx(mS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx(gS,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),s.jsx(xS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),s.jsx(W1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(m,g)=>[g==="filament"?`${m??0}g`:g==="cost"?`${e}${Number(m??0).toFixed(2)}`:m??0,g==="filament"?"Filament":g==="cost"?"Cost":"Prints"]}),s.jsx(GD,{}),s.jsx(QQ,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function VWe({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:m}=vre({id:t}),g={transform:Dg.Transform.toString(d),transition:f,opacity:m?.5:1};return r?null:s.jsxs("div",{ref:u,style:{...g,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${m?"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(ag,{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(uW,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):s.jsx(cW,{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(D2,{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 GWe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:a}){const o=()=>{const A={};return t.forEach(T=>{A[T.id]=T.defaultSize||4}),A},[l,c]=w.useState(()=>{const A=localStorage.getItem(e);if(A)try{const T=JSON.parse(A);return T.sizes||(T.sizes=o()),T}catch{}return{order:t.map(T=>T.id),hidden:t.filter(T=>T.defaultVisible===!1).map(T=>T.id),sizes:o()}}),[u,d]=w.useState(!1);w.useEffect(()=>{const A=()=>d(T=>!T);return window.addEventListener("toggle-hidden-panel",A),()=>window.removeEventListener("toggle-hidden-panel",A)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),w.useEffect(()=>{const T=t.map(C=>C.id).filter(C=>!l.order.includes(C));T.length>0&&c(C=>({...C,order:[...C.order,...T]}))},[t,l.order]);const f=Zne(M2(mM,{activationConstraint:{distance:8}}),M2(fM,{coordinateGetter:_re})),m=A=>{const{active:T,over:C}=A;C&&T.id!==C.id&&c(E=>{const D=E.order.indexOf(T.id),k=E.order.indexOf(C.id);return{...E,order:xM(E.order,D,k)}})},g=A=>{c(T=>({...T,hidden:T.hidden.includes(A)?T.hidden.filter(C=>C!==A):[...T.hidden,A]}))},x=A=>{c(T=>{const C=T.sizes[A]||4,E=C===1?2:C===2?4:1;return{...T,sizes:{...T.sizes,[A]:E}}})},y=()=>{const A={order:t.map(T=>T.id),hidden:t.filter(T=>T.defaultVisible===!1).map(T=>T.id),sizes:o()};c(A),i?.()},b=l.order.map(A=>t.find(T=>T.id===A)).filter(Boolean),v=b.filter(A=>!l.hidden.includes(A.id)),N=b.filter(A=>l.hidden.includes(A.id)),S=a?.({hiddenCount:N.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:y});return s.jsxs("div",{className:"space-y-4",children:[S,!r&&!a&&s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsxs(Me,{variant:"secondary",size:"sm",onClick:y,children:[s.jsx(Zf,{className:"w-4 h-4"}),"Reset Layout"]}),N.length>0&&s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[s.jsx(ou,{className:"w-4 h-4"}),N.length," Hidden"]})]}),u&&N.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:N.map(A=>s.jsxs("button",{onClick:()=>g(A.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(ou,{className:"w-3 h-3"}),A.title]},A.id))})]}),s.jsx(pre,{sensors:f,collisionDetection:nre,onDragEnd:m,children:s.jsx(bre,{items:v.map(A=>A.id),strategy:$L,children:s.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:v.map(A=>s.jsx(VWe,{id:A.id,title:A.title,component:A.component,isHidden:l.hidden.includes(A.id),size:l.sizes[A.id]||2,onToggleVisibility:()=>g(A.id),onToggleSize:()=>x(A.id)},A.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(Me,{className:"mt-4",onClick:y,children:"Reset Layout"})]})]})}function qWe({stats:t,currency:e}){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(Bl,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Total Prints"}),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(Wn,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Print Time"}),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(Bl,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament Used"}),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(Gj,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament Cost"}),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(Vd,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Energy Used"}),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(Gj,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Energy Cost"}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function WWe({stats:t,printerMap:e,size:n=1}){const r=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,i=n===1?112:n===2?128:144,a=i/2-8,o=a*2*Math.PI;return s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"relative flex-shrink-0",style:{width:i,height:i},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:i/2,cy:i/2,r:a,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:i/2,cy:i/2,r:a,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${r/100*o} ${o}`})]}),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:[r,"%"]})})]}),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(Dn,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:"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(ea,{className:"w-4 h-4 text-status-error flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:"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:"Prints by Printer"}),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(([l,c])=>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(l)||`Printer ${l}`}),s.jsx("span",{className:"text-white font-medium",children:c})]},l))})]})]})]})}function KWe({stats:t,printerMap:e,size:n=1}){const r=t?.average_time_accuracy;if(r==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:"No time accuracy data yet"})});const a=(Math.min(150,Math.max(50,r))-50)/100*100,l=(x=>x>=95&&x<=105?"#00ae42":x>105?"#3b82f6":"#f97316")(r),c=r-100,u=n===1?112:n===2?128:144,d=u/2-8,f=d*2*Math.PI,m=n===1?3:n===2?6:999,g=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:u,height:u},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:u/2,cy:u/2,r:d,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:u/2,cy:u/2,r:d,fill:"none",stroke:l,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${a/100*f} ${f}`})]}),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:[r.toFixed(0),"%"]}),s.jsxs("span",{className:`text-xs ${c>=0?"text-blue-400":"text-orange-400"}`,children:[c>=0?"+":"",c.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(pW,{className:"w-3 h-3 flex-shrink-0"}),s.jsx("span",{children:"100% = perfect estimate"})]}),g.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:g.map(([x,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(x)||`Printer ${x}`}),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),"%"]})]},x))})]})]})}function XWe({stats:t,size:e=1}){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:"No filament data available"});const n=Object.entries(t.prints_by_filament_type).sort(([,o],[,l])=>l-o),r=e===1?5:e===2?8:999,i=n.slice(0,r),a=n.length>r;return e===4&&i.length>4?s.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:i.map(([o,l])=>{const c=Math.round(l/(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:o}),s.jsx("span",{className:"text-bambu-gray",children:l})]}),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:`${c}%`}})})]},o)})}):s.jsxs("div",{className:"space-y-3",children:[i.map(([o,l])=>{const c=Math.round(l/(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:o}),s.jsxs("span",{className:"text-bambu-gray",children:[l," 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:`${c}%`}})})]},o)}),a&&s.jsxs("p",{className:"text-xs text-bambu-gray text-center pt-1",children:["+",n.length-r," more types"]})]})}function YWe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return s.jsx(BWe,{printDates:t,months:n})}function QWe({stats:t,printerMap:e}){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:"No printer data available"}):s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([n,r])=>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(qr,{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(n)||`Printer ${n}`}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[r," prints"]})]})]},n))})}function ZWe({archives:t,currency:e}){return!t||t.length===0?s.jsx("p",{className:"text-bambu-gray text-center py-4",children:"No print data available"}):s.jsx(HWe,{archives:t,currency:e})}function JWe({size:t=1}){const{data:e,isLoading:n}=ct({queryKey:["failureAnalysis"],queryFn:()=>fe.getFailureAnalysis({days:30})});if(n)return s.jsx("div",{className:"flex justify-center py-4",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!e||e.total_prints===0)return s.jsx("p",{className:"text-bambu-gray text-center py-4",children:"No print data in the last 30 days"});const r=t===1?5:t===2?8:999,i=Object.entries(e.failures_by_reason).sort(([,l],[,c])=>c-l),a=i.slice(0,r),o=i.length>r;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(Nn,{className:`w-5 h-5 ${e.failure_rate>20?"text-status-error":e.failure_rate>10?"text-status-warning":"text-status-ok"}`}),s.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[e.failure_rate.toFixed(1),"%"]})]})}),s.jsxs("div",{className:"text-sm text-bambu-gray mt-1",children:[e.failed_prints," / ",e.total_prints," prints failed"]}),e.trend&&e.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(xW,{className:`w-4 h-4 ${e.trend[e.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?"Failure Reasons":"Top Failure Reasons"}),s.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:a.map(([l,c])=>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:l||"Unknown"}),s.jsx("span",{className:"text-bambu-gray ml-2",children:c})]},l))}),o&&s.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:["+",i.length-r," more reasons"]})]})]})}function eKe(){const{showToast:t}=Hn(),[e,n]=w.useState(!1),[r,i]=w.useState(!1),[a,o]=w.useState(0),[l,c]=w.useState(0),[u,d]=w.useState(!1);w.useEffect(()=>{const E=()=>{try{const k=localStorage.getItem("bambusy-dashboard-layout");if(k){const R=JSON.parse(k);c(R.hidden?.length||0)}}catch{c(0)}};E(),window.addEventListener("storage",E);const D=setInterval(E,500);return()=>{window.removeEventListener("storage",E),clearInterval(D)}},[a]);const{data:f,isLoading:m,refetch:g}=ct({queryKey:["archiveStats"],queryFn:fe.getArchiveStats}),{data:x}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:y}=ct({queryKey:["archives"],queryFn:()=>fe.getArchives(void 0,void 0,1e3,0)}),{data:b}=ct({queryKey:["settings"],queryFn:fe.getSettings}),v=async E=>{i(!1),n(!0);try{const{blob:D,filename:k}=await fe.exportStats({format:E,days:90}),R=URL.createObjectURL(D),F=document.createElement("a");F.href=R,F.download=k,F.click(),URL.revokeObjectURL(R),t("Export downloaded")}catch{t("Export failed","error")}finally{n(!1)}},N=async()=>{d(!0);try{const E=await fe.recalculateCosts();await g(),t(`Recalculated costs for ${E.updated} archives`)}catch{t("Failed to recalculate costs","error")}finally{d(!1)}},S=b?.currency||"$",A=new Map(x?.map(E=>[String(E.id),E.name])||[]),T=y?.map(E=>E.created_at)||[];if(m)return s.jsx("div",{className:"p-4 md:p-8",children:s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"Loading statistics..."})});const C=[{id:"quick-stats",title:"Quick Stats",component:s.jsx(qWe,{stats:f,currency:S}),defaultSize:2},{id:"success-rate",title:"Success Rate",component:E=>s.jsx(WWe,{stats:f,printerMap:A,size:E}),defaultSize:1},{id:"time-accuracy",title:"Time Accuracy",component:E=>s.jsx(KWe,{stats:f,printerMap:A,size:E}),defaultSize:1},{id:"filament-types",title:"Filament Types",component:E=>s.jsx(XWe,{stats:f,size:E}),defaultSize:1},{id:"failure-analysis",title:"Failure Analysis (30 days)",component:E=>s.jsx(JWe,{size:E}),defaultSize:1},{id:"print-activity",title:"Print Activity",component:E=>s.jsx(YWe,{printDates:T,size:E}),defaultSize:2},{id:"prints-by-printer",title:"Prints by Printer",component:s.jsx(QWe,{stats:f,printerMap:A}),defaultSize:2},{id:"filament-trends",title:"Filament Usage Trends",component:s.jsx(ZWe,{archives:y||[],currency:S}),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:"Dashboard"}),s.jsx("p",{className:"text-bambu-gray",children:"Drag widgets to rearrange. Click the eye icon to hide."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[l>0&&s.jsxs(Me,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[s.jsx(ou,{className:"w-4 h-4"}),l," Hidden"]}),s.jsxs(Me,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),o(E=>E+1),t("Layout reset")},children:[s.jsx(Zf,{className:"w-4 h-4"}),"Reset Layout"]}),s.jsxs(Me,{variant:"secondary",onClick:N,disabled:u,title:"Recalculate all archive costs using current filament prices",children:[u?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Cce,{className:"w-4 h-4"}),"Recalculate Costs"]}),s.jsxs("div",{className:"relative",children:[s.jsxs(Me,{variant:"secondary",onClick:()=>i(!r),disabled:e,children:[e?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(bw,{className:"w-4 h-4"}),"Export Stats"]}),r&&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:()=>v("csv"),children:[s.jsx(Ga,{className:"w-4 h-4"}),"Export as CSV"]}),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:()=>v("xlsx"),children:[s.jsx(bw,{className:"w-4 h-4"}),"Export as Excel"]})]})]})]})]}),s.jsx(GWe,{widgets:C,storageKey:"bambusy-dashboard-layout",hideControls:!0},a)]})}function tKe({plug:t,onEdit:e}){const n=an(),{showToast:r}=Hn(),[i,a]=w.useState(!1),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,f]=w.useState(!1),{data:m,isLoading:g}=ct({queryKey:["smart-plug-status",t.id],queryFn:()=>fe.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:x}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),y=x?.find(k=>k.id===t.printer_id),b=ht({mutationFn:k=>fe.controlSmartPlug(t.id,k),onMutate:async k=>{await n.cancelQueries({queryKey:["smart-plug-status",t.id]});const R=n.getQueryData(["smart-plug-status",t.id]),F=k==="on"?"ON":k==="off"||m?.state==="ON"?"OFF":"ON";return n.setQueryData(["smart-plug-status",t.id],O=>({...O,state:F})),{previousStatus:R}},onError:(k,R,F)=>{F?.previousStatus&&n.setQueryData(["smart-plug-status",t.id],F.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=ht({mutationFn:k=>fe.updateSmartPlug(t.id,k),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&n.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]})}}),N=ht({mutationFn:()=>fe.deleteSmartPlug(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]})}}),S=m?.state==="ON",A=t.plug_type==="mqtt"&&m?.energy?.power!==null&&m?.energy?.power!==void 0,T=(m?.reachable??!1)||A,C=b.isPending,D=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const k=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${k}/`:`http://${k}/`})();return s.jsxs(s.Fragment,{children:[s.jsx(wt,{className:"relative",children:s.jsxs(Nt,{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"?T?"bg-teal-500/20":"bg-red-500/20":T?S?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?s.jsx(fD,{className:`w-5 h-5 ${T?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?s.jsx(U2,{className:`w-5 h-5 ${T?S?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):s.jsx(Gs,{className:`w-5 h-5 ${T?S?"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:[g?s.jsx(ut,{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"}),T&&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:T?S?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?m?.state||"?":"Offline"})]}):T?s.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[s.jsx(Vp,{className:"w-4 h-4 text-status-ok"}),s.jsx("span",{className:S?"text-status-ok":"text-bambu-gray",children:m?.state||"Unknown"})]}):s.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[s.jsx(Pf,{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(Ur,{className:"w-3 h-3"}),"Admin"]})]})]}),y&&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:y.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(ou,{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(df,{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(ii,{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(Me,{size:"sm",variant:S?"primary":"secondary",disabled:!T||C,onClick:()=>l(!0),className:"flex-1",children:[C?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xu,{className:"w-4 h-4"}),"On"]}),s.jsxs(Me,{size:"sm",variant:S?"secondary":"primary",disabled:!T||C,onClick:()=>u(!0),className:"flex-1",children:[C?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(H2,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&m?.energy&&s.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[m.energy.power!==null&&m.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(m.energy.power),"W"]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),m.energy.today!==null&&m.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:m.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($d,{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(z2,{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:k=>v.mutate({show_in_switchbar:k.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:k=>v.mutate({enabled:k.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:k=>v.mutate({auto_on:k.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:k=>v.mutate({auto_off:k.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(Wn,{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(G2,{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:k=>v.mutate({off_delay_minutes:parseInt(k.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:k=>v.mutate({off_temp_threshold:parseInt(k.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(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx($2,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>a(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),i&&s.jsx(Fn,{title:"Delete Smart Plug",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),a(!1)},onCancel:()=>a(!1)}),o&&s.jsx(Fn,{title:"Turn On Smart Plug",message:`Are you sure you want to turn on "${t.name}"?`,confirmText:"Turn On",variant:"default",onConfirm:()=>{b.mutate("on"),l(!1)},onCancel:()=>l(!1)}),c&&s.jsx(Fn,{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:()=>{b.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function nKe({plug:t,onClose:e}){const n=an(),r=!!t,[i,a]=w.useState(t?.plug_type||"tasmota"),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.ip_address||""),[d,f]=w.useState(t?.username||""),[m,g]=w.useState(t?.password||""),[x,y]=w.useState(t?.ha_entity_id||""),[b,v]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,S]=w.useState(t?.mqtt_power_path||""),[A,T]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,E]=w.useState(t?.mqtt_energy_topic||""),[D,k]=w.useState(t?.mqtt_energy_path||""),[R,F]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[O,X]=w.useState(t?.mqtt_state_topic||""),[j,q]=w.useState(t?.mqtt_state_path||""),[Y,W]=w.useState(t?.mqtt_state_on_value||""),[Z,ee]=w.useState(t?.ha_power_entity||""),[ne,z]=w.useState(t?.ha_energy_today_entity||""),[G,ae]=w.useState(t?.ha_energy_total_entity||""),[se,de]=w.useState(""),[me,ue]=w.useState(""),[Ae,pe]=w.useState(!1),Ee=w.useRef(null),[_e,oe]=w.useState(""),[ze,V]=w.useState(!1),H=w.useRef(null),[K,U]=w.useState(""),[Q,le]=w.useState(!1),ke=w.useRef(null),[Re,Ce]=w.useState(""),[B,I]=w.useState(!1),$=w.useRef(null),[te,ye]=w.useState(t?.printer_id||null),[be,Ye]=w.useState(null),[$e,Qe]=w.useState(null),[qe,Xe]=w.useState(t?.power_alert_enabled||!1),[ce,ie]=w.useState(t?.power_alert_high?.toString()||""),[Te,Ve]=w.useState(t?.power_alert_low?.toString()||""),[it,re]=w.useState(t?.schedule_enabled||!1),[De,we]=w.useState(t?.schedule_on_time||""),[Oe,Ue]=w.useState(t?.schedule_off_time||""),[je,Je]=w.useState(t?.show_in_switchbar||!1),[bt,Tt]=w.useState(!1),[Dt,sn]=w.useState({scanned:0,total:0}),[Lt,gn]=w.useState([]),rn=w.useRef(null),{data:zn}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:br}=ct({queryKey:["smart-plugs"],queryFn:fe.getSmartPlugs}),{data:er}=ct({queryKey:["settings"],queryFn:fe.getSettings}),yr=!!(er?.ha_enabled&&er?.ha_url&&er?.ha_token);w.useEffect(()=>{const xe=setTimeout(()=>{ue(se)},300);return()=>clearTimeout(xe)},[se]),w.useEffect(()=>{const xe=Le=>{Ee.current&&!Ee.current.contains(Le.target)&&pe(!1),H.current&&!H.current.contains(Le.target)&&V(!1),ke.current&&!ke.current.contains(Le.target)&&le(!1),$.current&&!$.current.contains(Le.target)&&I(!1)};return document.addEventListener("mousedown",xe),()=>document.removeEventListener("mousedown",xe)},[]);const{data:vr,isLoading:Xn,error:Bt}=ct({queryKey:["ha-entities",me],queryFn:()=>fe.getHAEntities(me||void 0),enabled:i==="homeassistant"&&yr,retry:!1,staleTime:0}),{data:In}=ct({queryKey:["ha-sensor-entities"],queryFn:fe.getHASensorEntities,enabled:i==="homeassistant"&&yr,retry:!1,staleTime:0});w.useEffect(()=>{const xe=Le=>{Le.key==="Escape"&&e()};return window.addEventListener("keydown",xe),()=>{window.removeEventListener("keydown",xe),rn.current&&clearInterval(rn.current)}},[e]);const Ti=async()=>{Tt(!0),gn([]),sn({scanned:0,total:0}),Qe(null);try{await fe.startTasmotaScan();const xe=async()=>{try{const Le=await fe.getTasmotaScanStatus();sn({scanned:Le.scanned,total:Le.total});const Ie=await fe.getDiscoveredTasmotaDevices();gn(Ie),Le.running||(Tt(!1),rn.current&&(clearInterval(rn.current),rn.current=null))}catch(Le){console.error("Polling error:",Le)}};await xe(),rn.current=setInterval(xe,500)}catch(xe){Tt(!1);const Le=xe instanceof Error?xe.message:typeof xe=="string"?xe:JSON.stringify(xe);Qe(Le||"Failed to start scan")}},_r=async()=>{try{await fe.stopTasmotaScan()}catch{}Tt(!1),rn.current&&(clearInterval(rn.current),rn.current=null)},Se=xe=>{u(xe.ip_address),l(xe.name),Ye(null)},We=ht({mutationFn:()=>fe.testSmartPlugConnection(c,d||null,m||null),onSuccess:xe=>{Ye(xe),Qe(null),!o&&xe.device_name&&l(xe.device_name)},onError:xe=>{Ye(null),Qe(xe.message)}}),et=ht({mutationFn:xe=>fe.createSmartPlug(xe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:xe=>{Qe(xe.message)}}),ot=ht({mutationFn:xe=>fe.updateSmartPlug(t.id,xe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:xe=>{Qe(xe.message)}}),at=zn?.filter(xe=>!br?.some(Ie=>Ie.printer_id===xe.id&&Ie.id!==t?.id)),At=xe=>{if(xe.preventDefault(),Qe(null),!o.trim()){Qe("Name is required");return}if(i==="tasmota"&&!c.trim()){Qe("IP address is required for Tasmota plugs");return}if(i==="homeassistant"&&!x){Qe("Entity is required for Home Assistant plugs");return}if(i==="mqtt"){const Ie=b.trim()&&N.trim(),Ne=C.trim()&&D.trim(),ft=O.trim()&&j.trim();if(!Ie&&!Ne&&!ft){Qe("At least one data source must be configured: power (topic + path), energy (topic + path), or state (topic + path)");return}}const Le={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"&&Z||null,ha_energy_today_entity:i==="homeassistant"&&ne||null,ha_energy_total_entity:i==="homeassistant"&&G||null,mqtt_power_topic:i==="mqtt"&&b.trim()||null,mqtt_power_path:i==="mqtt"&&N.trim()||null,mqtt_power_multiplier:i==="mqtt"&&parseFloat(A)||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"&&O.trim()||null,mqtt_state_path:i==="mqtt"&&j.trim()||null,mqtt_state_on_value:i==="mqtt"&&Y.trim()||null,username:i==="tasmota"&&d.trim()||null,password:i==="tasmota"&&m.trim()||null,printer_id:te,power_alert_enabled:qe,power_alert_high:ce?parseFloat(ce):null,power_alert_low:Te?parseFloat(Te):null,schedule_enabled:it,schedule_on_time:De||null,schedule_off_time:Oe||null,show_in_switchbar:je};r?ot.mutate(Le):et.mutate(Le)},he=et.isPending||ot.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:xe=>xe.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(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:At,className:"p-6 space-y-4 overflow-y-auto",children:[$e&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:$e}),!r&&s.jsxs("div",{className:"flex gap-2 mb-2",children:[s.jsxs("button",{type:"button",onClick:()=>{a("tasmota"),Ye(null),Qe(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(Gs,{className:"w-4 h-4"}),"Tasmota"]}),s.jsxs("button",{type:"button",onClick:()=>{a("homeassistant"),Ye(null),Qe(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(U2,{className:"w-4 h-4"}),"HA"]}),s.jsxs("button",{type:"button",onClick:()=>{a("mqtt"),Ye(null),Qe(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(fD,{className:"w-4 h-4"}),"MQTT"]})]}),!r&&i==="tasmota"&&s.jsxs("div",{className:"space-y-3",children:[bt?s.jsxs(Me,{type:"button",variant:"secondary",onClick:_r,className:"w-full",children:[s.jsx(Ut,{className:"w-4 h-4"}),"Stop Scanning"]}):s.jsxs(Me,{type:"button",variant:"primary",onClick:Ti,className:"w-full",children:[s.jsx(_a,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),bt&&Dt.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:[Dt.scanned," / ",Dt.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:`${Dt.scanned/Dt.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(xe=>s.jsxs("button",{type:"button",onClick:()=>Se(xe),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Gs,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:xe.name}),s.jsx("p",{className:"text-xs text-bambu-gray",children:xe.ip_address})]})]}),xe.state&&s.jsxs("span",{className:`flex items-center gap-1 text-xs ${xe.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[s.jsx(xu,{className:"w-3 h-3"}),xe.state]})]},xe.ip_address))})]}),!bt&&Lt.length===0&&Dt.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:[!yr&&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..."})})]})]}),yr&&s.jsxs(s.Fragment,{children:[Xn&&s.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[s.jsx(ut,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Bt&&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: ",Bt.message]}),(()=>{const xe=br?.filter(Ne=>Ne.ha_entity_id&&Ne.id!==t?.id).map(Ne=>Ne.ha_entity_id)||[],Le=(vr||[]).filter(Ne=>!xe.includes(Ne.entity_id)),Ie=vr?.find(Ne=>Ne.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:"Select Entity *"}),s.jsxs("div",{className:"relative",children:[s.jsx(_a,{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:Ae?se:Ie?`${Ie.friendly_name} (${Ie.entity_id})`:"",onChange:Ne=>{de(Ne.target.value),Ae||pe(!0)},onFocus:()=>{pe(!0),de("")},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&&!Ae&&s.jsx("button",{type:"button",onClick:()=>{y(""),de("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Xn&&s.jsx(ut,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),Ae&&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:[Xn&&s.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[s.jsx(ut,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Xn&&Le.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:me?`No entities found matching "${me}"`:"No entities available"}),!Xn&&Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{y(Ne.entity_id),pe(!1),de(""),o||l(Ne.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Ne.entity_id===x?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[s.jsx("span",{children:Ne.entity_id}),s.jsx("span",{className:Ne.state==="on"?"text-bambu-green":"",children:Ne.state})]})]},Ne.entity_id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:me?`Searching all entities (${Le.length} found)`:`Showing switch, light, input_boolean (${Le.length} available)`})]})})(),x&&In&&In.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 xe=In.filter(Ne=>Ne.unit_of_measurement==="W"||Ne.unit_of_measurement==="kW"||Ne.unit_of_measurement==="mW"),Le=_e?xe.filter(Ne=>Ne.entity_id.toLowerCase().includes(_e.toLowerCase())||Ne.friendly_name.toLowerCase().includes(_e.toLowerCase())):xe,Ie=In.find(Ne=>Ne.entity_id===Z);return s.jsxs("div",{ref:H,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(_a,{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:ze?_e:Ie?`${Ie.friendly_name} (${Ie.state} ${Ie.unit_of_measurement})`:"",onChange:Ne=>{oe(Ne.target.value),ze||V(!0)},onFocus:()=>{V(!0),oe("")},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"}),Z&&!ze&&s.jsx("button",{type:"button",onClick:()=>{ee(""),oe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),ze&&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:()=>{ee(""),V(!1),oe("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{ee(Ne.entity_id),V(!1),oe("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ne.entity_id===Z?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ne.entity_id," • ",Ne.state," ",Ne.unit_of_measurement]})]},Ne.entity_id)),Le.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=In.filter(Ne=>Ne.unit_of_measurement==="kWh"||Ne.unit_of_measurement==="Wh"||Ne.unit_of_measurement==="MWh"),Le=K?xe.filter(Ne=>Ne.entity_id.toLowerCase().includes(K.toLowerCase())||Ne.friendly_name.toLowerCase().includes(K.toLowerCase())):xe,Ie=In.find(Ne=>Ne.entity_id===ne);return s.jsxs("div",{ref:ke,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(_a,{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:Q?K:Ie?`${Ie.friendly_name} (${Ie.state} ${Ie.unit_of_measurement})`:"",onChange:Ne=>{U(Ne.target.value),Q||le(!0)},onFocus:()=>{le(!0),U("")},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"}),ne&&!Q&&s.jsx("button",{type:"button",onClick:()=>{z(""),U("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Q&&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(""),le(!1),U("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{z(Ne.entity_id),le(!1),U("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ne.entity_id===ne?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ne.entity_id," • ",Ne.state," ",Ne.unit_of_measurement]})]},Ne.entity_id)),Le.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=In.filter(Ne=>Ne.unit_of_measurement==="kWh"||Ne.unit_of_measurement==="Wh"||Ne.unit_of_measurement==="MWh"),Le=Re?xe.filter(Ne=>Ne.entity_id.toLowerCase().includes(Re.toLowerCase())||Ne.friendly_name.toLowerCase().includes(Re.toLowerCase())):xe,Ie=In.find(Ne=>Ne.entity_id===G);return s.jsxs("div",{ref:$,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(_a,{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:B?Re:Ie?`${Ie.friendly_name} (${Ie.state} ${Ie.unit_of_measurement})`:"",onChange:Ne=>{Ce(Ne.target.value),B||I(!0)},onFocus:()=>{I(!0),Ce("")},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"}),G&&!B&&s.jsx("button",{type:"button",onClick:()=>{ae(""),Ce("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),B&&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:()=>{ae(""),I(!1),Ce("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{ae(Ne.entity_id),I(!1),Ce("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ne.entity_id===G?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ne.entity_id," • ",Ne.state," ",Ne.unit_of_measurement]})]},Ne.entity_id)),Le.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:[!er?.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)."]}),er?.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:b,onChange:xe=>v(xe.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:N,onChange:xe=>S(xe.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),s.jsx("input",{type:"text",value:A,onChange:xe=>T(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"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:xe=>E(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:xe=>k(xe.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:xe=>F(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"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:O,onChange:xe=>X(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:xe=>q(xe.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:Y,onChange:xe=>W(xe.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.jsx("p",{className:"text-xs text-bambu-gray",children:'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:xe=>{u(xe.target.value),Ye(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(Me,{type:"button",variant:"secondary",onClick:()=>We.mutate(),disabled:!c.trim()||We.isPending,children:[We.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Vp,{className:"w-4 h-4"}),"Test"]})]})]}),i==="tasmota"&&be&&s.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${be.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:be.success?s.jsxs(s.Fragment,{children:[s.jsx(Dn,{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:[be.device_name&&`Device: ${be.device_name} - `,"State: ",be.state]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Pf,{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:xe=>l(xe.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:xe=>f(xe.target.value),placeholder:"admin",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),s.jsx("input",{type:"password",value:m,onChange:xe=>g(xe.target.value),placeholder:"********",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),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:te??"",onChange:xe=>ye(xe.target.value?Number(xe.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[s.jsx("option",{value:"",children:"No printer (manual control only)"}),at?.map(xe=>s.jsx("option",{value:xe.id,children:xe.name},xe.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(df,{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:qe,onChange:xe=>Xe(xe.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"})]})]}),qe&&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:ce,onChange:xe=>ie(xe.target.value),placeholder:"e.g. 200",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),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:Te,onChange:xe=>Ve(xe.target.value),placeholder:"e.g. 10",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),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(Wn,{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:it,onChange:xe=>re(xe.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"})]})]}),it&&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:De,onChange:xe=>we(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),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:Oe,onChange:xe=>Ue(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),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(z2,{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:je,onChange:xe=>Je(xe.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(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:he,className:"flex-1",children:[he?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function $n({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 rKe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function iKe({provider:t,onEdit:e}){const n=an(),[r,i]=w.useState(!1),[a,o]=w.useState(!1),[l,c]=w.useState(null),{data:u}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),d=u?.find(y=>y.id===t.printer_id),f=ht({mutationFn:y=>fe.updateNotificationProvider(t.id,y),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),m=ht({mutationFn:()=>fe.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),g=ht({mutationFn:()=>fe.testNotificationProvider(t.id),onSuccess:y=>{c(y),n.invalidateQueries({queryKey:["notification-providers"]})},onError:y=>{c({success:!1,message:y.message})}}),x=y=>y||"";return s.jsxs(s.Fragment,{children:[s.jsx(wt,{className:"relative",children:s.jsxs(Nt,{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(df,{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:rKe[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: ",og(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(vi(t.last_error_at)?.getTime()||0)>(vi(t.last_success)?.getTime()||0))&&s.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),s.jsx($n,{checked:t.enabled,onChange:y=>f.mutate({enabled:y})})]})]}),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(yw,{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(ii,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),s.jsx("div",{className:"mb-3",children:s.jsxs(Me,{size:"sm",variant:"secondary",disabled:g.isPending,onClick:()=>{c(null),g.mutate()},className:"w-full",children:[g.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(mD,{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(Dn,{className:"w-4 h-4"}):s.jsx(ea,{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($d,{className:"w-4 h-4"}),"Event Settings"]}),a?s.jsx(su,{className:"w-4 h-4"}):s.jsx(Pi,{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($n,{checked:t.enabled,onChange:y=>f.mutate({enabled:y})})]}),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($n,{checked:t.on_print_start,onChange:y=>f.mutate({on_print_start:y})})]}),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($n,{checked:t.on_plate_not_empty??!0,onChange:y=>f.mutate({on_plate_not_empty:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),s.jsx($n,{checked:t.on_print_complete,onChange:y=>f.mutate({on_print_complete:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),s.jsx($n,{checked:t.on_print_failed,onChange:y=>f.mutate({on_print_failed:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),s.jsx($n,{checked:t.on_print_stopped,onChange:y=>f.mutate({on_print_stopped:y})})]}),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($n,{checked:t.on_print_progress,onChange:y=>f.mutate({on_print_progress:y})})]})]}),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($n,{checked:t.on_printer_offline,onChange:y=>f.mutate({on_printer_offline:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),s.jsx($n,{checked:t.on_printer_error,onChange:y=>f.mutate({on_printer_error:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),s.jsx($n,{checked:t.on_filament_low,onChange:y=>f.mutate({on_filament_low:y})})]}),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($n,{checked:t.on_maintenance_due??!1,onChange:y=>f.mutate({on_maintenance_due:y})})]})]}),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($n,{checked:t.on_ams_humidity_high??!1,onChange:y=>f.mutate({on_ams_humidity_high:y})})]}),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($n,{checked:t.on_ams_temperature_high??!1,onChange:y=>f.mutate({on_ams_temperature_high:y})})]})]}),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($n,{checked:t.on_ams_ht_humidity_high??!1,onChange:y=>f.mutate({on_ams_ht_humidity_high:y})})]}),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($n,{checked:t.on_ams_ht_temperature_high??!1,onChange:y=>f.mutate({on_ams_ht_temperature_high:y})})]})]}),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(yw,{className:"w-4 h-4 text-purple-400"}),s.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),s.jsx($n,{checked:t.quiet_hours_enabled,onChange:y=>f.mutate({quiet_hours_enabled:y})})]}),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(Wn,{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(ii,{className:"w-4 h-4 text-emerald-400"}),s.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),s.jsx($n,{checked:t.daily_digest_enabled,onChange:y=>f.mutate({daily_digest_enabled:y})})]}),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(Wn,{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(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx($2,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),r&&s.jsx(Fn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{m.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const ZG=[{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 aKe({provider:t,onClose:e}){const n=an(),r=!!t,[i,a]=w.useState(t?.name||""),[o,l]=w.useState(t?.provider_type||"email"),[c,u]=w.useState(t?.printer_id||null),[d,f]=w.useState(t?.quiet_hours_enabled||!1),[m,g]=w.useState(t?.quiet_hours_start||"22:00"),[x,y]=w.useState(t?.quiet_hours_end||"07:00"),[b,v]=w.useState(t?.daily_digest_enabled||!1),[N,S]=w.useState(t?.daily_digest_time||"08:00"),[A,T]=w.useState(t?.on_print_start??!1),[C,E]=w.useState(t?.on_print_complete??!0),[D,k]=w.useState(t?.on_print_failed??!0),[R,F]=w.useState(t?.on_print_stopped??!0),[O,X]=w.useState(t?.on_print_progress??!1),[j,q]=w.useState(t?.on_printer_offline??!1),[Y,W]=w.useState(t?.on_printer_error??!1),[Z,ee]=w.useState(t?.on_filament_low??!1),[ne,z]=w.useState(t?.on_maintenance_due??!1),[G,ae]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([U,Q])=>[U,String(Q)])):{}),[se,de]=w.useState(null),[me,ue]=w.useState(null),{data:Ae}=ct({queryKey:["printers"],queryFn:fe.getPrinters});w.useEffect(()=>{const U=Q=>{Q.key==="Escape"&&e()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[e]);const pe=ht({mutationFn:()=>fe.testNotificationConfig({provider_type:o,config:G}),onSuccess:U=>{de(U),ue(null)},onError:U=>{de({success:!1,message:U.message})}}),Ee=ht({mutationFn:U=>fe.createNotificationProvider(U),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:U=>{ue(U.message)}}),_e=ht({mutationFn:U=>fe.updateNotificationProvider(t.id,U),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:U=>{ue(U.message)}}),oe=U=>{if(U.preventDefault(),ue(null),!i.trim()){ue("Name is required");return}const Q=H(o);for(const ke of Q)if(!G[ke.key]?.trim()){ue(`${ke.label} is required`);return}const le={name:i.trim(),provider_type:o,config:G,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?m:null,quiet_hours_end:d?x:null,daily_digest_enabled:b,daily_digest_time:b?N:null,on_print_start:A,on_print_complete:C,on_print_failed:D,on_print_stopped:R,on_print_progress:O,on_printer_offline:j,on_printer_error:Y,on_filament_low:Z,on_maintenance_due:ne};r?_e.mutate(le):Ee.mutate(le)},ze=Ee.isPending||_e.isPending,V=U=>{switch(U){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:Q=>Q.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:Q=>Q.payload_format!=="slack"}];default:return[]}},H=U=>V(U).filter(Q=>Q.required),K=V(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: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.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(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:oe,className:"p-6 space-y-4",children:[me&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:me}),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:U=>a(U.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:U=>{l(U.target.value),ae({}),de(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:ZG.map(U=>s.jsx("option",{value:U.value,children:U.label},U.value))}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ZG.find(U=>U.value===o)?.description})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),K.filter(U=>!("showIf"in U)||U.showIf?.(G)!==!1).map(U=>s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[U.label," ",U.required&&"*"]}),U.type==="select"&&"options"in U&&U.options?s.jsx("select",{value:G[U.key]||U.options[0]?.value||"",onChange:Q=>{ae({...G,[U.key]:Q.target.value}),de(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:U.options.map(Q=>s.jsx("option",{value:Q.value,children:Q.label},Q.value))}):s.jsx("input",{type:U.type,value:G[U.key]||"",onChange:Q=>{ae({...G,[U.key]:Q.target.value}),de(null)},placeholder:U.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"})]},U.key))]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>{de(null),pe.mutate()},disabled:pe.isPending||!G[H(o)[0]?.key],className:"flex-1",children:[pe.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(mD,{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(Dn,{className:"w-5 h-5"}),s.jsx("span",{children:se.message})]}):s.jsxs(s.Fragment,{children:[s.jsx(ea,{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:U=>u(U.target.value?Number(U.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"}),Ae?.map(U=>s.jsx("option",{value:U.id,children:U.name},U.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($n,{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:m,onChange:U=>g(U.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:U=>y(U.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($n,{checked:b,onChange:v})]}),b&&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:N,onChange:U=>S(U.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($n,{checked:A,onChange:T})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Complete"}),s.jsx($n,{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($n,{checked:D,onChange:k})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Stopped"}),s.jsx($n,{checked:R,onChange:F})]}),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($n,{checked:O,onChange:X})]})]})]}),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($n,{checked:j,onChange:q})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Error"}),s.jsx($n,{checked:Y,onChange:W})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),s.jsx($n,{checked:Z,onChange:ee})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),s.jsx($n,{checked:ne,onChange:z})]})]})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:ze,className:"flex-1",children:[ze?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function sKe({template:t,onClose:e}){const n=an(),r=w.useRef(null),[i,a]=w.useState(t.title_template),[o,l]=w.useState(t.body_template),[c,u]=w.useState(null),[d,f]=w.useState(!0),{data:m}=ct({queryKey:["template-variables"],queryFn:fe.getTemplateVariables}),g=m?.find(T=>T.event_type===t.event_type),{data:x,isLoading:y}=ct({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>fe.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});w.useEffect(()=>{const T=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[e]);const b=ht({mutationFn:T=>fe.updateNotificationTemplate(t.id,T),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:T=>{u(T.message)}}),v=ht({mutationFn:()=>fe.resetNotificationTemplate(t.id),onSuccess:T=>{a(T.title_template),l(T.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:T=>{u(T.message)}}),N=T=>{if(T.preventDefault(),u(null),!i.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}b.mutate({title_template:i,body_template:o})},S=T=>{const C=r.current;if(!C)return;const E=C.selectionStart,D=C.selectionEnd,k=o,R=k.substring(0,E),F=k.substring(D),O=R+`{${T}}`+F;l(O),setTimeout(()=>{C.focus();const X=E+T.length+2;C.setSelectionRange(X,X)},0)},A=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(Ut,{className:"w-5 h-5 text-bambu-gray"})})]}),s.jsxs("form",{onSubmit:N,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:T=>a(T.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:T=>l(T.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..."})]}),g&&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:g.variables.map(T=>s.jsxs("button",{type:"button",onClick:()=>S(T),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(Jn,{className:"w-3 h-3"}),T]},T))}),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(ou,{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:y?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[s.jsx(ut,{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(Me,{type:"button",variant:"ghost",onClick:()=>v.mutate(),disabled:v.isPending,className:"text-orange-400 hover:text-orange-300",children:[v.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(Zf,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),s.jsxs(Me,{onClick:N,disabled:b.isPending||!A,children:[b.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(xs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const oKe={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"},lKe={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 cKe({onClose:t}){const e=an(),{showToast:n}=Hn(),[r,i]=w.useState(7),[a,o]=w.useState(null),[l,c]=w.useState(!1),{data:u}=ct({queryKey:["settings"],queryFn:fe.getSettings}),d=u?.time_format||"system",{data:f,isLoading:m,refetch:g,isRefetching:x}=ct({queryKey:["notification-logs",r,l],queryFn:()=>fe.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:y}=ct({queryKey:["notification-log-stats",r],queryFn:()=>fe.getNotificationLogStats(r)}),b=ht({mutationFn:()=>fe.clearNotificationLogs(30),onSuccess:N=>{n(N.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:N=>{n(`Failed to clear logs: ${N.message}`,"error")}}),v=N=>{const S=vi(N);if(!S)return"";const T=new Date().getTime()-S.getTime();return T<6e4?"Just now":T<36e5?`${Math.floor(T/6e4)}m ago`:T<864e5?`${Math.floor(T/36e5)}h ago`:S.toLocaleDateString()+" "+Cfe(S,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(f0,{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:"×"})]}),y&&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:y.total})," notifications"]}),s.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[s.jsx(Dn,{className:"w-4 h-4"}),y.success_count," sent"]}),y.failure_count>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(ea,{className:"w-4 h-4"}),y.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:N=>i(Number(N.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:N=>c(N.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(Me,{size:"sm",variant:"secondary",onClick:()=>g(),disabled:x,children:[x?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Refresh"]}),s.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>b.mutate(),disabled:b.isPending,className:"text-red-400 hover:text-red-300",children:[b.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"}),"Clear Old"]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:m?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):f&&f.length>0?s.jsx("div",{className:"space-y-2",children:f.map(N=>s.jsx(uKe,{log:N,isExpanded:a===N.id,onToggle:()=>o(a===N.id?null:N.id),formatDate:v,formatFullDate:S=>lg(S,d)},N.id))}):s.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[s.jsx(f0,{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 uKe({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(Dn,{className:"w-4 h-4 text-bambu-green shrink-0"}):s.jsx(ea,{className:"w-4 h-4 text-red-400 shrink-0"}),s.jsx("span",{className:`text-xs font-medium ${lKe[t.event_type]||"text-bambu-gray"}`,children:oKe[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(su,{className:"w-4 h-4 text-bambu-gray shrink-0"}):s.jsx(Pi,{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 dKe(){const t=await fetch("/api/v1/settings/spoolman");if(!t.ok)throw new Error("Failed to load Spoolman settings");return t.json()}async function hKe(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 fKe(){const t=an(),[e,n]=w.useState(!1),[r,i]=w.useState(""),[a,o]=w.useState("auto"),[l,c]=w.useState(!1),[u,d]=w.useState("all"),[f,m]=w.useState(!1),[g,x]=w.useState(!1),{data:y,isLoading:b}=ct({queryKey:["spoolman-settings"],queryFn:dKe}),{data:v,isLoading:N,refetch:S}=ct({queryKey:["spoolman-status"],queryFn:fe.getSpoolmanStatus,refetchInterval:3e4}),{data:A}=ct({queryKey:["printers"],queryFn:fe.getPrinters});w.useEffect(()=>{y&&(n(y.spoolman_enabled==="true"),i(y.spoolman_url||""),o(y.spoolman_sync_mode||"auto"),m(!0))},[y]),w.useEffect(()=>{if(!f||!y)return;if(y.spoolman_enabled==="true"!==e||(y.spoolman_url||"")!==r||(y.spoolman_sync_mode||"auto")!==a){const q=setTimeout(()=>{T.mutate()},500);return()=>clearTimeout(q)}},[e,r,a,f]);const T=ht({mutationFn:()=>hKe({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=ht({mutationFn:fe.connectSpoolman,onSuccess:()=>{S()}}),E=ht({mutationFn:fe.disconnectSpoolman,onSuccess:()=>{S()}}),D=ht({mutationFn:fe.syncAllPrintersAms,onSuccess:j=>{j.success}}),k=ht({mutationFn:j=>fe.syncPrinterAms(j),onSuccess:j=>{j.success}}),R=()=>{u==="all"?D.mutate():k.mutate(u)},F=D.isPending||k.isPending,O=u==="all"?D.data:k.data,X=u==="all"?D.isSuccess:k.isSuccess;return b?s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Qc,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]})}),s.jsx(Nt,{children:s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Qc,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]}),T.isPending&&s.jsx(ut,{className:"w-4 h-4 text-bambu-green animate-spin"}),l&&s.jsx(Ya,{className:"w-4 h-4 text-bambu-green"})]})}),s.jsxs(Nt,{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(zl,{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:"}),N?s.jsx(ut,{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(Ya,{className:"w-4 h-4"}),"Connected"]}):s.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[s.jsx(Ut,{className:"w-4 h-4"}),"Disconnected"]})]}),s.jsx("div",{className:"flex gap-2",children:v?.connected?s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(pde,{className:"w-4 h-4"}),"Disconnect"]}):s.jsxs(Me,{size:"sm",onClick:()=>C.mutate(),disabled:C.isPending||!r,children:[C.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Ll,{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"}),A?.map(j=>s.jsx("option",{value:j.id,children:j.name},j.id))]}),s.jsx(Pi,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:R,disabled:F,children:[F?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Sync"]})]})]}),X&&O&&s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx("div",{className:`p-2 rounded text-sm ${O.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:O.success?`Synced ${O.synced_count} spool${O.synced_count!==1?"s":""} successfully`:`Synced ${O.synced_count} spool${O.synced_count!==1?"s":""} with ${O.errors.length} error${O.errors.length!==1?"s":""}`}),O.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(Nn,{className:"w-3.5 h-3.5"}),s.jsxs("span",{className:"font-medium",children:[O.skipped_count," spool",O.skipped_count!==1?"s":""," skipped"]})]}),O.skipped_count>5&&s.jsx("button",{onClick:()=>x(!g),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:g?"Show less":"Show all"})]}),s.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(g?O.skipped:O.skipped.slice(0,5)).map((j,q)=>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]})]},q)),!g&&O.skipped_count>5&&s.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",O.skipped_count-5," more"]})]})]}),O.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:O.errors.map((j,q)=>s.jsx("li",{children:j},q))})]})]})]})]})]})}function mKe({link:t,onClose:e}){const n=an(),{mode:r}=ih(),i=!!t,a=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.url||""),[d,f]=w.useState(t?.icon||"link"),[m,g]=w.useState(!!t?.custom_icon),[x,y]=w.useState(t?.custom_icon?fe.getExternalLinkIconUrl(t.id):null),[b,v]=w.useState(null),[N,S]=w.useState(null);w.useEffect(()=>{const F=O=>{O.key==="Escape"&&e()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[e]);const A=ht({mutationFn:async F=>{const O=await fe.createExternalLink(F);return b?await fe.uploadExternalLinkIcon(O.id,b):O},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:F=>{S(F.message)}}),T=ht({mutationFn:async F=>{let O=await fe.updateExternalLink(t.id,F);return b?O=await fe.uploadExternalLinkIcon(t.id,b):!m&&t?.custom_icon&&(O=await fe.deleteExternalLinkIcon(t.id)),O},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:F=>{S(F.message)}}),C=F=>{const O=F.target.files?.[0];if(O){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(O.type)){S("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(O.size>1024*1024){S("Image file must be less than 1MB");return}v(O),g(!0);const j=new FileReader;j.onload=q=>{y(q.target?.result)},j.readAsDataURL(O)}},E=()=>{v(null),y(null),g(!1),a.current&&(a.current.value="")},D=F=>{if(F.preventDefault(),S(null),!o.trim()){S("Name is required");return}if(!c.trim()){S("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){S("URL must start with http:// or https://");return}const O={name:o.trim(),url:c.trim(),icon:d};i?T.mutate(O):A.mutate(O)},k=A.isPending||T.isPending,R=q2(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:F=>F.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:m&&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(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:D,className:"p-6 space-y-4",children:[N&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:N}),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:F=>l(F.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:F=>u(F.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}),m&&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(ln,{className:"w-4 h-4"})})]}):s.jsxs(Me,{type:"button",variant:"secondary",size:"sm",onClick:()=>a.current?.click(),children:[s.jsx(di,{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."})]}),!m&&s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),s.jsx(Sfe,{value:d,onChange:f})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:k,className:"flex-1",children:[k?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function pKe(){const t=an(),[e,n]=w.useState(!1),[r,i]=w.useState(null),[a,o]=w.useState(null),[l,c]=w.useState(null),{data:u,isLoading:d}=ct({queryKey:["external-links"],queryFn:fe.getExternalLinks}),f=ht({mutationFn:N=>fe.deleteExternalLink(N),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),m=ht({mutationFn:N=>fe.reorderExternalLinks(N),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),g=(N,S)=>{c(S),N.dataTransfer.effectAllowed="move"},x=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},y=(N,S)=>{if(N.preventDefault(),l===null||l===S||!u)return;const A=u.map(D=>D.id),T=A.indexOf(l),C=A.indexOf(S);if(T===-1||C===-1)return;const E=[...A];E.splice(T,1),E.splice(C,0,l),m.mutate(E),c(null)},b=N=>{o(N)},v=()=>{a&&(f.mutate(a.id),o(null))};return s.jsxs(s.Fragment,{children:[s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ll,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),s.jsxs(Me,{size:"sm",onClick:()=>n(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Link"]})]})}),s.jsxs(Nt,{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(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?s.jsx("div",{className:"space-y-2",children:u.map(N=>{const S=q2(N.icon);return s.jsxs("div",{draggable:!0,onDragStart:A=>g(A,N.id),onDragOver:x,onDrop:A=>y(A,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${l===N.id?"opacity-50":""}`,children:[s.jsx(ag,{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(S,{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:N.name}),s.jsx(Ur,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),s.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),s.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s.jsx("button",{onClick:()=>i(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:"Edit",children:s.jsx(ia,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>b(N),disabled:f.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:"Delete",children:s.jsx(ln,{className:"w-4 h-4"})})]})]},N.id)})}):s.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[s.jsx(Ll,{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(mKe,{link:r,onClose:()=>{n(!1),i(null)}}),a&&s.jsx(Fn,{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 gKe(){const t=an(),{showToast:e}=Hn(),[n,r]=w.useState(!1),[i,a]=w.useState(""),[o,l]=w.useState("immediate"),[c,u]=w.useState("3DPrinter-X1-Carbon"),[d,f]=w.useState(!1),[m,g]=w.useState(null),{data:x,isLoading:y}=ct({queryKey:["virtual-printer-settings"],queryFn:z1.getSettings,refetchInterval:1e4}),{data:b}=ct({queryKey:["virtual-printer-models"],queryFn:z1.getModels});w.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=ht({mutationFn:D=>z1.updateSettings(D),onSuccess:()=>{t.invalidateQueries({queryKey:["virtual-printer-settings"]}),e("Virtual printer settings updated"),g(null)},onError:D=>{if(e(D.message||"Failed to update settings","error"),x){r(x.enabled);const k=x.mode==="queue"?"review":x.mode;l(k==="print_queue"||k==="review"?k:"immediate"),u(x.model)}g(null)}}),N=()=>{const D=!n;if(D&&!i&&!x?.access_code_set){e("Please set an access code first","error");return}r(D),g("toggle"),v.mutate({enabled:D,access_code:i||void 0,mode:o})},S=()=>{if(!i){e("Access code cannot be empty","error");return}if(i.length!==8){e("Access code must be exactly 8 characters","error");return}g("accessCode"),v.mutate({access_code:i}),a("")},A=D=>{l(D),g("mode"),v.mutate({mode:D})},T=D=>{u(D),g("model"),v.mutate({model:D})};if(y)return s.jsx(wt,{children:s.jsx(Nt,{className:"py-8 flex justify-center",children:s.jsx(ut,{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(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(qr,{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(Nt,{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:N,disabled:m==="toggle",className:`relative w-12 h-6 rounded-full transition-colors ${n?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${m==="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=>T(D.target.value),disabled:m==="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:b?.models&&Object.entries(b.models).sort(([,D],[,k])=>D.localeCompare(k)).map(([D,k])=>s.jsx("option",{value:D,children:k},D))}),s.jsx(Pi,{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(zl,{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(Ya,{className:"w-4 h-4"}),"Access code is set"]}):s.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[s.jsx(Nn,{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(D2,{className:"w-4 h-4"}):s.jsx(ou,{className:"w-4 h-4"})})]}),s.jsx(Me,{onClick:S,disabled:!i||m==="accessCode",variant:"primary",children:m==="accessCode"?s.jsx(ut,{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:()=>A("immediate"),disabled:m==="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:()=>A("review"),disabled:m==="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:()=>A("print_queue"),disabled:m==="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(wt,{className:"border-l-4 border-l-yellow-500",children:s.jsx(Nt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Nn,{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(Ur,{className:"w-4 h-4"}),"Read the setup guide before enabling"]})]})]})})}),s.jsx(wt,{children:s.jsx(Nt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(zl,{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(wt,{children:[s.jsx(Qn,{children:s.jsx("h3",{className:"text-md font-semibold text-white",children:"Status Details"})}),s.jsx(Nt,{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})]})]})})]})]})]})}const L1=[{id:"settings",labelKey:"backup.categories.settings",defaultLabel:"App Settings",icon:s.jsx(V2,{className:"w-4 h-4"}),default:!0,description:"Language, theme, update preferences"},{id:"notifications",labelKey:"backup.categories.notifications",defaultLabel:"Notification Providers",icon:s.jsx(df,{className:"w-4 h-4"}),default:!0,description:"ntfy, Pushover, Discord, etc."},{id:"templates",labelKey:"backup.categories.templates",defaultLabel:"Notification Templates",icon:s.jsx(Ga,{className:"w-4 h-4"}),default:!0,description:"Custom message templates"},{id:"smart_plugs",labelKey:"backup.categories.smartPlugs",defaultLabel:"Smart Plugs",icon:s.jsx(Gs,{className:"w-4 h-4"}),default:!0,description:"Tasmota plug configurations"},{id:"external_links",labelKey:"backup.categories.externalLinks",defaultLabel:"External Links",icon:s.jsx(zg,{className:"w-4 h-4"}),default:!0,description:"Sidebar links to external services"},{id:"printers",labelKey:"backup.categories.printers",defaultLabel:"Printers",icon:s.jsx(qr,{className:"w-4 h-4"}),default:!1,description:"Printer info (access codes excluded)"},{id:"plate_calibration",labelKey:"backup.categories.plateCalibration",defaultLabel:"Plate Detection",icon:s.jsx(Cf,{className:"w-4 h-4"}),default:!1,description:"Empty plate reference images",requiresPrinters:!0},{id:"filaments",labelKey:"backup.categories.filaments",defaultLabel:"Filament Inventory",icon:s.jsx(dD,{className:"w-4 h-4"}),default:!1,description:"Filament types and costs"},{id:"maintenance",labelKey:"backup.categories.maintenance",defaultLabel:"Maintenance Types",icon:s.jsx(Hd,{className:"w-4 h-4"}),default:!1,description:"Custom maintenance schedules"},{id:"archives",labelKey:"backup.categories.archives",defaultLabel:"Print Archives",icon:s.jsx(Ka,{className:"w-4 h-4"}),default:!1,description:"All print data + files (3MF, thumbnails, photos)"},{id:"projects",labelKey:"backup.categories.projects",defaultLabel:"Projects",icon:s.jsx(wa,{className:"w-4 h-4"}),default:!1,description:"Projects, BOM items, and attachments"},{id:"pending_uploads",labelKey:"backup.categories.pendingUploads",defaultLabel:"Pending Uploads",icon:s.jsx(di,{className:"w-4 h-4"}),default:!1,description:"Virtual printer uploads awaiting review"},{id:"api_keys",labelKey:"backup.categories.apiKeys",defaultLabel:"API Keys",icon:s.jsx(ef,{className:"w-4 h-4"}),default:!1,description:"Webhook API keys (new keys generated on import)"}];function xKe({onClose:t,onExport:e}){const{t:n}=Lg(),[r,i]=w.useState(()=>{const x={};return L1.forEach(y=>{x[y.id]=y.default}),x}),[a,o]=w.useState(!1),[l,c]=w.useState(!1);w.useEffect(()=>{const x=y=>{y.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]);const u=x=>{i(y=>({...y,[x]:!y[x]}))},d=()=>{const x={};L1.forEach(y=>{x[y.id]=!0}),i(x)},f=()=>{const x={};L1.forEach(y=>{x[y.id]=!1}),i(x)},m=Object.values(r).filter(Boolean).length,g=async()=>{c(!0);try{await e({...r,access_codes:a&&r.printers})}finally{c(!1)}};return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:l?void 0:t,children:s.jsx(wt,{className:"w-full max-w-lg",onClick:x=>x.stopPropagation(),children:s.jsxs(Nt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-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:s.jsx($r,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:n("backup.exportTitle",{defaultValue:"Export Backup"})}),s.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.selectCategories",{defaultValue:"Select data to include"})})]})]}),s.jsx("button",{onClick:t,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx(Ut,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"flex gap-2 px-4 pt-4",children:[s.jsx("button",{onClick:d,disabled:l,className:"text-sm text-bambu-green hover:text-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed",children:n("common.selectAll",{defaultValue:"Select All"})}),s.jsx("span",{className:"text-bambu-gray",children:"|"}),s.jsx("button",{onClick:f,disabled:l,className:"text-sm text-bambu-gray hover:text-white disabled:opacity-50 disabled:cursor-not-allowed",children:n("common.selectNone",{defaultValue:"Select None"})})]}),s.jsx("div",{className:`p-4 space-y-2 max-h-[400px] overflow-y-auto ${l?"opacity-50 pointer-events-none":""}`,children:L1.map(x=>{const y=l||x.requiresPrinters&&!r.printers;return s.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg transition-colors ${y?"cursor-not-allowed opacity-50":"cursor-pointer"} ${r[x.id]&&!y?"bg-bambu-green/10 border border-bambu-green/30":"bg-bambu-dark hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[s.jsx("input",{type:"checkbox",checked:r[x.id]&&!y,onChange:()=>u(x.id),disabled:y,className:"w-4 h-4 rounded border-bambu-gray bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),s.jsx("div",{className:`${r[x.id]&&!y?"text-bambu-green":"text-bambu-gray"}`,children:x.icon}),s.jsxs("div",{className:"flex-1",children:[s.jsx("div",{className:"text-white text-sm font-medium",children:n(x.labelKey,{defaultValue:x.defaultLabel})}),s.jsx("div",{className:"text-xs text-bambu-gray",children:x.requiresPrinters&&!r.printers?"Requires Printers to be selected":x.description})]})]},x.id)})}),r.archives&&s.jsx("div",{className:"mx-4 mb-2 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(Ka,{className:"w-4 h-4 text-yellow-500 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-yellow-200 dark:text-yellow-200 text-yellow-700",children:[s.jsx("span",{className:"font-medium",children:"ZIP file will be created."}),s.jsx("span",{className:"text-yellow-600 dark:text-yellow-200/70",children:" Includes all 3MF files, thumbnails, timelapses, and photos. This may take a while and result in a large file."})]})]})}),r.printers&&s.jsxs("div",{className:"mx-4 mb-2 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(ef,{className:"w-4 h-4 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-white",children:"Include Access Codes"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"For transferring to another machine"})]})]}),s.jsx($n,{checked:a,onChange:o})]}),a&&s.jsx("div",{className:"mt-2 p-2 rounded bg-orange-500/10 border border-orange-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[s.jsx(Nn,{className:"w-3 h-3 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0"}),s.jsx("span",{className:"text-orange-700 dark:text-orange-200",children:"Access codes will be included in plain text. Keep this backup file secure!"})]})})]}),s.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:n("backup.selectedCount",{count:m,defaultValue:`${m} categories selected`})}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Me,{variant:"secondary",onClick:t,disabled:l,children:n("common.cancel",{defaultValue:"Cancel"})}),s.jsx(Me,{onClick:g,disabled:m===0||l,className:"bg-bambu-green hover:bg-bambu-green-dark disabled:opacity-50 disabled:cursor-not-allowed min-w-[100px]",children:l?s.jsxs(s.Fragment,{children:[s.jsx(ut,{className:"w-4 h-4 mr-2 animate-spin"}),n("backup.exporting",{defaultValue:"Exporting..."})]}):s.jsxs(s.Fragment,{children:[s.jsx($r,{className:"w-4 h-4 mr-2"}),n("backup.export",{defaultValue:"Export"})]})})]})]})]})})})}const JG={settings:"Settings",notification_providers:"Notification Providers",notification_templates:"Notification Templates",smart_plugs:"Smart Plugs",printers:"Printers",filaments:"Filaments",maintenance_types:"Maintenance Types",archives:"Archives",projects:"Projects",pending_uploads:"Pending Uploads",external_links:"External Links",api_keys:"API Keys"};function bKe({onClose:t,onRestore:e,onSuccess:n}){const[r,i]=w.useState("options"),[a,o]=w.useState(!1),[l,c]=w.useState(null),[u,d]=w.useState(null),[f,m]=w.useState(new Set),g=w.useRef(null);w.useEffect(()=>{const A=T=>{T.key==="Escape"&&r!=="restoring"&&(r==="result"&&u?.success&&n(),t())};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t,n,r,u]);const x=A=>{const T=A.target.files?.[0];T&&c(T)},y=async()=>{if(l){i("restoring");try{const A=await e(l,a);d(A),i("result")}catch{d({success:!1,message:"Failed to restore backup. Please check the file format."}),i("result")}}},b=()=>{u?.success&&n(),t()},v=A=>{m(T=>{const C=new Set(T);return C.has(A)?C.delete(A):C.add(A),C})},N=u?.restored?Object.values(u.restored).reduce((A,T)=>A+T,0)+(u.files_restored||0):0,S=u?.total_skipped||0;return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onMouseDown:A=>{A.target===A.currentTarget&&r!=="restoring"&&t()},children:s.jsx(wt,{className:"w-full max-w-lg",children:s.jsxs(Nt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-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 ${r==="result"&&u?.success?"bg-bambu-green/20 text-bambu-green":r==="result"&&!u?.success?"bg-red-500/20 text-red-500":"bg-blue-500/20 text-blue-500"}`,children:r==="result"&&u?.success?s.jsx(Dn,{className:"w-5 h-5"}):r==="result"&&!u?.success?s.jsx(Nn,{className:"w-5 h-5"}):s.jsx(di,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsxs("h3",{className:"text-lg font-semibold text-white",children:[r==="options"&&"Restore Backup",r==="restoring"&&"Restoring...",r==="result"&&(u?.success?"Restore Complete":"Restore Failed")]}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:[r==="options"&&"Import settings from a backup file",r==="restoring"&&"Please wait while your data is being restored",r==="result"&&u?.message]})]})]}),r!=="restoring"&&s.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx(Ut,{className:"w-5 h-5"})})]}),r==="options"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("input",{ref:g,type:"file",accept:".json,.zip",className:"hidden",onChange:x}),s.jsx("button",{type:"button",onClick:()=>g.current?.click(),className:`w-full p-4 border-2 border-dashed rounded-lg transition-colors ${l?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:l?s.jsxs("div",{className:"flex items-center justify-center gap-2 text-bambu-green",children:[s.jsx(Dn,{className:"w-5 h-5"}),s.jsx("span",{className:"font-medium",children:l.name})]}):s.jsxs("div",{className:"flex flex-col items-center gap-2 text-bambu-gray",children:[s.jsx(di,{className:"w-8 h-8"}),s.jsx("span",{children:"Click to select backup file (.json or .zip)"})]})})]}),s.jsx("div",{className:"p-3 rounded-lg bg-blue-500/10 border border-blue-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Nn,{className:"w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-blue-700 dark:text-blue-200",children:[s.jsx("p",{className:"font-medium mb-1",children:"How duplicate handling works:"}),s.jsxs("ul",{className:"text-blue-600 dark:text-blue-200/80 space-y-1 text-xs",children:[s.jsxs("li",{children:[s.jsx("strong",{children:"Printers"})," - matched by serial number"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Smart Plugs"})," - matched by IP address"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Notification Providers"})," - matched by name"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Filaments"})," - matched by name + type + brand"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Archives"})," - matched by content hash (always skipped)"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Pending Uploads"})," - matched by filename"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Settings & Templates"})," - always overwritten"]})]})]})]})}),s.jsx("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs("p",{className:"text-white font-medium flex items-center gap-2",children:[a?s.jsx(gr,{className:"w-4 h-4 text-orange-400"}):s.jsx(m0,{className:"w-4 h-4 text-bambu-gray"}),a?"Replace existing data":"Keep existing data"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a?"Overwrite items that already exist with backup data":"Only restore items that don't already exist"})]}),s.jsx($n,{checked:a,onChange:o})]})}),a&&s.jsx("div",{className:"p-3 rounded-lg bg-orange-500/10 border border-orange-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Nn,{className:"w-4 h-4 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-orange-700 dark:text-orange-200",children:[s.jsx("span",{className:"font-medium",children:"Caution:"})," Overwriting will replace your current configurations with data from the backup. Printer access codes are never overwritten for security."]})]})})]}),s.jsxs("div",{className:"flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:t,children:"Cancel"}),s.jsxs(Me,{type:"button",onClick:y,disabled:!l,className:"bg-bambu-green hover:bg-bambu-green-dark disabled:opacity-50",children:[s.jsx(di,{className:"w-4 h-4 mr-2"}),"Restore"]})]})]}),r==="restoring"&&s.jsxs("div",{className:"p-8 flex flex-col items-center gap-4",children:[s.jsx(ut,{className:"w-12 h-12 text-bambu-green animate-spin"}),s.jsx("p",{className:"text-bambu-gray",children:"Processing backup file..."})]}),r==="result"&&u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-4 space-y-4 max-h-[400px] overflow-y-auto",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{className:"p-3 rounded-lg bg-bambu-green/10 border border-bambu-green/30",children:[s.jsx("div",{className:"text-2xl font-bold text-bambu-green",children:N}),s.jsx("div",{className:"text-sm text-bambu-gray",children:"Items Restored"})]}),s.jsxs("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:[s.jsx("div",{className:"text-2xl font-bold text-yellow-500",children:S}),s.jsx("div",{className:"text-sm text-bambu-gray",children:"Items Skipped"})]})]}),u.restored&&Object.entries(u.restored).some(([,A])=>A>0)&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("h4",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green"}),"Restored"]}),s.jsxs("div",{className:"space-y-1",children:[Object.entries(u.restored).filter(([,A])=>A>0).map(([A,T])=>s.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded bg-bambu-dark",children:[s.jsx("span",{className:"text-white",children:JG[A]||A}),s.jsx("span",{className:"text-bambu-green font-medium",children:T})]},A)),(u.files_restored||0)>0&&s.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded bg-bambu-dark",children:[s.jsx("span",{className:"text-white",children:"Files (3MF, thumbnails, etc.)"}),s.jsx("span",{className:"text-bambu-green font-medium",children:u.files_restored})]})]})]}),u.skipped&&Object.entries(u.skipped).some(([,A])=>A>0)&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("h4",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(m0,{className:"w-4 h-4 text-yellow-500"}),"Skipped (already exist)"]}),s.jsx("div",{className:"space-y-1",children:Object.entries(u.skipped).filter(([,A])=>A>0).map(([A,T])=>{const C=u.skipped_details?.[A]||[],E=f.has(A);return s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>C.length>0&&v(A),className:`w-full flex items-center justify-between text-sm p-2 rounded bg-bambu-dark ${C.length>0?"hover:bg-bambu-dark-tertiary cursor-pointer":""}`,children:[s.jsxs("span",{className:"text-white flex items-center gap-2",children:[JG[A]||A,C.length>0&&(E?s.jsx(su,{className:"w-3 h-3"}):s.jsx(Pi,{className:"w-3 h-3"}))]}),s.jsx("span",{className:"text-yellow-500 font-medium",children:T})]}),E&&C.length>0&&s.jsxs("div",{className:"mt-1 ml-4 p-2 rounded bg-bambu-dark-tertiary text-xs text-bambu-gray space-y-1",children:[C.slice(0,10).map((D,k)=>s.jsx("div",{children:D},k)),C.length>10&&s.jsxs("div",{className:"text-bambu-gray/60",children:["...and ",C.length-10," more"]})]})]},A)})})]}),u.new_api_keys&&u.new_api_keys.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("h4",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(Nn,{className:"w-4 h-4 text-orange-500"}),"New API Keys Generated"]}),s.jsxs("div",{className:"p-3 rounded bg-orange-500/10 border border-orange-500/30",children:[s.jsx("p",{className:"text-xs text-orange-200 mb-2",children:"These keys are only shown once. Copy them now!"}),s.jsx("div",{className:"space-y-2",children:u.new_api_keys.map((A,T)=>s.jsxs("div",{className:"p-2 rounded bg-bambu-dark",children:[s.jsx("div",{className:"text-sm text-white font-medium mb-1",children:A.name}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-xs text-bambu-green bg-bambu-dark-tertiary px-2 py-1 rounded font-mono flex-1 break-all",children:A.key}),s.jsx("button",{onClick:()=>navigator.clipboard.writeText(A.key),className:"text-xs text-bambu-gray hover:text-white px-2 py-1 rounded bg-bambu-dark-tertiary",children:"Copy"})]})]},T))})]})]}),N===0&&S===0&&s.jsx("div",{className:"p-4 text-center text-bambu-gray",children:"No data was found to restore in the backup file."})]}),s.jsx("div",{className:"flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:s.jsx(Me,{onClick:b,children:"Close"})})]})]})})})}function eq({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(Dn,{className:"w-3 h-3"}),failed:s.jsx(ea,{className:"w-3 h-3"}),skipped:s.jsx(m0,{className:"w-3 h-3"}),running:s.jsx(ut,{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 tq(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}=Hn(),[n,r]=w.useState(""),[i,a]=w.useState(""),[o,l]=w.useState("main"),[c,u]=w.useState(!1),[d,f]=w.useState("daily"),[m,g]=w.useState(!0),[x,y]=w.useState(!0),[b,v]=w.useState(!1),[N,S]=w.useState(!0),[A,T]=w.useState(!1),[C,E]=w.useState(!1),[D,k]=w.useState(!1),[R,F]=w.useState(null),O=w.useRef(null),X=w.useRef(!1),{data:j,isLoading:q}=ct({queryKey:["github-backup-config"],queryFn:fe.getGitHubBackupConfig}),{data:Y}=ct({queryKey:["github-backup-status"],queryFn:fe.getGitHubBackupStatus,refetchInterval:oe=>oe.state.data?.is_running?500:1e4}),{data:W}=ct({queryKey:["github-backup-logs"],queryFn:()=>fe.getGitHubBackupLogs(20)}),{data:Z}=ct({queryKey:["cloud-status"],queryFn:fe.getCloudStatus}),{data:ee}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),ne=Jq({queries:(ee??[]).map(oe=>({queryKey:["printerStatus",oe.id],queryFn:()=>fe.getPrinterStatus(oe.id),staleTime:1e4,refetchInterval:3e4}))}),z=(ee??[]).map((oe,ze)=>({printer:oe,connected:ne[ze]?.data?.connected??!1})),G=z.length,ae=z.filter(oe=>oe.connected).length,se=G>0&&ae===0,de=ae>0&&ae{j&&(r(j.repository_url),l(j.branch),u(j.schedule_enabled),f(j.schedule_type),g(j.backup_kprofiles),y(j.backup_cloud_profiles),v(j.backup_settings),S(j.enabled),a(""),setTimeout(()=>{X.current=!0},100))},[j]);const me=w.useCallback(async(oe=!1)=>{if(j?.has_token)try{oe&&i?(await fe.saveGitHubBackupConfig({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:m,backup_cloud_profiles:x,backup_settings:b,enabled:N}),a(""),e("Token updated")):(await fe.updateGitHubBackupConfig({repository_url:n,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:m,backup_cloud_profiles:x,backup_settings:b,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(ze){e(`Failed to save: ${ze.message}`,"error")}},[j?.has_token,n,i,o,c,d,m,x,b,N,t,e]);w.useEffect(()=>{if(!(!X.current||!j?.has_token))return O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{me(!1)},500),()=>{O.current&&clearTimeout(O.current)}},[n,o,c,d,m,x,b,N,me,j?.has_token]),w.useEffect(()=>{if(!(!X.current||!j?.has_token||!i))return O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{me(!0)},1e3),()=>{O.current&&clearTimeout(O.current)}},[i,me,j?.has_token]);const ue=ht({mutationFn:oe=>fe.saveGitHubBackupConfig(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),a(""),X.current=!0},onError:oe=>{e(`Failed to save: ${oe.message}`,"error")}}),Ae=ht({mutationFn:fe.triggerGitHubBackup,onSuccess:oe=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),oe.success?oe.files_changed>0?e(`Backup complete - ${oe.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${oe.message}`,"error")},onError:oe=>{e(`Backup failed: ${oe.message}`,"error")}}),pe=ht({mutationFn:()=>fe.clearGitHubBackupLogs(0),onSuccess:oe=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${oe.deleted} logs`)},onError:oe=>{e(`Failed to clear logs: ${oe.message}`,"error")}}),Ee=async()=>{k(!0),F(null);try{let oe;if(i){if(!n){e("Enter repository URL","error"),k(!1);return}oe=await fe.testGitHubConnection(n,i)}else if(j?.has_token)oe=await fe.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),k(!1);return}F({success:oe.success,message:oe.message})}catch(oe){F({success:!1,message:oe.message})}finally{k(!1)}},_e=()=>{if(!n){e("Repository URL is required","error");return}if(!i){e("Access token is required","error");return}ue.mutate({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:m,backup_cloud_profiles:x,backup_settings:b,enabled:N})};return q?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(ut,{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(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(qj,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),j&&Z?.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($n,{checked:N,onChange:S})]})]})}),s.jsx(Nt,{className:"space-y-4",children:Z?.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:oe=>{r(oe.target.value),F(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 ",j?.has_token&&s.jsx("span",{className:"text-green-400",children:"(saved)"})]}),s.jsx("input",{type:"password",value:i,onChange:oe=>{a(oe.target.value),F(null)},placeholder:j?.has_token?"Enter new token to update":"ghp_xxxxxxxxxxxx",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),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:oe=>l(oe.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:oe=>{oe.target.value==="disabled"?u(!1):(u(!0),f(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:"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 ${se?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[s.jsx("input",{type:"checkbox",checked:m,onChange:oe=>g(oe.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:se}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm ${se?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),se&&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(Nn,{className:"w-3 h-3"}),"No printers connected"]}),de&&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(Nn,{className:"w-3 h-3"}),ae,"/",G," 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:oe=>y(oe.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:!Z?.is_authenticated}),s.jsxs("div",{children:[s.jsx("span",{className:`text-sm ${Z?.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:b,onChange:oe=>v(oe.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:[Y?.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:Y.last_backup_at?s.jsxs(s.Fragment,{children:[s.jsxs("span",{children:["Last backup: ",tq(Y.last_backup_at)]}),s.jsx(eq,{status:Y.last_backup_status})]}):s.jsx("span",{children:"No backups yet"})}),Y.next_scheduled_run&&s.jsxs("span",{className:"text-bambu-gray",children:[s.jsx(Wn,{className:"w-3 h-3 inline mr-1"}),"Next: ",tq(Y.next_scheduled_run)]})]}),R&&s.jsxs("div",{className:`text-sm flex items-center gap-1 ${R.success?"text-green-400":"text-red-400"}`,children:[R.success?s.jsx(Dn,{className:"w-4 h-4"}):s.jsx(ea,{className:"w-4 h-4"}),R.message]}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:Y?.configured?s.jsx(s.Fragment,{children:Ae.isPending||Y.is_running?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[s.jsx(ut,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{className:"text-sm",children:Y.progress||"Starting backup..."})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"primary",size:"sm",onClick:()=>Ae.mutate(),disabled:!j?.enabled,children:[s.jsx(Po,{className:"w-4 h-4"}),"Backup Now"]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:Ee,disabled:D,children:[D?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Test"]})]})}):s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"primary",size:"sm",onClick:_e,disabled:ue.isPending||!n||!i,children:[ue.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Dn,{className:"w-4 h-4"}),"Enable Backup"]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:Ee,disabled:D||!n||!i,children:[D?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{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(Nn,{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."})]})})]}),W&&W.length>0&&s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(f0,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),s.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>pe.mutate(),disabled:pe.isPending,children:[s.jsx(ln,{className:"w-4 h-4"}),"Clear"]})]})}),s.jsx(Nt,{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:W.slice(0,10).map(oe=>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(oe.started_at)}),s.jsx("td",{className:"py-2 px-2",children:s.jsx(eq,{status:oe.status})}),s.jsx("td",{className:"py-2 px-2",children:oe.commit_sha?s.jsxs("a",{href:`${j?.repository_url}/commit/${oe.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[oe.commit_sha.substring(0,7),s.jsx(Ur,{className:"w-3 h-3"})]}):s.jsx("span",{className:"text-bambu-gray",children:"-"})})]},oe.id))})]})})})]})]}),s.jsx("div",{className:"space-y-6",children:s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Qc,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Export or import your Bambuddy data as a local file for manual backup or migration."}),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:"Export Data"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Download all settings, printers, and profiles"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>T(!0),children:[s.jsx($r,{className:"w-4 h-4"}),"Export"]})]}),s.jsxs("div",{className:"flex items-center justify-between py-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Import Backup"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Restore from a previous export file"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>E(!0),children:[s.jsx(di,{className:"w-4 h-4"}),"Import"]})]})]})]})}),A&&s.jsx(xKe,{onClose:()=>T(!1),onExport:async oe=>{T(!1);try{const{blob:ze,filename:V}=await fe.exportBackup(oe),H=URL.createObjectURL(ze),K=document.createElement("a");K.href=H,K.download=V,K.click(),URL.revokeObjectURL(H),e("Backup downloaded successfully")}catch{e("Failed to create backup","error")}}}),C&&s.jsx(bKe,{onClose:()=>E(!1),onRestore:async(oe,ze)=>await fe.importBackup(oe,ze),onSuccess:()=>{E(!1),e("Backup restored successfully"),t.invalidateQueries()}})]})}const _Ke={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 wKe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function Lb(t,e,n=0){if(n>5)return"...";if(e.$ref)return Lb(t,wKe(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const a=Lb(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?[Lb(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,a]of Object.entries(e.properties))r[i]=Lb(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]=w.useState(!1),[l,c]=w.useState({}),[u,d]=w.useState(""),[f,m]=w.useState(null),[g,x]=w.useState(!1),[y,b]=w.useState(!1);w.useEffect(()=>{if(a&&n.parameters){const D={};for(const k of n.parameters)k.schema?.default!==void 0&&(D[k.name]=String(k.schema.default));c(k=>({...D,...k}))}},[a,n.parameters]),w.useEffect(()=>{if(a&&n.requestBody?.content?.["application/json"]?.schema&&!u){const D=n.requestBody.content["application/json"].schema,k=Lb(r,D);d(JSON.stringify(k,null,2))}},[a,n.requestBody,r,u]);const N=(()=>{const D=[];for(const k of n.parameters||[])if(k.in==="path"||k.required){const R=l[k.name];(R===void 0||R==="")&&D.push(k.name)}return D})(),S=async()=>{if(N.length>0){m({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${N.join(", ")}`,duration:0});return}x(!0),m(null);try{let D=t;const k=new URLSearchParams;for(const ne of n.parameters||[]){const z=l[ne.name];z!==void 0&&z!==""&&(ne.in==="path"?D=D.replace(`{${ne.name}}`,encodeURIComponent(z)):ne.in==="query"&&k.append(ne.name,z))}const R=k.toString(),F=`${D}${R?`?${R}`:""}`,O={"Content-Type":"application/json"};i&&(O["X-API-Key"]=i);const X={method:e.toUpperCase(),headers:O};["post","put","patch"].includes(e)&&u&&(X.body=u);const j=performance.now(),q=await fetch(F,X),Y=Math.round(performance.now()-j),W={};q.headers.forEach((ne,z)=>{W[z]=ne});let Z;q.headers.get("content-type")?.includes("application/json")?Z=await q.json():Z=await q.text(),m({status:q.status,statusText:q.statusText,headers:W,body:Z,duration:Y})}catch(D){m({status:0,statusText:"Network Error",headers:{},body:D instanceof Error?D.message:"Unknown error",duration:0})}finally{x(!1)}},A=async()=>{if(f){const D=typeof f.body=="string"?f.body:JSON.stringify(f.body,null,2);try{await navigator.clipboard.writeText(D),b(!0),setTimeout(()=>b(!1),2e3)}catch{const k=document.createElement("textarea");k.value=D,k.style.position="fixed",k.style.left="-999999px",document.body.appendChild(k),k.select(),document.execCommand("copy"),document.body.removeChild(k),b(!0),setTimeout(()=>b(!1),2e3)}}},T=(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(Pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):s.jsx(Ss,{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 ${_Ke[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}),T.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:T.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:k=>c(R=>({...R,[D.name]:k.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:k=>c(R=>({...R,[D.name]:k.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(k=>s.jsx("option",{value:k,children:k},k))]}):s.jsx("input",{type:"text",value:l[D.name]||"",onChange:k=>c(R=>({...R,[D.name]:k.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(Me,{onClick:S,disabled:g,children:[g?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Po,{className:"w-4 h-4"}),"Execute"]}),N.length>0&&s.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[s.jsx(ra,{className:"w-3 h-3"}),"Fill in: ",N.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(Me,{variant:"secondary",size:"sm",onClick:A,children:y?s.jsx(Dn,{className:"w-3 h-3 text-green-400"}):s.jsx(ll,{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 NKe({apiKey:t=""}){const[e,n]=w.useState(null),[r,i]=w.useState(!0),[a,o]=w.useState(null),[l,c]=w.useState(new Set),[u,d]=w.useState("");if(w.useEffect(()=>{async function b(){try{const v=await fetch("/openapi.json");if(!v.ok)throw new Error("Failed to fetch OpenAPI schema");const N=await v.json();n(N)}catch(v){o(v instanceof Error?v.message:"Unknown error")}finally{i(!1)}}b()},[]),r)return s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(a||!e)return s.jsx(wt,{children:s.jsx(Nt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-red-400",children:[s.jsx(ra,{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[b,v]of Object.entries(e.paths))for(const[N,S]of Object.entries(v)){if(N==="parameters")continue;const A=S.tags||["Other"];for(const T of A)f[T]||(f[T]=[]),f[T].push({path:b,method:N,spec:S})}const m=Object.entries(f).map(([b,v])=>{if(!u)return{tag:b,endpoints:v};const N=v.filter(({path:S,method:A,spec:T})=>{const C=u.toLowerCase();return S.toLowerCase().includes(C)||A.toLowerCase().includes(C)||(T.summary?.toLowerCase()||"").includes(C)||(T.description?.toLowerCase()||"").includes(C)});return{tag:b,endpoints:N}}).filter(({endpoints:b})=>b.length>0).sort((b,v)=>b.tag.localeCompare(v.tag)),g=b=>{c(v=>{const N=new Set(v);return N.has(b)?N.delete(b):N.add(b),N})},x=()=>{c(new Set(m.map(b=>b.tag)))},y=()=>{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:b=>d(b.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Me,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:y,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(Ur,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:[m.reduce((b,v)=>b+v.endpoints.length,0)," endpoints in ",m.length," categories"]}),s.jsx("div",{className:"space-y-3",children:m.map(({tag:b,endpoints:v})=>s.jsxs(wt,{children:[s.jsx("button",{onClick:()=>g(b),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(b)?s.jsx(Pi,{className:"w-5 h-5 text-bambu-gray"}):s.jsx(Ss,{className:"w-5 h-5 text-bambu-gray"}),s.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:b.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(b)&&s.jsx(Nt,{className:"pt-0 space-y-2",children:v.map(({path:N,method:S,spec:A})=>s.jsx(SKe,{path:N,method:S,spec:A,schema:e,apiKey:t},`${S}-${N}`))})]},b))})]})}const MKe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"];function EKe(){const t=an(),e=fl(),[n,r]=Oq(),{t:i,i18n:a}=Lg(),{showToast:o}=Hn(),{authEnabled:l,user:c,refreshAuth:u}=ah(),{mode:d,darkStyle:f,darkBackground:m,darkAccent:g,lightStyle:x,lightBackground:y,lightAccent:b,setDarkStyle:v,setDarkBackground:N,setDarkAccent:S,setLightStyle:A,setLightBackground:T,setLightAccent:C}=ih(),[E,D]=w.useState(null),[k,R]=w.useState(!1),[F,O]=w.useState(null),[X,j]=w.useState(!1),[q,Y]=w.useState(null),[W,Z]=w.useState(null),[ee,ne]=w.useState(!1),[z,G]=w.useState(SW()),ae=n.get("tab"),se=ae&&MKe.includes(ae)?ae:"general",[de,me]=w.useState(se),ue=ve=>{me(ve),ve==="general"?n.delete("tab"):n.set("tab",ve),r(n,{replace:!0})},[Ae,pe]=w.useState(!1),[Ee,_e]=w.useState(""),[oe,ze]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[V,H]=w.useState(null),[K,U]=w.useState(null),[Q,le]=w.useState(""),[ke,Re]=w.useState(!1),[Ce,B]=w.useState(!1),[I,$]=w.useState(null),[te,ye]=w.useState(!1),[be,Ye]=w.useState(!1),[$e,Qe]=w.useState(null),[qe,Xe]=w.useState(!1),[ce,ie]=w.useState({}),[Te,Ve]=w.useState({}),it=ve=>{G(ve),Tfe(ve)},re=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:De,isLoading:we}=ct({queryKey:["settings"],queryFn:fe.getSettings}),{data:Oe,isLoading:Ue}=ct({queryKey:["smart-plugs"],queryFn:fe.getSmartPlugs}),{data:je,isLoading:Je}=ct({queryKey:["smart-plugs-energy",Oe?.map(ve=>ve.id)],queryFn:async()=>{if(!Oe||Oe.length===0)return null;const ve=await Promise.all(Oe.filter(Wt=>Wt.enabled).map(async Wt=>{try{const Kt=await fe.getSmartPlugStatus(Wt.id);return{plug:Wt,status:Kt}}catch{return{plug:Wt,status:null}}}));let Et=0,Be=0,mt=0,jt=0,gt=0;for(const{plug:Wt,status:Kt}of ve){const Bn=Wt.plug_type==="mqtt"&&Kt?.energy?.power!=null;(Kt?.reachable||Bn)&&Kt?.energy&&(gt++,Kt.energy?.power!=null&&(Et+=Kt.energy.power),Kt.energy?.today!=null&&(Be+=Kt.energy.today),Kt.energy?.yesterday!=null&&(mt+=Kt.energy.yesterday),Kt.energy?.total!=null&&(jt+=Kt.energy.total))}return{totalPower:Et,totalToday:Be,totalYesterday:mt,totalLifetime:jt,reachableCount:gt,totalPlugs:Oe.filter(Wt=>Wt.enabled).length}},enabled:de==="plugs"&&!!Oe&&Oe.length>0,refetchInterval:de==="plugs"?1e4:!1}),{data:bt,isLoading:Tt}=ct({queryKey:["notification-providers"],queryFn:fe.getNotificationProviders}),{data:Dt,isLoading:sn}=ct({queryKey:["api-keys"],queryFn:fe.getAPIKeys}),Lt=ht({mutationFn:ve=>fe.createAPIKey(ve),onSuccess:ve=>{H(ve.key||null),pe(!1),_e(""),t.invalidateQueries({queryKey:["api-keys"]}),o("API key created")},onError:ve=>{o(`Failed to create API key: ${ve.message}`,"error")}}),gn=ht({mutationFn:ve=>fe.deleteAPIKey(ve),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o("API key deleted")},onError:ve=>{o(`Failed to delete API key: ${ve.message}`,"error")}}),{data:rn}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:zn,isLoading:br}=ct({queryKey:["notification-templates"],queryFn:fe.getNotificationTemplates}),{data:er}=ct({queryKey:["virtual-printer-settings"],queryFn:z1.getSettings,refetchInterval:1e4}),yr=er?.status?.running??!1,{data:vr}=ct({queryKey:["ffmpeg-status"],queryFn:fe.checkFfmpeg}),{data:Xn}=ct({queryKey:["version"],queryFn:fe.getVersion}),{data:Bt,refetch:In,isRefetching:Ti}=ct({queryKey:["updateCheck"],queryFn:fe.checkForUpdates,staleTime:300*1e3}),{data:_r,refetch:Se}=ct({queryKey:["updateStatus"],queryFn:fe.getUpdateStatus,refetchInterval:ve=>{const Et=ve.state.data;return Et?.status==="downloading"||Et?.status==="installing"?1e3:!1}}),{data:We}=ct({queryKey:["mqtt-status"],queryFn:fe.getMQTTStatus,refetchInterval:de==="network"?5e3:!1}),{data:et}=ct({queryKey:["github-backup-status"],queryFn:fe.getGitHubBackupStatus}),{data:ot}=ct({queryKey:["cloud-status"],queryFn:fe.getCloudStatus}),at=ht({mutationFn:fe.applyUpdate,onSuccess:ve=>{ve.is_docker?o(ve.message,"error"):Se()}}),[At,he]=w.useState(null),xe=ht({mutationFn:fe.testAllNotificationProviders,onSuccess:ve=>{he(ve),t.invalidateQueries({queryKey:["notification-providers"]}),ve.failed===0?o(`All ${ve.tested} providers tested successfully!`,"success"):o(`${ve.success}/${ve.tested} providers succeeded`,ve.failed>0?"error":"success")},onError:ve=>{o(`Failed to test providers: ${ve.message}`,"error")}}),Le=ht({mutationFn:async ve=>{if(!Oe)return{success:0,failed:0};const Et=Oe.filter(mt=>mt.enabled),Be=await Promise.all(Et.map(async mt=>{try{return await fe.controlSmartPlug(mt.id,ve),{success:!0}}catch{return{success:!1}}}));return{success:Be.filter(mt=>mt.success).length,failed:Be.filter(mt=>!mt.success).length}},onSuccess:(ve,Et)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ve.failed===0?o(`All ${ve.success} plugs turned ${Et}`,"success"):o(`${ve.success} plugs turned ${Et}, ${ve.failed} failed`,"error")},onError:ve=>{o(`Failed: ${ve.message}`,"error")}}),Ie=w.useRef(null),Ne=w.useRef(!1),ft=w.useRef(!0);w.useEffect(()=>{if(De&&!E){const ve={...De,external_url:De.external_url||window.location.origin};D(ve),setTimeout(()=>{ft.current=!1},100)}},[De,E]);const _t=ht({mutationFn:fe.updateSettings,onSuccess:ve=>{t.setQueryData(["settings"],ve),D(ve),t.invalidateQueries({queryKey:["archiveStats"]}),o("Settings saved","success")},onError:ve=>{o(`Failed to save: ${ve.message}`,"error")},onSettled:()=>{Ne.current=!1}}),kt=ht({mutationFn:({id:ve,data:Et})=>fe.updatePrinter(ve,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o("Camera settings saved","success")},onError:ve=>{o(`Failed to update printer: ${ve.message}`,"error")}});w.useEffect(()=>{if(!(ft.current||!E||!De||!(De.auto_archive!==E.auto_archive||De.save_thumbnails!==E.save_thumbnails||De.capture_finish_photo!==E.capture_finish_photo||De.default_filament_cost!==E.default_filament_cost||De.currency!==E.currency||De.energy_cost_per_kwh!==E.energy_cost_per_kwh||De.energy_tracking_mode!==E.energy_tracking_mode||De.check_updates!==E.check_updates||(De.check_printer_firmware??!0)!==(E.check_printer_firmware??!0)||De.notification_language!==E.notification_language||De.ams_humidity_good!==E.ams_humidity_good||De.ams_humidity_fair!==E.ams_humidity_fair||De.ams_temp_good!==E.ams_temp_good||De.ams_temp_fair!==E.ams_temp_fair||De.ams_history_retention_days!==E.ams_history_retention_days||De.per_printer_mapping_expanded!==E.per_printer_mapping_expanded||De.date_format!==E.date_format||De.time_format!==E.time_format||De.default_printer_id!==E.default_printer_id||De.ftp_retry_enabled!==E.ftp_retry_enabled||De.ftp_retry_count!==E.ftp_retry_count||De.ftp_retry_delay!==E.ftp_retry_delay||De.ftp_timeout!==E.ftp_timeout||De.mqtt_enabled!==E.mqtt_enabled||De.mqtt_broker!==E.mqtt_broker||De.mqtt_port!==E.mqtt_port||De.mqtt_username!==E.mqtt_username||De.mqtt_password!==E.mqtt_password||De.mqtt_topic_prefix!==E.mqtt_topic_prefix||De.mqtt_use_tls!==E.mqtt_use_tls||De.external_url!==E.external_url||De.ha_enabled!==E.ha_enabled||De.ha_url!==E.ha_url||De.ha_token!==E.ha_token||(De.library_archive_mode??"ask")!==(E.library_archive_mode??"ask")||Number(De.library_disk_warning_gb??5)!==Number(E.library_disk_warning_gb??5)||(De.camera_view_mode??"window")!==(E.camera_view_mode??"window")||De.prometheus_enabled!==E.prometheus_enabled||De.prometheus_token!==E.prometheus_token))&&!Ne.current)return Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{if(Ne.current)return;Ne.current=!0;const Et={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};_t.mutate(Et)},500),()=>{Ie.current&&clearTimeout(Ie.current)}},[E,De,_t]);const pt=w.useCallback((ve,Et)=>{D(Be=>Be?{...Be,[ve]:Et}:null)},[]),$t=async(ve,Et,Be)=>{if(!Et){o("Please enter a camera URL","error");return}Ve(mt=>({...mt,[ve]:!0})),ie(mt=>({...mt,[ve]:null}));try{const mt=await fe.testExternalCamera(ve,Et,Be);ie(jt=>({...jt,[ve]:mt})),mt.success?o(`Camera connected${mt.resolution?` (${mt.resolution})`:""}`,"success"):o(mt.error||"Connection failed","error")}catch(mt){const jt=mt instanceof Error?mt.message:"Test failed";ie(gt=>({...gt,[ve]:{success:!1,error:jt}})),o(jt,"error")}finally{Ve(mt=>({...mt,[ve]:!1}))}},[Pt,St]=w.useState({}),Yt=w.useRef({});w.useEffect(()=>{if(rn){const ve={};rn.forEach(Et=>{Et.external_camera_url&&Pt[Et.id]===void 0&&(ve[Et.id]=Et.external_camera_url)}),Object.keys(ve).length>0&&St(Et=>({...Et,...ve}))}},[rn]);const qt=(ve,Et)=>{St(Be=>({...Be,[ve]:Et})),Yt.current[ve]&&clearTimeout(Yt.current[ve]),Yt.current[ve]=setTimeout(()=>{kt.mutate({id:ve,data:{external_camera_url:Et||null}})},800)},dn=(ve,Et)=>{const Be={};Et.type!==void 0&&(Be.external_camera_type=Et.type||null),Et.enabled!==void 0&&(Be.external_camera_enabled=Et.enabled),kt.mutate({id:ve,data:Be})};return we||!E?s.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:s.jsx(ut,{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:"Settings"}),s.jsx("p",{className:"text-bambu-gray",children:"Configure Bambuddy"})]}),s.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary overflow-x-auto",children:[s.jsx("button",{onClick:()=>ue("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${de==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:"General"}),s.jsxs("button",{onClick:()=>ue("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Gs,{className:"w-4 h-4"}),"Smart Plugs",Oe&&Oe.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Oe.length})]}),s.jsxs("button",{onClick:()=>ue("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(df,{className:"w-4 h-4"}),"Notifications",bt&&bt.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:bt.length})]}),s.jsxs("button",{onClick:()=>ue("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(due,{className:"w-4 h-4"}),"Filament"]}),s.jsxs("button",{onClick:()=>ue("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Vp,{className:"w-4 h-4"}),"Network",s.jsx("span",{className:`w-2 h-2 rounded-full ${We?.enabled?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>ue("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(ef,{className:"w-4 h-4"}),"API Keys",Dt&&Dt.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Dt.length})]}),s.jsxs("button",{onClick:()=>ue("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(qr,{className:"w-4 h-4"}),"Virtual Printer",s.jsx("span",{className:`w-2 h-2 rounded-full ${yr?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>ue("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(tf,{className:"w-4 h-4"}),"Users",l&&s.jsx("span",{className:`w-2 h-2 rounded-full ${l?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>ue("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Qc,{className:"w-4 h-4"}),"Backup",s.jsx("span",{className:`w-2 h-2 rounded-full ${ot?.is_authenticated&&et?.configured&&et?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),de==="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(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(jd,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),s.jsx("select",{value:a.language,onChange:ve=>a.changeLanguage(ve.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:JU.map(ve=>s.jsxs("option",{value:ve.code,children:[ve.nativeName," (",ve.name,")"]},ve.code))}),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.jsx("select",{value:z,onChange:ve=>it(ve.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:g0.map(ve=>s.jsx("option",{value:ve.to,children:i(ve.labelKey)},ve.id))}),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("select",{value:E.date_format||"system",onChange:ve=>pt("date_format",ve.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:"system",children:"System Default"}),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.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),s.jsxs("select",{value:E.time_format||"system",onChange:ve=>pt("time_format",ve.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:"system",children:"System Default"}),s.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),s.jsx("option",{value:"24h",children:"24-hour (15:30)"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),s.jsxs("select",{value:E.default_printer_id??"",onChange:ve=>pt("default_printer_id",ve.target.value?Number(ve.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 default (ask each time)"}),rn?.map(ve=>s.jsx("option",{value:ve.id,children:ve.name},ve.id))]}),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:"Sidebar order"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:re,children:[s.jsx(Zf,{className:"w-4 h-4"}),"Reset"]})]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(dD,{className:"w-5 h-5"}),"Appearance"]})}),s.jsxs(Nt,{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:m,onChange:ve=>{N(ve.target.value),o("Settings saved","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:g,onChange:ve=>{S(ve.target.value),o("Settings saved","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:ve=>{v(ve.target.value),o("Settings saved","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:y,onChange:ve=>{T(ve.target.value),o("Settings saved","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:b,onChange:ve=>{C(ve.target.value),o("Settings saved","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:ve=>{A(ve.target.value),o("Settings saved","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(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Archive Settings"})}),s.jsxs(Nt,{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:ve=>pt("auto_archive",ve.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:"Save thumbnails"}),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:ve=>pt("save_thumbnails",ve.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:"Capture finish photo"}),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:ve=>pt("capture_finish_photo",ve.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&&vr&&!vr.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(Nn,{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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(gD,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),s.jsxs(Nt,{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:ve=>pt("camera_view_mode",ve.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:"New Window"}),s.jsx("option",{value:"embedded",children:"Embedded Overlay"})]}),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:"External Cameras"}),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."}),rn&&rn.length>0?s.jsx("div",{className:"space-y-3",children:rn.map(ve=>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:ve.name}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ve.external_camera_enabled,onChange:Et=>dn(ve.id,{enabled:Et.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"})]})]}),ve.external_camera_enabled&&s.jsxs("div",{className:"space-y-2 mt-2",children:[s.jsx("input",{type:"text",placeholder:ve.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Pt[ve.id]??ve.external_camera_url??"",onChange:Et=>qt(ve.id,Et.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("select",{value:ve.external_camera_type||"mjpeg",onChange:Et=>dn(ve.id,{type:Et.target.value}),className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[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(Me,{size:"sm",variant:"secondary",onClick:()=>$t(ve.id,Pt[ve.id]??ve.external_camera_url??"",ve.external_camera_type||"mjpeg"),disabled:Te[ve.id]||!(Pt[ve.id]??ve.external_camera_url),children:Te[ve.id]?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):"Test"})]}),ce[ve.id]&&s.jsx("div",{className:`text-xs flex items-center gap-1 ${ce[ve.id]?.success?"text-green-500":"text-red-500"}`,children:ce[ve.id]?.success?s.jsxs(s.Fragment,{children:[s.jsx(Dn,{className:"w-3 h-3"}),"Connected",ce[ve.id]?.resolution&&` (${ce[ve.id]?.resolution})`]}):s.jsxs(s.Fragment,{children:[s.jsx(ea,{className:"w-3 h-3"}),ce[ve.id]?.error||"Connection failed"]})})]})]},ve.id))}):s.jsx("p",{className:"text-xs text-bambu-gray italic",children:"No printers configured"})]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Cost Tracking"})}),s.jsxs(Nt,{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:ve=>pt("default_filament_cost",parseFloat(ve.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:ve=>pt("currency",ve.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:ve=>pt("energy_cost_per_kwh",parseFloat(ve.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:ve=>pt("energy_tracking_mode",ve.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:"Prints Only"}),s.jsx("option",{value:"total",children:"Total Consumption"})]}),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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Ga,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),s.jsxs(Nt,{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:ve=>pt("library_archive_mode",ve.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:"Always create archive entry"}),s.jsx("option",{value:"never",children:"Never create archive entry"}),s.jsx("option",{value:"ask",children:"Ask each time"})]}),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:ve=>pt("library_disk_warning_gb",parseFloat(ve.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(pKe,{}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),s.jsxs(Nt,{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:"Check for updates"}),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:ve=>pt("check_updates",ve.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:"Check printer firmware"}),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:ve=>pt("check_printer_firmware",ve.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:"Current version"}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",Xn?.version||"..."]})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>In(),disabled:Ti,children:[Ti?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Check now"]})]}),Bt?.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",Bt.latest_version]}),Bt.release_name&&Bt.release_name!==Bt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:Bt.release_name})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[Bt.release_notes&&s.jsx("button",{onClick:()=>ye(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),Bt.release_url&&s.jsx("a",{href:Bt.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:"View release on GitHub",children:s.jsx(Ur,{className:"w-4 h-4"})})]})]}),_r?.status==="downloading"||_r?.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(ut,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{children:_r.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:`${_r.progress}%`}})})]}):_r?.status==="complete"?s.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:_r.message}):_r?.status==="error"?s.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:_r.error||_r.message}):Bt?.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(Me,{className:"mt-3",onClick:()=>at.mutate(),disabled:at.isPending,children:[at.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx($r,{className:"w-4 h-4"}),"Install Update"]})]}):Bt?.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: ",Bt.error]}):Bt&&!Bt.update_available?s.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Data Management"})}),s.jsxs(Nt,{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:"Clear Notification Logs"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Delete notification logs older than 30 days"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Re(!0),children:[s.jsx(ln,{className:"w-4 h-4"}),"Clear"]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Reset UI Preferences"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Reset sidebar order, theme, view modes, and layout preferences. Printers, archives, and settings are not affected."})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>B(!0),children:[s.jsx(ln,{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(Me,{variant:"secondary",size:"sm",onClick:()=>ue("backup"),children:[s.jsx(Qc,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),de==="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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(jd,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),s.jsxs(Nt,{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:ve=>pt("external_url",ve.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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(gr,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),s.jsxs(Nt,{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:"Enable retry"}),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:ve=>pt("ftp_retry_enabled",ve.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:ve=>pt("ftp_retry_count",Math.min(10,Math.max(1,parseInt(ve.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:ve=>pt("ftp_retry_delay",Math.min(30,Math.max(1,parseInt(ve.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:ve=>pt("ftp_timeout",Math.min(120,Math.max(10,parseInt(ve.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(wt,{children:[s.jsx(Qn,{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(U2,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),E.ha_enabled&&$e&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${$e.success?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${$e.success?"text-green-400":"text-red-400"}`,children:$e.success?"Connected":"Disconnected"})]})]})}),s.jsxs(Nt,{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, and input_boolean entities."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Enable Home Assistant"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Control smart plugs via Home Assistant"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.ha_enabled??!1,onChange:ve=>pt("ha_enabled",ve.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:ve=>pt("ha_url",ve.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:ve=>pt("ha_token",ve.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(Me,{variant:"secondary",size:"sm",disabled:qe,onClick:async()=>{Xe(!0),Qe(null);try{const ve=await fe.testHAConnection(E.ha_url,E.ha_token);Qe(ve)}catch(ve){Qe({success:!1,message:null,error:ve instanceof Error?ve.message:"Unknown error"})}finally{Xe(!1)}},children:[qe?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Vp,{className:"w-4 h-4"}),"Test Connection"]})})]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{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(Vp,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),We?.enabled&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${We.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${We.connected?"text-green-400":"text-red-400"}`,children:We.connected?"Connected":"Disconnected"})]})]})}),s.jsxs(Nt,{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:"Enable MQTT"}),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:ve=>pt("mqtt_enabled",ve.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:ve=>pt("mqtt_broker",ve.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:ve=>pt("mqtt_port",Math.min(65535,Math.max(1,parseInt(ve.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:ve=>{const Et=ve.target.checked;pt("mqtt_use_tls",Et);const Be=E.mqtt_port??1883;Et&&Be===1883?pt("mqtt_port",8883):!Et&&Be===8883&&pt("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:"Use TLS"})]})]}),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:ve=>pt("mqtt_username",ve.target.value),placeholder:"Leave empty for anonymous",className:"w-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:ve=>pt("mqtt_password",ve.target.value),placeholder:"Leave empty for anonymous",className:"w-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:ve=>pt("mqtt_topic_prefix",ve.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."]})]}),We&&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 ${We.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:"text-bambu-gray",children:We.connected?s.jsxs(s.Fragment,{children:["Connected to ",s.jsxs("span",{className:"text-white",children:[We.broker,":",We.port]})]}):"Not connected"})]})})]})]})]})]}),s.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Jj,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),s.jsxs(Nt,{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:"Enable Metrics Endpoint"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Expose printer data in Prometheus format"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.prometheus_enabled??!1,onChange:ve=>pt("prometheus_enabled",ve.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:ve=>pt("prometheus_token",ve.target.value),placeholder:"Leave empty for no authentication",className:"w-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:"Available Metrics"}),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)"})]})]})]})]})]})})]}),$e&&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:[$e.success?s.jsx(Dn,{className:"w-8 h-8 text-green-400"}):s.jsx(ea,{className:"w-8 h-8 text-red-400"}),s.jsx("h3",{className:"text-lg font-medium text-white",children:$e.success?"Connection Successful":"Connection Failed"})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:$e.success?$e.message||"Successfully connected to Home Assistant.":$e.error||"Failed to connect to Home Assistant."}),s.jsx("div",{className:"flex justify-end",children:s.jsx(Me,{variant:"primary",onClick:()=>Qe(null),children:"OK"})})]})}),de==="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(Gs,{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:[Oe&&Oe.filter(ve=>ve.enabled).length>1&&s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>$("on"),disabled:Le.isPending,title:"Turn all plugs on",children:[Le.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xu,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),s.jsxs(Me,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>$("off"),disabled:Le.isPending,title:"Turn all plugs off",children:[Le.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(H2,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),s.jsxs(Me,{className:"whitespace-nowrap",onClick:()=>{O(null),R(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Oe&&Oe.length>0&&s.jsxs(wt,{className:"mb-6",children:[s.jsx(Qn,{children:s.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[s.jsx(Vd,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",Je&&s.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),s.jsx(Nt,{children:je?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(Vd,{className:"w-3 h-3"}),"Current Power"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:[je.reachableCount,"/",je.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(ii,{className:"w-3 h-3"}),"Today"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:["~",(je.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(Jj,{className:"w-3 h-3"}),"Yesterday"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:["~",(je.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(Gj,{className:"w-3 h-3"}),"Total"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:["~",(je.totalLifetime*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]})]}):Je?null:s.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),Ue?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Oe&&Oe.length>0?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Oe.map(ve=>s.jsx(tKe,{plug:ve,onEdit:Et=>{O(Et),R(!0)}},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(Gs,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:"No smart plugs configured"}),s.jsx("p",{className:"text-sm mb-4",children:"Add a Tasmota-based smart plug to track energy usage and automate power control."}),s.jsxs(Me,{onClick:()=>{O(null),R(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Your First Smart Plug"]})]})})})]}),de==="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(df,{className:"w-5 h-5 text-bambu-green"}),"Providers"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>ne(!0),children:[s.jsx(f0,{className:"w-4 h-4"}),"Log"]}),bt&&bt.length>0&&s.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>{he(null),xe.mutate()},disabled:xe.isPending,children:[xe.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(mD,{className:"w-4 h-4"}),"Test All"]}),s.jsxs(Me,{size:"sm",onClick:()=>{Y(null),j(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add"]})]})]}),s.jsx(wt,{className:"mb-4",children:s.jsx(Nt,{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:ve=>pt("notification_language",ve.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:JU.map(ve=>s.jsx("option",{value:ve.code,children:ve.nativeName},ve.code))})]})})}),At&&s.jsx(wt,{className:"mb-4",children:s.jsxs(Nt,{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:"Test Results"}),s.jsx("button",{onClick:()=>he(null),className:"text-bambu-gray hover:text-white text-xs",children:"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(Dn,{className:"w-4 h-4"}),At.success," passed"]}),At.failed>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(ea,{className:"w-4 h-4"}),At.failed," failed"]})]}),At.results.filter(ve=>!ve.success).length>0&&s.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:At.results.filter(ve=>!ve.success).map(ve=>s.jsxs("div",{className:"text-xs text-red-400",children:[s.jsxs("span",{className:"font-medium",children:[ve.provider_name,":"]})," ",ve.message]},ve.provider_id))})]})}),Tt?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):bt&&bt.length>0?s.jsx("div",{className:"space-y-3",children:bt.map(ve=>s.jsx(iKe,{provider:ve,onEdit:Et=>{Y(Et),j(!0)}},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(df,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm font-medium text-white mb-2",children:"No providers configured"}),s.jsx("p",{className:"text-xs mb-3",children:"Add a provider to receive alerts."}),s.jsxs(Me,{size:"sm",onClick:()=>{Y(null),j(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Provider"]})]})})})]}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[s.jsx(Ga,{className:"w-5 h-5 text-bambu-green"}),"Message Templates"]}),s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Customize notification messages for each event."}),br?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):zn&&zn.length>0?s.jsx("div",{className:"space-y-2",children:zn.map(ve=>s.jsx(wt,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>Z(ve),children:s.jsx(Nt,{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:ve.name}),s.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ve.title_template})]}),s.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:Et=>{Et.stopPropagation(),Z(ve)},children:s.jsx($2,{className:"w-4 h-4 text-bambu-gray"})})]})})},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(Ga,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm",children:"No templates available. Restart the backend to seed default templates."})]})})})]})]}),de==="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(ef,{className:"w-5 h-5 text-bambu-green"}),"API Keys"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Create API keys for external integrations and webhooks."})]}),s.jsxs(Me,{size:"sm",onClick:()=>pe(!0),className:"flex-shrink-0",children:[s.jsx(Jn,{className:"w-4 h-4"}),"Create Key"]})]}),V&&s.jsx(wt,{className:"mb-6 border-bambu-green",children:s.jsx(Nt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Dn,{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:"API Key Created Successfully"}),s.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Copy this key now - it won't be shown again!"}),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:V}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(V);else{const ve=document.createElement("textarea");ve.value=V,ve.style.position="fixed",ve.style.left="-999999px",document.body.appendChild(ve),ve.select(),document.execCommand("copy"),document.body.removeChild(ve)}o("Key copied to clipboard")}catch{o("Failed to copy key","error")}},children:s.jsx(ll,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>{le(V),o("Key added to API Browser")},children:"Use in API Browser"}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>H(null),children:"Dismiss"})]})]})]})})}),Ae&&s.jsxs(wt,{className:"mb-6",children:[s.jsx(Qn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:"Create New API Key"})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Key Name"}),s.jsx("input",{type:"text",value:Ee,onChange:ve=>_e(ve.target.value),placeholder:"e.g., Home Assistant, OctoPrint",className:"w-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:"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:oe.can_read_status,onChange:ve=>ze(Et=>({...Et,can_read_status:ve.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:"Read Status"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"View printer status and queue"})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:oe.can_queue,onChange:ve=>ze(Et=>({...Et,can_queue:ve.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:"Manage Queue"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Add and remove items from print queue"})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:oe.can_control_printer,onChange:ve=>ze(Et=>({...Et,can_control_printer:ve.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:"Control Printer"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Pause, resume, and stop prints"})]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[s.jsxs(Me,{onClick:()=>Lt.mutate({name:Ee||"Unnamed Key",...oe}),disabled:Lt.isPending,children:[Lt.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Jn,{className:"w-4 h-4"}),"Create Key"]}),s.jsx(Me,{variant:"secondary",onClick:()=>pe(!1),children:"Cancel"})]})]})]}),sn?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Dt&&Dt.length>0?s.jsx("div",{className:"space-y-3",children:Dt.map(ve=>s.jsx(wt,{children:s.jsx(Nt,{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(ef,{className:`w-5 h-5 ${ve.enabled?"text-bambu-green":"text-bambu-gray"}`}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium",children:ve.name}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[ve.key_prefix,"••••••••",ve.last_used&&` · Last used: ${og(ve.last_used)}`]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"flex gap-1 text-xs",children:[ve.can_read_status&&s.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:"Read"}),ve.can_queue&&s.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:"Queue"}),ve.can_control_printer&&s.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:"Control"})]}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>U(ve.id),children:s.jsx(ln,{className:"w-4 h-4 text-red-400"})})]})]})})},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(ef,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:"No API keys"}),s.jsx("p",{className:"text-sm mb-4",children:"Create an API key to integrate with external services."}),s.jsxs(Me,{onClick:()=>pe(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Create Your First Key"]})]})})}),s.jsxs(wt,{className:"mt-6",children:[s.jsx(Qn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:"Webhook Endpoints"})}),s.jsxs(Nt,{className:"space-y-3 text-sm",children:[s.jsxs("p",{className:"text-bambu-gray",children:["Use your API key in the ",s.jsx("code",{className:"text-bambu-green",children:"X-API-Key"})," header."]}),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.jsx("span",{className:"text-bambu-gray",children:" - Get all printer status"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Get specific printer status"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Add to print queue"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Pause print"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Resume print"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Stop print"})]})]})]})]})]}),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(jd,{className:"w-5 h-5 text-bambu-green"}),"API Browser"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Explore and test all available API endpoints."})]}),s.jsx(wt,{className:"mb-4",children:s.jsxs(Nt,{className:"py-3",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"API Key for Testing"}),s.jsx("input",{type:"text",value:Q,onChange:ve=>le(ve.target.value),placeholder:"Paste your API key here to test authenticated endpoints...",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.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:["This key will be sent as ",s.jsx("code",{className:"text-bambu-green",children:"X-API-Key"})," header with requests."]})]})}),s.jsx(NKe,{apiKey:Q})]})]}),de==="virtual-printer"&&s.jsx(gKe,{}),de==="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(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"AMS Display Thresholds"})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Configure color thresholds for AMS humidity and temperature indicators."}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(uD,{className:"w-4 h-4 text-blue-400"}),s.jsx("span",{className:"font-medium",children:"Humidity"})]}),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:"Good (green) ≤"}),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:ve=>pt("ams_humidity_good",parseInt(ve.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.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Fair (orange) ≤"}),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:ve=>pt("ams_humidity_fair",parseInt(ve.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:"Above fair threshold shows as red (bad)"})]}),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(G2,{className:"w-4 h-4 text-orange-400"}),s.jsx("span",{className:"font-medium",children:"Temperature"})]}),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:"Good (blue) ≤"}),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:ve=>pt("ams_temp_good",parseFloat(ve.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.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Fair (orange) ≤"}),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:ve=>pt("ams_temp_fair",parseFloat(ve.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:"Above fair threshold shows as red (hot)"})]}),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(Qc,{className:"w-4 h-4 text-purple-400"}),s.jsx("span",{className:"font-medium",children:"History Retention"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Keep sensor history for"}),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:ve=>pt("ams_history_retention_days",parseInt(ve.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:"days"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Older humidity and temperature data will be automatically deleted"})]}),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(qr,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"font-medium",children:"Print Modal"})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-white",children:"Expand custom mapping by default"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:"When printing to multiple printers, show per-printer AMS mapping expanded"})]}),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:ve=>pt("per_printer_mapping_expanded",ve.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(fKe,{})})]}),K!==null&&s.jsx(Fn,{title:"Delete API Key",message:"Are you sure you want to delete this API key? Any integrations using this key will stop working.",confirmText:"Delete Key",variant:"danger",onConfirm:()=>{gn.mutate(K),U(null)},onCancel:()=>U(null)}),k&&s.jsx(nKe,{plug:F,onClose:()=>{R(!1),O(null)}}),X&&s.jsx(aKe,{provider:q,onClose:()=>{j(!1),Y(null)}}),W&&s.jsx(sKe,{template:W,onClose:()=>Z(null)}),ee&&s.jsx(cKe,{onClose:()=>ne(!1)}),ke&&s.jsx(Fn,{title:"Clear Notification Logs",message:"This will permanently delete all notification logs older than 30 days. This action cannot be undone.",confirmText:"Clear Logs",variant:"warning",onConfirm:async()=>{Re(!1);try{const ve=await fe.clearNotificationLogs(30);o(ve.message,"success")}catch{o("Failed to clear logs","error")}},onCancel:()=>Re(!1)}),Ce&&s.jsx(Fn,{title:"Reset UI Preferences",message:"This will reset all UI preferences to defaults: sidebar order, theme, dashboard layout, view modes, and sorting preferences. Your printers, archives, and server settings will NOT be affected. The page will reload after clearing.",confirmText:"Reset Preferences",variant:"default",onConfirm:()=>{B(!1),localStorage.clear(),o("UI preferences reset. Refreshing...","success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>B(!1)}),I&&s.jsx(Fn,{title:`Turn All Plugs ${I==="on"?"On":"Off"}`,message:`This will turn ${I==="on"?"ON":"OFF"} all ${Oe?.filter(ve=>ve.enabled).length||0} enabled smart plugs. ${I==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${I==="on"?"On":"Off"}`,variant:I==="off"?"danger":"warning",onConfirm:()=>{const ve=I;$(null),Le.mutate(ve)},onCancel:()=>$(null)}),te&&Bt?.release_notes&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>ye(!1),children:s.jsxs(wt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ve=>ve.stopPropagation(),children:[s.jsxs(Qn,{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",Bt.latest_version]}),Bt.release_name&&Bt.release_name!==Bt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray",children:Bt.release_name})]}),s.jsx("button",{onClick:()=>ye(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:s.jsx(Ut,{className:"w-5 h-5"})})]}),s.jsx(Nt,{className:"overflow-y-auto flex-1",children:s.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:Bt.release_notes})}),s.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[Bt.release_url&&s.jsx("a",{href:Bt.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:s.jsxs(Me,{variant:"secondary",className:"w-full",children:[s.jsx(Ur,{className:"w-4 h-4"}),"View on GitHub"]})}),s.jsx(Me,{onClick:()=>ye(!1),className:"flex-1",children:"Close"})]})]})}),de==="users"&&s.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[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(tf,{className:"w-5 h-5 text-bambu-green"}),"User Authentication"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Enable authentication to secure your Bambuddy instance and manage user access."})]}),s.jsx(wt,{children:s.jsx(Nt,{className:"py-6",children:l?s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center bg-green-500/20",children:s.jsx(LT,{className:"w-6 h-6 text-green-400"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-white font-medium",children:"Authentication Enabled"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Your Bambuddy instance is secured with authentication."})]})]}),c&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Current User"}),s.jsx("p",{className:"text-white font-medium",children:c.username}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Role: ",s.jsx("span",{className:"capitalize",children:c.role})]})]}),s.jsx("div",{className:`px-3 py-1 rounded-full text-xs font-medium ${c.role==="admin"?"bg-purple-500/20 text-purple-300":"bg-blue-500/20 text-blue-300"}`,children:c.role==="admin"?"Admin":"User"})]})}),s.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[s.jsxs(Me,{onClick:()=>e("/users"),className:"w-full",variant:"secondary",children:[s.jsx(tf,{className:"w-4 h-4"}),"Manage Users"]}),c?.role==="admin"&&s.jsxs(Me,{onClick:()=>Ye(!0),className:"w-full",variant:"secondary",children:[s.jsx(bz,{className:"w-4 h-4"}),"Disable Authentication"]})]})]}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:`w-12 h-12 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?s.jsx(LT,{className:"w-6 h-6 text-green-400"}):s.jsx(bz,{className:"w-6 h-6 text-gray-400"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-white font-medium",children:"Authentication Disabled"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Your Bambuddy instance is currently accessible without authentication."})]})]}),s.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Enable authentication to:"}),s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-4",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Require login to access the system"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage multiple users with different roles"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Control access to printer settings and user management"})]})]}),s.jsxs(Me,{type:"button",onClick:ve=>{ve.preventDefault(),e("/setup")},className:"w-full",children:[s.jsx(LT,{className:"w-4 h-4"}),"Activate Authentication"]})]})]})})})]}),l&&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(Zj,{className:"w-5 h-5 text-bambu-green"}),"Role Permissions"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Overview of what each role can do."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-purple-500/20 flex items-center justify-center",children:s.jsx(Zj,{className:"w-4 h-4 text-purple-300"})}),s.jsx("h3",{className:"text-white font-medium",children:"Admin"})]})}),s.jsx(Nt,{children:s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage printer settings"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Create, edit, and delete users"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Access all system features"})]})]})})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-500/20 flex items-center justify-center",children:s.jsx(tf,{className:"w-4 h-4 text-blue-300"})}),s.jsx("h3",{className:"text-white font-medium",children:"User"})]})}),s.jsx(Nt,{children:s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Send print jobs"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage files and archives"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage filament"})]})]})})]})]})]})]}),de==="backup"&&s.jsx(vKe,{}),be&&s.jsx(Fn,{title:"Disable Authentication",message:"Are you sure you want to disable authentication? This will make your Bambuddy instance accessible without login. All users will remain in the database but authentication will be disabled.",confirmText:"Disable Authentication",variant:"danger",onConfirm:async()=>{try{await fe.disableAuth(),o("Authentication disabled successfully","success"),await u(),Ye(!1),window.location.href="/"}catch(ve){const Et=ve instanceof Error?ve.message:"Failed to disable authentication";o(Et,"error")}},onCancel:()=>Ye(!1)})]})}const Nre=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},TKe=t=>t.startsWith("HH")?"HF":"S",AKe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},GR=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 wj({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:a,note:o}){const l=TKe(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(Ro,{className:"w-4 h-4 text-bambu-green"}):s.jsx(Do,{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:Nre(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(mW,{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(ll,{className:"w-4 h-4"})})]})}function Sj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],isDualNozzle:i=!1,initialNote:a="",initialNoteKey:o=null,onClose:l,onSave:c,onSaveNote:u}){const{showToast:d}=Hn(),[f,m]=w.useState(t?.name||""),[g,x]=w.useState(t?.k_value?Nre(t.k_value):"0.020"),[y,b]=w.useState(t?.filament_id||""),[v,N]=w.useState(t?.nozzle_id?AKe(t.nozzle_id):"HH00"),[S,A]=w.useState(t?.nozzle_diameter||n),[T,C]=w.useState(t?[t.extruder_id]:i?[0,1]:[0]),[E,D]=w.useState(!1),[k,R]=w.useState({current:0,total:0}),[F,O]=w.useState(a),X=Fr.useMemo(()=>{const ne=new Map;for(const z of r)if(z.filament_id&&!ne.has(z.filament_id)){const G=GR(z.name||"");ne.set(z.filament_id,{id:z.filament_id,name:G||z.filament_id})}return Array.from(ne.values()).sort((z,G)=>z.name.localeCompare(G.name))},[r]),j=ht({mutationFn:ne=>(console.log("[KProfile] Calling API..."),fe.setKProfile(e,ne)),onSuccess:ne=>{if(console.log("[KProfile] Save success:",ne),d("K-profile saved"),u&&F!==a){let z;F===""&&o?z=o:t&&t.slot_id>0?z=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:z=`name_${f}_${y}`,u(z,F)}D(!0),setTimeout(()=>{D(!1),c()},2500)},onError:ne=>{console.error("[KProfile] Save error:",ne),d(ne.message,"error"),D(!1)}}),q=ht({mutationFn:ne=>(console.log("[KProfile] Deleting profile..."),fe.deleteKProfile(e,ne)),onSuccess:ne=>{console.log("[KProfile] Delete success:",ne),d("K-profile deleted"),D(!0),setTimeout(()=>{D(!1),l()},4e3)},onError:ne=>{console.error("[KProfile] Delete error:",ne),d(ne.message,"error"),D(!1)}}),[Y,W]=w.useState(!1),Z=()=>{t&&q.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})},ee=async ne=>{if(ne.preventDefault(),i&&!t&&T.length===0){d("Please select at least one extruder","error");return}const z=parseFloat(g).toFixed(6),G=`${v}-${S}`;if(t||T.length===1){const se={name:f,k_value:z,filament_id:y,nozzle_id:G,nozzle_diameter:S,extruder_id:t?t.extruder_id:T[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",se),j.mutate(se);return}D(!0),R({current:1,total:T.length});const ae=T.map(se=>({name:f,k_value:z,filament_id:y,nozzle_id:G,nozzle_diameter:S,extruder_id:se,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${ae.length} profiles in batch:`,ae);try{if(await fe.setKProfilesBatch(e,ae),d(`K-profile saved to ${T.length} extruders`),u&&F){const se=`name_${f}_${y}`;u(se,F)}}catch(se){console.error("[KProfile] Failed to save batch:",se),d("Failed to save K-profiles","error"),D(!1),R({current:0,total:0});return}R({current:T.length,total:T.length}),setTimeout(()=>{D(!1),R({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(wt,{className:"w-full max-w-md relative",children:[E&&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(ut,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:k.total>1?`Saving to extruder ${k.current}/${k.total}...`:"Syncing with printer..."}),s.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:"Please wait"})]}),s.jsxs(Nt,{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:t?"Edit K-Profile":"Add K-Profile"}),s.jsx("button",{onClick:l,className:"text-bambu-gray hover:text-white transition-colors",disabled:E,children:s.jsx(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:ee,className:"p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Profile Name"}),s.jsx("input",{type:"text",value:f,onChange:ne=>m(ne.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:"My PLA Profile",required:!t})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"K-Value"}),s.jsx("input",{type:"text",inputMode:"decimal",value:g,onChange:ne=>{const z=ne.target.value;(z===""||/^\d*\.?\d*$/.test(z))&&x(z)},onBlur:ne=>{const z=parseFloat(ne.target.value);isNaN(z)||x((Math.trunc(z*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:"0.020",required:!0}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Typical range: 0.01 - 0.06 for PLA, 0.02 - 0.10 for PETG"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Filament"}),s.jsxs("select",{value:y,onChange:ne=>{const z=ne.target.value;if(b(z),!t&&z&&!f){const G=X.find(ae=>ae.id===z);G&&m(`${v==="HH00"?"HF":"S"} ${G.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:"Select filament..."}),t?.filament_id&&s.jsx("option",{value:t.filament_id,children:X.find(ne=>ne.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&X.map(ne=>s.jsx("option",{value:ne.id,children:ne.name},ne.id))]}),!t&&X.length===0&&s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"No filaments found. Create a K-profile in Bambu Studio first."})]}),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:"Flow Type"}),s.jsxs("select",{value:v,onChange:ne=>{const z=ne.target.value;if(N(z),!t&&y&&!f){const G=X.find(ae=>ae.id===y);G&&m(`${z==="HS00"?"HF":"S"} ${G.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:"High Flow"}),s.jsx("option",{value:"HS00",children:"Standard"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Nozzle Size"}),s.jsxs("select",{value:S,onChange:ne=>A(ne.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[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:t?"Extruder":"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?"Left":"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:T.includes(1),onChange:ne=>{ne.target.checked?C([...T,1]):C(T.filter(z=>z!==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:"Left"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:T.includes(0),onChange:ne=>{ne.target.checked?C([...T,0]):C(T.filter(z=>z!==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:"Right"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes (stored locally)"}),s.jsx("textarea",{value:F,onChange:ne=>O(ne.target.value),placeholder:"Add notes about this profile...",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:"Notes are saved in Bambuddy, not on the printer"})]}),s.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&s.jsx(Me,{type:"button",variant:"secondary",onClick:()=>W(!0),disabled:q.isPending||E,className:"text-red-500 hover:bg-red-500/10",children:q.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"})}),s.jsx(Me,{type:"button",variant:"secondary",onClick:l,disabled:E,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:j.isPending||E,className:"flex-1",children:[j.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(I2,{className:"w-4 h-4"}),"Save"]})]})]})]})]}),Y&&s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:s.jsx(wt,{className:"w-full max-w-sm",children:s.jsxs(Nt,{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(ln,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:"Delete Profile"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"This cannot be undone"})]})]}),s.jsxs("p",{className:"text-bambu-gray mb-6",children:["Are you sure you want to delete ",s.jsxs("span",{className:"text-white font-medium",children:['"',t?.name,'"']})," from the printer?"]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Me,{variant:"secondary",onClick:()=>W(!1),className:"flex-1",children:"Cancel"}),s.jsxs(Me,{onClick:()=>{W(!1),Z()},disabled:q.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[q.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"}),"Delete"]})]})]})})})]})}const I1={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function CKe(){const{showToast:t}=Hn(),[e,n]=w.useState(null),[r,i]=w.useState(()=>localStorage.getItem(I1.NOZZLE_DIAMETER)||"0.4"),[a,o]=w.useState(null),[l,c]=w.useState(!1),[u,d]=w.useState(null),[f,m]=w.useState(""),[g,x]=w.useState("all"),[y,b]=w.useState("all"),[v,N]=w.useState(()=>localStorage.getItem(I1.SORT_OPTION)||"name"),[S,A]=w.useState(!1),[T,C]=w.useState(new Set),[E,D]=w.useState(!1),[k,R]=w.useState(!1),F=w.useCallback(U=>`${U.slot_id}_${U.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(I1.NOZZLE_DIAMETER,r)},[r]),w.useEffect(()=>{localStorage.setItem(I1.SORT_OPTION,v)},[v]);const{data:O,isLoading:X}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:j,isLoading:q,isFetching:Y,error:W,refetch:Z}=ct({queryKey:["kprofiles",e,r],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",e,"nozzle",r);const U=await fe.getKProfiles(e,r);return console.log("[KProfiles] Received profiles:",U?.profiles?.length||0,"profiles"),U},enabled:!!e,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:ee}=ct({queryKey:["kprofiles",e,"0.4"],queryFn:()=>fe.getKProfiles(e,"0.4"),enabled:!!e,staleTime:6e4}),{data:ne,refetch:z}=ct({queryKey:["kprofile-notes",e],queryFn:()=>fe.getKProfileNotes(e),enabled:!!e,staleTime:3e4}),G=W?.message?.includes("not connected");w.useEffect(()=>{if(!e&&O&&O.length>0){const U=O.find(Q=>Q.is_active);U&&n(U.id)}},[e,O]),w.useEffect(()=>{if(e){const U=setTimeout(()=>{Z()},150);return()=>clearTimeout(U)}},[e,r]);const ae=O?.filter(U=>U.is_active)||[],se=Fr.useMemo(()=>j?.profiles?j.profiles.filter(Q=>{const le=f.toLowerCase(),ke=!le||Q.name.toLowerCase().includes(le)||Q.filament_id.toLowerCase().includes(le),Re=g==="all"||g==="left"&&Q.extruder_id===1||g==="right"&&Q.extruder_id===0,Ce=y==="all"||y==="hf"&&Q.nozzle_id.startsWith("HH")||y==="s"&&Q.nozzle_id.startsWith("HS");return ke&&Re&&Ce}).sort((Q,le)=>{switch(v){case"k_value":return parseFloat(Q.k_value)-parseFloat(le.k_value);case"filament":return GR(Q.name).localeCompare(GR(le.name));case"name":default:return Q.name.localeCompare(le.name)}}):[],[j?.profiles,f,g,y,v]),de=O?.find(U=>U.id===e),me=de?.nozzle_count===2;w.useEffect(()=>{const U=Q=>{Q.target instanceof HTMLInputElement||Q.target instanceof HTMLTextAreaElement||Q.target instanceof HTMLSelectElement||a||l||u||(Q.key==="r"||Q.key==="R"?(Q.preventDefault(),Z()):Q.key==="n"||Q.key==="N"?(Q.preventDefault(),c(!0)):Q.key==="Escape"&&S&&(Q.preventDefault(),A(!1),C(new Set)))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[a,l,u,S,Z]);const ue=w.useCallback(()=>{if(!j?.profiles||j.profiles.length===0){t("No profiles to export","error");return}const U={version:1,exported_at:new Date().toISOString(),printer:de?.name||"Unknown",nozzle_diameter:r,profiles:j.profiles.map(Re=>({name:Re.name,k_value:Re.k_value,filament_id:Re.filament_id,nozzle_id:Re.nozzle_id,nozzle_diameter:Re.nozzle_diameter,extruder_id:Re.extruder_id}))},Q=new Blob([JSON.stringify(U,null,2)],{type:"application/json"}),le=URL.createObjectURL(Q),ke=document.createElement("a");ke.href=le,ke.download=`kprofiles_${de?.name||"printer"}_${r}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke),URL.revokeObjectURL(le),t(`Exported ${j.profiles.length} profiles`)},[j?.profiles,de,r,t]),Ae=w.useCallback(()=>{const U=document.createElement("input");U.type="file",U.accept=".json",U.onchange=async Q=>{const le=Q.target.files?.[0];if(le)try{const ke=await le.text(),Re=JSON.parse(ke);if(!Re.profiles||!Array.isArray(Re.profiles)){t("Invalid file format","error");return}let Ce=0;for(const B of Re.profiles)if(!(!B.name||!B.k_value||!B.filament_id))try{await fe.setKProfile(e,{name:B.name,k_value:parseFloat(B.k_value).toFixed(6),filament_id:B.filament_id,nozzle_id:B.nozzle_id||`HH00-${r}`,nozzle_diameter:B.nozzle_diameter||r,extruder_id:B.extruder_id??0,slot_id:0}),Ce++,await new Promise(I=>setTimeout(I,500))}catch(I){console.error("Failed to import profile:",B.name,I)}t(`Imported ${Ce} of ${Re.profiles.length} profiles`),Z()}catch(ke){console.error("Import error:",ke),t("Failed to parse import file","error")}},U.click()},[e,r,t,Z]),pe=w.useCallback(U=>{C(Q=>{const le=new Set(Q);return le.has(U)?le.delete(U):le.add(U),le})},[]),Ee=w.useCallback(()=>{C(new Set(se.map(U=>F(U))))},[se,F]),_e=w.useCallback(()=>{T.size!==0&&D(!0)},[T.size]),oe=w.useCallback(async()=>{const U=se.filter(le=>T.has(F(le)));R(!0);let Q=0;for(const le of U)try{await fe.deleteKProfile(e,{slot_id:le.slot_id,extruder_id:le.extruder_id,nozzle_id:le.nozzle_id,nozzle_diameter:le.nozzle_diameter,filament_id:le.filament_id,setting_id:le.setting_id}),Q++,await new Promise(ke=>setTimeout(ke,300))}catch(ke){console.error("Failed to delete profile:",le.name,ke)}t(`Deleted ${Q} profiles`),R(!1),D(!1),A(!1),C(new Set),Z()},[e,T,se,t,Z,F]),ze=w.useCallback(U=>{const Q=[];return U.setting_id&&Q.push(U.setting_id),Q.push(`slot_${U.slot_id}_${U.filament_id}_${U.extruder_id}`),Q.push(`name_${U.name}_${U.filament_id}`),Q},[]),V=w.useCallback(async(U,Q)=>{if(e)try{await fe.setKProfileNote(e,U,Q),z()}catch(le){console.error("Failed to save note:",le),t("Failed to save note","error")}},[e,z,t]),H=w.useCallback(U=>{if(!ne?.notes)return{note:"",key:null};const Q=ze(U);for(const le of Q)if(ne.notes[le])return{note:ne.notes[le],key:le};return{note:"",key:null}},[ne,ze]),K=w.useCallback(U=>H(U).note,[H]);return X?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!O||O.length===0?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(ra,{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:"No Printers Configured"}),s.jsx("p",{className:"text-bambu-gray",children:"Add a printer in Settings to manage K-profiles"})]})}):ae.length===0?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(qr,{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:"No Active Printers"}),s.jsx("p",{className:"text-bambu-gray",children:"Enable a printer connection to view its K-profiles"})]})}):s.jsxs(s.Fragment,{children:[Y&&!q&&s.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[s.jsx(ut,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:"Loading K-Profiles..."})]}),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:"Printer"}),s.jsx("select",{value:e||"",onChange:U=>n(parseInt(U.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:ae.map(U=>s.jsx("option",{value:U.id,children:U.name},U.id))})]}),s.jsxs("div",{className:"w-32",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Nozzle"}),s.jsxs("select",{value:r,onChange:U=>i(U.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(Me,{variant:"secondary",onClick:()=>Z(),disabled:Y,children:[s.jsx(gr,{className:`w-4 h-4 ${Y?"animate-spin":""}`}),"Refresh"]}),s.jsxs(Me,{onClick:()=>c(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Profile"]})]})]}),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(_a,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),s.jsx("input",{type:"text",value:f,onChange:U=>m(U.target.value),placeholder:"Search by name or filament...",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"})]}),me&&s.jsx("div",{className:"w-36",children:s.jsxs("select",{value:g,onChange:U=>x(U.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:"All Extruders"}),s.jsx("option",{value:"left",children:"Left Only"}),s.jsx("option",{value:"right",children:"Right Only"})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:y,onChange:U=>b(U.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:"All Flow"}),s.jsx("option",{value:"hf",children:"HF Only"}),s.jsx("option",{value:"s",children:"S Only"})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:v,onChange:U=>N(U.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:"Sort: Name"}),s.jsx("option",{value:"k_value",children:"Sort: K-Value"}),s.jsx("option",{value:"filament",children:"Sort: Filament"})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[s.jsxs(Me,{variant:"secondary",onClick:ue,disabled:!j?.profiles?.length,title:"Export profiles to JSON",children:[s.jsx($r,{className:"w-4 h-4"}),"Export"]}),s.jsxs(Me,{variant:"secondary",onClick:Ae,title:"Import profiles from JSON",children:[s.jsx(di,{className:"w-4 h-4"}),"Import"]}),s.jsx("div",{className:"flex-1"}),S?s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"secondary",onClick:Ee,title:"Select all visible profiles",children:[s.jsx(Ro,{className:"w-4 h-4"}),"Select All"]}),s.jsxs(Me,{variant:"secondary",onClick:_e,disabled:T.size===0,className:"text-red-500 hover:bg-red-500/10",title:`Delete ${T.size} selected profiles`,children:[s.jsx(ln,{className:"w-4 h-4"}),"Delete (",T.size,")"]}),s.jsxs(Me,{variant:"secondary",onClick:()=>{A(!1),C(new Set)},children:[s.jsx(Ut,{className:"w-4 h-4"}),"Cancel"]})]}):s.jsxs(Me,{variant:"secondary",onClick:()=>A(!0),disabled:!se.length,title:"Enter selection mode for bulk delete",children:[s.jsx(Ro,{className:"w-4 h-4"}),"Select"]})]}),q?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):G?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(Pf,{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:"Printer Offline"}),s.jsx("p",{className:"text-bambu-gray mb-4",children:"The selected printer is not connected. Power it on to view K-profiles."}),s.jsxs(Me,{variant:"secondary",onClick:()=>Z(),children:[s.jsx(gr,{className:"w-4 h-4"}),"Retry"]})]})}):se.length>0?me?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:"Left Extruder"}),s.jsx("div",{className:"space-y-1",children:se.filter(U=>U.extruder_id===1).map(U=>s.jsx(wj,{profile:U,onEdit:()=>o(U),onCopy:()=>d(U),selectionMode:S,isSelected:T.has(F(U)),onToggleSelect:()=>pe(F(U)),note:K(U)},F(U)))})]}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:"Right Extruder"}),s.jsx("div",{className:"space-y-1",children:se.filter(U=>U.extruder_id===0).map(U=>s.jsx(wj,{profile:U,onEdit:()=>o(U),onCopy:()=>d(U),selectionMode:S,isSelected:T.has(F(U)),onToggleSelect:()=>pe(F(U)),note:K(U)},F(U)))})]})]}):s.jsx("div",{className:"space-y-1",children:se.map(U=>s.jsx(wj,{profile:U,onEdit:()=>o(U),onCopy:()=>d(U),selectionMode:S,isSelected:T.has(F(U)),onToggleSelect:()=>pe(F(U)),note:K(U)},F(U)))}):f||g!=="all"||y!=="all"?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(_a,{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:"No Matching Profiles"}),s.jsx("p",{className:"text-bambu-gray",children:"No profiles match your search criteria"})]})}):s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(I2,{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:"No K-Profiles"}),s.jsxs("p",{className:"text-bambu-gray mb-4",children:["No pressure advance profiles found for ",r,"mm nozzle"]}),s.jsxs(Me,{onClick:()=>c(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Create First Profile"]})]})}),a&&e&&(()=>{const{note:U,key:Q}=H(a);return s.jsx(Sj,{profile:a,printerId:e,nozzleDiameter:r,existingProfiles:ee?.profiles||j?.profiles,isDualNozzle:me,initialNote:U,initialNoteKey:Q,onSaveNote:V,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),o(null),Z()},onSave:()=>{o(null),Z()}})})(),l&&e&&s.jsx(Sj,{printerId:e,nozzleDiameter:r,existingProfiles:ee?.profiles||j?.profiles,isDualNozzle:me,onSaveNote:V,onClose:()=>{c(!1),Z()},onSave:()=>{c(!1),Z()}}),u&&e&&s.jsx(Sj,{printerId:e,nozzleDiameter:r,existingProfiles:ee?.profiles||j?.profiles,isDualNozzle:me,onSaveNote:V,profile:{...u,slot_id:0,name:`${u.name} (Copy)`},onClose:()=>{d(null),Z()},onSave:()=>{d(null),Z()}}),E&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-sm",children:s.jsxs(Nt,{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(ln,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:"Delete Profiles"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"This cannot be undone"})]})]}),s.jsxs("p",{className:"text-bambu-gray mb-6",children:["Are you sure you want to delete ",s.jsx("span",{className:"text-white font-medium",children:T.size})," selected profiles from the printer?"]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Me,{variant:"secondary",onClick:()=>D(!1),disabled:k,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{onClick:oe,disabled:k,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[k?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"}),"Delete"]})]})]})})})]})}function HL(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 ny(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function kKe(t){const e=vi(t);if(!e)return"";const r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4),a=Math.floor(r/36e5),o=Math.floor(r/864e5);return i<1?"Just now":i<60?`${i}m ago`:a<24?`${a}h ago`:o<7?`${o}d ago`:e.toLocaleDateString()}function jKe({onSuccess:t}){const{showToast:e}=Hn(),[n,r]=w.useState("email"),[i,a]=w.useState(""),[o,l]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState(""),[m,g]=w.useState("global"),x=ht({mutationFn:()=>fe.cloudLogin(i,o,m),onSuccess:S=>{S.success?(e("Logged in successfully"),t()):S.needs_verification?(e("Verification code sent to your email"),r("code")):e(S.message,"error")},onError:S=>e(S.message,"error")}),y=ht({mutationFn:()=>fe.cloudVerify(i,c),onSuccess:S=>{S.success?(e("Logged in successfully"),t()):e(S.message,"error")},onError:S=>e(S.message,"error")}),b=ht({mutationFn:()=>fe.cloudSetToken(d),onSuccess:()=>{e("Token set successfully"),t()},onError:S=>e(S.message,"error")}),v=S=>{S.preventDefault(),n==="email"?x.mutate():n==="code"?y.mutate():n==="token"&&b.mutate()},N=x.isPending||y.isPending||b.isPending;return s.jsx(wt,{className:"max-w-md mx-auto",children:s.jsxs(Nt,{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(R2,{className:"w-6 h-6 text-bambu-green"})}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:"Connect to Bambu Cloud"}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Sync your slicer presets across devices"})]}),s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[n==="email"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Email"}),s.jsx("input",{type:"email",value:i,onChange:S=>a(S.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:"Password"}),s.jsx("input",{type:"password",value:o,onChange:S=>l(S.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:"Region"}),s.jsxs("select",{value:m,onChange:S=>g(S.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:"Global"}),s.jsx("option",{value:"china",children:"China"})]})]})]}),n==="code"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Verification Code"}),s.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Check your email (",i,") for a 6-digit code"]}),s.jsx("input",{type:"text",value:c,onChange:S=>u(S.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})]}),n==="token"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Access Token"}),s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Paste your Bambu Lab access token (from Bambu Studio)"}),s.jsx("textarea",{value:d,onChange:S=>f(S.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:[n==="code"&&s.jsx(Me,{type:"button",variant:"secondary",onClick:()=>r("email"),className:"flex-1",children:"Back"}),s.jsxs(Me,{type:"submit",disabled:N,className:"flex-1",children:[N?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(yz,{className:"w-4 h-4"}),n==="email"?"Login":n==="code"?"Verify":"Set Token"]})]}),n==="email"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>r("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx(ef,{className:"w-4 h-4"}),"Use access token instead"]})}),n==="token"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>r("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx(yz,{className:"w-4 h-4"}),"Login with email instead"]})})]})]})})}function Tp({label:t,value:e,options:n,onChange:r}){const[i,a]=w.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(Pi,{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]=w.useState(!1);w.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?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 Nj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:a,compareDisabled:o}){const l=HL(t.name),c=ny(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&&c&&s.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:"My preset (editable)"}),s.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),l.filamentType&&t.type==="filament"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:l.filamentType}),l.layerHeight&&t.type==="process"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:l.layerHeight}),l.printer&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:l.printer})]})}),s.jsx("button",{onClick:u=>{u.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:"Duplicate",children:s.jsx(ll,{className:"w-4 h-4"})})]})}function qR(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:[S&&d&&s.jsx("button",{onClick:T=>{T.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(Ya,{className:"w-4 h-4"})}),S?s.jsx("div",{...f,...m,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(ag,{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?fe.getArchivePlateThumbnail(t.archive_id,t.plate_id):fe.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?s.jsx("img",{src:t.plate_id!=null?fe.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):fe.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(ul,{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(ms,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:"View archive",children:s.jsx(Ur,{className:"w-3.5 h-3.5"})}):t.library_file_id?s.jsx(ms,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:"View in File Manager",children:s.jsx(Ur,{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?"text-orange-400":""}`,children:[s.jsx(qr,{className:"w-3.5 h-3.5"}),t.printer_id===null?"Unassigned":t.printer_name||`Printer #${t.printer_id}`]}),t.print_time_seconds&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_d,{className:"w-3.5 h-3.5"}),Sre(t.print_time_seconds)]}),S&&!t.manual_start&&s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wn,{className:"w-3.5 h-3.5"}),IWe(t.scheduled_time,c)]})]}),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(oW,{className:"w-3 h-3"}),"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:"Requires previous success"}),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(xu,{className:"w-3 h-3"}),"Auto power off"]})]}),N&&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:"Printing in progress..."})]}),t.error_message&&s.jsxs("p",{className:"text-xs text-red-400 mt-2 flex items-center gap-1",children:[s.jsx(ra,{className:"w-3 h-3"}),t.error_message]})]}),s.jsx(FWe,{status:t.status}),s.jsxs("div",{className:"flex items-center gap-1",children:[N&&s.jsx(Me,{variant:"ghost",size:"sm",onClick:a,title:"Stop Print",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Kce,{className:"w-4 h-4"})}),S&&s.jsxs(s.Fragment,{children:[t.manual_start&&s.jsx(Me,{variant:"ghost",size:"sm",onClick:l,title:"Start Print",className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10",children:s.jsx(Po,{className:"w-4 h-4"})}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:n,title:"Edit",children:s.jsx(ia,{className:"w-4 h-4"})}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:r,title:"Cancel",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",children:s.jsx(Ut,{className:"w-4 h-4"})})]}),A&&s.jsxs(s.Fragment,{children:[s.jsx(Me,{variant:"ghost",size:"sm",onClick:o,title:"Re-queue",className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10",children:s.jsx(gr,{className:"w-4 h-4"})}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:i,title:"Remove",children:s.jsx(ln,{className:"w-4 h-4"})})]})]})]})})}function zWe(){const t=an(),{showToast:e}=Hn(),[n,r]=w.useState(null),[i,a]=w.useState(""),[o,l]=w.useState(!1),[c,u]=w.useState(null),[d,f]=w.useState(null),[m,g]=w.useState(null),[x,y]=w.useState([]),[b,v]=w.useState(!1),[N,S]=w.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[A,T]=w.useState(()=>{const _e=localStorage.getItem("queue.historySortAsc");return _e!==null?_e==="true":!1}),[C,E]=w.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[D,k]=w.useState(()=>{const _e=localStorage.getItem("queue.pendingSortAsc");return _e!==null?_e==="true":!0});w.useEffect(()=>{localStorage.setItem("queue.historySortBy",N)},[N]),w.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(A))},[A]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",C)},[C]),w.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(D))},[D]);const R=Zne(M2(mM,{activationConstraint:{distance:8}}),M2(fM,{coordinateGetter:_re})),{data:F}=ct({queryKey:["settings"],queryFn:fe.getSettings}),O=F?.time_format||"system",{data:X,isLoading:j}=ct({queryKey:["queue",n,i],queryFn:()=>fe.getQueue(n||void 0,i||void 0),refetchInterval:5e3}),{data:q}=ct({queryKey:["printers"],queryFn:()=>fe.getPrinters()}),Y=ht({mutationFn:_e=>fe.cancelQueueItem(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Queue item cancelled")},onError:()=>e("Failed to cancel item","error")}),W=ht({mutationFn:_e=>fe.removeFromQueue(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Queue item removed")},onError:()=>e("Failed to remove item","error")}),Z=ht({mutationFn:_e=>fe.stopQueueItem(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Print stopped")},onError:()=>e("Failed to stop print","error")}),ee=ht({mutationFn:_e=>fe.startQueueItem(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]}),e("Print released to queue")},onError:()=>e("Failed to start print","error")}),ne=ht({mutationFn:_e=>fe.reorderQueue(_e),onSuccess:()=>{t.invalidateQueries({queryKey:["queue"]})},onError:()=>e("Failed to reorder queue","error")}),z=ht({mutationFn:async()=>{const _e=X?.filter(oe=>["completed","failed","skipped","cancelled"].includes(oe.status))||[];for(const oe of _e)await fe.removeFromQueue(oe.id);return _e.length},onSuccess:_e=>{t.invalidateQueries({queryKey:["queue"]}),e(`Cleared ${_e} history item${_e!==1?"s":""}`)},onError:()=>e("Failed to clear history","error")}),G=ht({mutationFn:_e=>fe.bulkUpdateQueue(_e),onSuccess:_e=>{t.invalidateQueries({queryKey:["queue"]}),y([]),v(!1),e(_e.message)},onError:()=>e("Failed to update items","error")}),ae=ht({mutationFn:async _e=>{for(const oe of _e)await fe.cancelQueueItem(oe);return _e.length},onSuccess:_e=>{t.invalidateQueries({queryKey:["queue"]}),y([]),e(`Cancelled ${_e} item${_e!==1?"s":""}`)},onError:()=>e("Failed to cancel items","error")}),se=_e=>{y(oe=>oe.includes(_e)?oe.filter(ze=>ze!==_e):[...oe,_e])},de=w.useMemo(()=>{const _e=X?.filter(ze=>ze.status==="pending")||[],oe=ze=>{if(!ze.scheduled_time)return 0;const V=new Date(ze.scheduled_time).getTime(),H=Date.now()+4320*60*60*1e3;return V>H?0:V};return[..._e].sort((ze,V)=>{let H;if(C==="name"){const K=ze.archive_name||ze.library_file_name||"",U=V.archive_name||V.library_file_name||"";H=K.localeCompare(U)}else C==="printer"?H=(ze.printer_name||"").localeCompare(V.printer_name||""):C==="time"?H=oe(ze)-oe(V):H=ze.position-V.position;return D?H:-H})},[X,C,D]),me=()=>{const _e=de.map(oe=>oe.id);x.length===_e.length?y([]):y(_e)},ue=X?.filter(_e=>_e.status==="printing")||[],Ae=w.useMemo(()=>[...X?.filter(oe=>["completed","failed","skipped","cancelled"].includes(oe.status))||[]].sort((oe,ze)=>{let V;if(N==="name"){const H=oe.archive_name||oe.library_file_name||"",K=ze.archive_name||ze.library_file_name||"";V=H.localeCompare(K)}else N==="printer"?V=(oe.printer_name||"").localeCompare(ze.printer_name||""):V=new Date(ze.completed_at||ze.created_at).getTime()-new Date(oe.completed_at||oe.created_at).getTime();return A?-V:V}),[X,N,A]),pe=w.useMemo(()=>de.reduce((_e,oe)=>_e+(oe.print_time_seconds||0),0),[de]),Ee=_e=>{const{active:oe,over:ze}=_e;if(!ze||oe.id===ze.id)return;const V=de.findIndex(K=>K.id===oe.id),H=de.findIndex(K=>K.id===ze.id);if(V!==-1&&H!==-1){const U=xM(de,V,H).map((Q,le)=>({id:Q.id,position:le+1}));ne.mutate(U)}};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(lW,{className:"w-7 h-7 text-bambu-green"}),"Print Queue"]}),s.jsx("p",{className:"text-bambu-gray mt-1",children:"Schedule and manage your print jobs"})]})}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-8",children:[s.jsx(wt,{className:"bg-gradient-to-br from-blue-500/10 to-transparent border-blue-500/20",children:s.jsx(Nt,{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(Po,{className:"w-5 h-5 text-blue-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:ue.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Printing"})]})]})})}),s.jsx(wt,{className:"bg-gradient-to-br from-yellow-500/10 to-transparent border-yellow-500/20",children:s.jsx(Nt,{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(Wn,{className:"w-5 h-5 text-yellow-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:de.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Queued"})]})]})})}),s.jsx(wt,{className:"bg-gradient-to-br from-bambu-green/10 to-transparent border-bambu-green/20",children:s.jsx(Nt,{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(_d,{className:"w-5 h-5 text-bambu-green"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Sre(pe)}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Total Queue Time"})]})]})})}),s.jsx(wt,{className:"bg-gradient-to-br from-gray-500/10 to-transparent border-gray-500/20",children:s.jsx(Nt,{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(Dn,{className:"w-5 h-5 text-gray-400"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-2xl font-bold text-white",children:Ae.length}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"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:n===-1?"unassigned":n||"",onChange:_e=>{const oe=_e.target.value;r(oe==="unassigned"?-1:oe===""?null:Number(oe))},children:[s.jsx("option",{value:"",children:"All Printers"}),s.jsx("option",{value:"unassigned",children:"Unassigned"}),q?.map(_e=>s.jsx("option",{value:_e.id,children:_e.name},_e.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:i,onChange:_e=>a(_e.target.value),children:[s.jsx("option",{value:"",children:"All Status"}),s.jsx("option",{value:"pending",children:"Pending"}),s.jsx("option",{value:"printing",children:"Printing"}),s.jsx("option",{value:"completed",children:"Completed"}),s.jsx("option",{value:"failed",children:"Failed"}),s.jsx("option",{value:"skipped",children:"Skipped"}),s.jsx("option",{value:"cancelled",children:"Cancelled"})]}),s.jsx("div",{className:"flex-1"}),Ae.length>0&&s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>l(!0),children:[s.jsx(ln,{className:"w-4 h-4"}),"Clear History"]})]}),j?s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"Loading..."}):X?.length===0?s.jsxs(wt,{className:"p-12 text-center border-dashed",children:[s.jsx(ii,{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:"No prints scheduled"}),s.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:'Schedule a print from the Archives page using the "Schedule" option in the context menu, or drag and drop files to get started.'})]}):s.jsxs("div",{className:"space-y-8",children:[ue.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"}),"Currently Printing"]}),s.jsx("div",{className:"space-y-3",children:ue.map(_e=>s.jsx(_j,{item:_e,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>g({type:"stop",item:_e}),onRequeue:()=>{},onStart:()=>{},timeFormat:O},_e.id))})]}),de.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(Wn,{className:"w-5 h-5 text-yellow-400"}),"Queued",s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",de.length," item",de.length!==1?"s":"",")"]}),s.jsx("span",{className:"text-xs text-bambu-gray ml-2",title:"Position only affects ASAP items. Scheduled items run at their set time.",children:"Drag to reorder (ASAP only)"})]}),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:C,onChange:_e=>E(_e.target.value),children:[s.jsx("option",{value:"position",children:"Sort by Position"}),s.jsx("option",{value:"name",children:"Sort by Name"}),s.jsx("option",{value:"printer",children:"Sort by Printer"}),s.jsx("option",{value:"time",children:"Sort by Schedule"})]}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>k(!D),title:D?"Ascending":"Descending",className:"px-2",children:D?s.jsx(ig,{className:"w-4 h-4"}):s.jsx(h0,{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(Me,{variant:"ghost",size:"sm",onClick:me,className:"flex items-center gap-2",children:[x.length===de.length&&de.length>0?s.jsx(Ro,{className:"w-4 h-4 text-bambu-green"}):s.jsx(Do,{className:"w-4 h-4"}),x.length===de.length&&de.length>0?"Deselect All":"Select All"]}),x.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"text-sm text-bambu-gray",children:[x.length," selected"]}),s.jsx("div",{className:"h-4 w-px bg-bambu-dark-tertiary"}),s.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>v(!0),className:"flex items-center gap-2 text-bambu-green hover:text-bambu-green-light",children:[s.jsx(ia,{className:"w-4 h-4"}),"Edit Selected"]}),s.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>ae.mutate(x),className:"flex items-center gap-2 text-red-400 hover:text-red-300",disabled:ae.isPending,children:[s.jsx(Ut,{className:"w-4 h-4"}),"Cancel Selected"]})]})]}),s.jsx(pre,{sensors:R,collisionDetection:nre,onDragEnd:Ee,children:s.jsx(bre,{items:de.map(_e=>_e.id),strategy:EWe,children:s.jsx("div",{className:"space-y-3",children:de.map((_e,oe)=>s.jsx(_j,{item:_e,position:oe+1,onEdit:()=>u(_e),onCancel:()=>g({type:"cancel",item:_e}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>ee.mutate(_e.id),timeFormat:O,isSelected:x.includes(_e.id),onToggleSelect:()=>se(_e.id)},_e.id))})})})]}),Ae.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(Dn,{className:"w-5 h-5 text-bambu-gray"}),"History",s.jsxs("span",{className:"text-sm font-normal text-bambu-gray",children:["(",Ae.length," item",Ae.length!==1?"s":"",")"]})]}),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:N,onChange:_e=>S(_e.target.value),children:[s.jsx("option",{value:"date",children:"Sort by Date"}),s.jsx("option",{value:"name",children:"Sort by Name"}),s.jsx("option",{value:"printer",children:"Sort by Printer"})]}),s.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>T(!A),title:A?"Ascending (oldest first)":"Descending (newest first)",className:"px-2",children:A?s.jsx(ig,{className:"w-4 h-4"}):s.jsx(h0,{className:"w-4 h-4"})})]})]}),s.jsx("div",{className:"space-y-3",children:Ae.slice(0,20).map((_e,oe)=>s.jsx(_j,{item:_e,position:oe+1,onEdit:()=>{},onCancel:()=>{},onRemove:()=>g({type:"remove",item:_e}),onStop:()=>{},onRequeue:()=>f(_e),onStart:()=>{},timeFormat:O},_e.id))})]})]}),c&&s.jsx(th,{mode:"edit-queue-item",archiveId:c.archive_id??void 0,libraryFileId:c.library_file_id??void 0,archiveName:c.archive_name||c.library_file_name||`File #${c.archive_id||c.library_file_id}`,queueItem:c,onClose:()=>u(null)}),d&&s.jsx(th,{mode:"add-to-queue",archiveId:d.archive_id??void 0,libraryFileId:d.library_file_id??void 0,archiveName:d.archive_name||d.library_file_name||`File #${d.archive_id||d.library_file_id}`,onClose:()=>f(null)}),m&&s.jsx(Fn,{title:m.type==="cancel"?"Cancel Scheduled Print":m.type==="stop"?"Stop Print":"Remove from History",message:m.type==="cancel"?`Are you sure you want to cancel "${m.item.archive_name||m.item.library_file_name||"this print"}"?`:m.type==="stop"?`Are you sure you want to stop the current print "${m.item.archive_name||m.item.library_file_name||"this print"}"? This will cancel the print job on the printer.`:`Are you sure you want to remove "${m.item.archive_name||m.item.library_file_name||"this item"}" from the queue history?`,confirmText:m.type==="cancel"?"Cancel Print":m.type==="stop"?"Stop Print":"Remove",variant:"danger",onConfirm:()=>{m.type==="cancel"?Y.mutate(m.item.id):m.type==="stop"?Z.mutate(m.item.id):W.mutate(m.item.id),g(null)},onCancel:()=>g(null)}),o&&s.jsx(Fn,{title:"Clear History",message:`Are you sure you want to remove all ${Ae.length} item${Ae.length!==1?"s":""} from the history?`,confirmText:"Clear History",variant:"danger",onConfirm:()=>{z.mutate(),l(!1)},onCancel:()=>l(!1)}),b&&s.jsx(UWe,{selectedCount:x.length,printers:q?.map(_e=>({id:_e.id,name:_e.name}))||[],onSave:_e=>{Object.keys(_e).length>0&&G.mutate({item_ids:x,..._e})},onClose:()=>v(!1),isSaving:G.isPending})]})}function BWe({printDates:t,months:e=3}){const n=w.useRef(null),[r,i]=w.useState(0);w.useEffect(()=>{const N=n.current;if(!N)return;const S=new ResizeObserver(A=>{const T=A[0]?.contentRect.width||0;i(T)});return S.observe(N),()=>S.disconnect()},[]);const{weeks:a,monthLabels:o,printCounts:l}=w.useMemo(()=>{const N={};t.forEach(F=>{const O=F.split("T")[0];N[O]=(N[O]||0)+1});const S=new Date,A=new Date(S);A.setMonth(A.getMonth()-e),A.setDate(A.getDate()-A.getDay());const T=[],C=[];let E=[],D=-1;const k=new Date(A);let R=0;for(;k<=S;)k.getDay()===0&&E.length>0&&(T.push(E),E=[],R++),k.getMonth()!==D&&(C.push({month:k.toLocaleDateString("en-US",{month:"short"}),weekIndex:R}),D=k.getMonth()),E.push(new Date(k)),k.setDate(k.getDate()+1);return E.length>0&&T.push(E),{weeks:T,monthLabels:C,printCounts:N}},[t,e]),c=Math.max(1,...Object.values(l)),u=N=>{if(N===0)return"bg-bambu-dark";const S=N/c;return S<=.25?"bg-bambu-green/30":S<=.5?"bg-bambu-green/50":S<=.75?"bg-bambu-green/75":"bg-bambu-green"},d=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],f=a.length,m=32,g=2,x=r-m-16,y=f>0?Math.floor((x-(f-1)*g)/f):12,b=Math.max(8,Math.min(20,y)),v=b<=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:m+4},children:o.map(({month:N,weekIndex:S},A)=>s.jsx("div",{className:"text-bambu-gray",style:{fontSize:v,marginLeft:A===0?0:`${(S-(o[A-1]?.weekIndex||0))*(b+g)-24}px`},children:N},A))}),s.jsxs("div",{className:"flex",style:{gap:g},children:[s.jsx("div",{className:"flex flex-col",style:{gap:g,marginRight:4,width:m},children:d.map((N,S)=>s.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:m,height:b,fontSize:v,visibility:S%2===1?"visible":"hidden"},children:N},N))}),a.map((N,S)=>s.jsx("div",{className:"flex flex-col",style:{gap:g},children:[0,1,2,3,4,5,6].map(A=>{const T=N.find(k=>k.getDay()===A);if(!T)return s.jsx("div",{style:{width:b,height:b}},A);const C=T.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:b,height:b},title:`${T.toLocaleDateString()}: ${E} print${E!==1?"s":""}`},A)})},S))]}),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:g},children:[s.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),s.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),s.jsx("span",{children:"More"})]})]})})}const O1=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"];function $We(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 HWe({archives:t,currency:e="$"}){const[n,r]=w.useState("30d"),i=w.useMemo(()=>{const m=$We(n);return t.filter(g=>(vi(g.completed_at||g.created_at)||new Date(0))>=m)},[t,n]),a=w.useMemo(()=>{const m=new Map;return i.forEach(g=>{const x=vi(g.completed_at||g.created_at)||new Date,y=`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,b=m.get(y)||{date:y,filament:0,cost:0,prints:0};b.filament+=g.filament_used_grams||0,b.cost+=g.cost||0,b.prints+=1,m.set(y,b)}),Array.from(m.values()).sort((g,x)=>g.date.localeCompare(x.date)).map(g=>({...g,dateLabel:new Date(g.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[i]),o=w.useMemo(()=>{if(n==="7d"||n==="30d")return a;const m=new Map;return i.forEach(g=>{const x=vi(g.completed_at||g.created_at)||new Date,y=new Date(x);y.setDate(x.getDate()-x.getDay());const b=`${y.getFullYear()}-${String(y.getMonth()+1).padStart(2,"0")}-${String(y.getDate()).padStart(2,"0")}`,v=m.get(b)||{week:b,filament:0,cost:0,prints:0};v.filament+=g.filament_used_grams||0,v.cost+=g.cost||0,v.prints+=1,m.set(b,v)}),Array.from(m.values()).sort((g,x)=>g.week.localeCompare(x.week)).map(g=>({date:g.week,dateLabel:`Week of ${new Date(g.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...g}))},[i,a,n]),l=w.useMemo(()=>{const m=new Map;return i.forEach(g=>{const y=(g.filament_type||"Unknown").split(", ");y.forEach(b=>{const v=(g.filament_used_grams||0)/y.length;m.set(b,(m.get(b)||0)+v)})}),Array.from(m.entries()).map(([g,x])=>({name:g,value:Math.round(x)})).sort((g,x)=>x.value-g.value)},[i]),c=w.useMemo(()=>{const m=new Date,g=[];for(let x=5;x>=0;x--){const y=new Date(m.getFullYear(),m.getMonth()-x,1),b=new Date(m.getFullYear(),m.getMonth()-x+1,0),v=y.toLocaleDateString("en-US",{month:"short",year:"2-digit"}),N=t.filter(S=>{const A=vi(S.completed_at||S.created_at)||new Date(0);return A>=y&&A<=b});g.push({month:v,filament:Math.round(N.reduce((S,A)=>S+(A.filament_used_grams||0),0)),cost:N.reduce((S,A)=>S+(A.cost||0),0),prints:N.length})}return g},[t]),u=n==="7d"||n==="30d"?a:o,d=i.reduce((m,g)=>m+(g.filament_used_grams||0),0),f=i.reduce((m,g)=>m+(g.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(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:[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(G1,{width:"100%",height:250,children:s.jsxs(Uke,{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(mS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx(gS,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),s.jsx(xS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),s.jsx(W1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:m=>[`${Number(m??0).toFixed(0)}g`,"Filament"]}),s.jsx(_Z,{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(G1,{width:160,height:160,children:s.jsxs(Ike,{children:[s.jsx(GQ,{data:l,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:l.map((m,g)=>s.jsx(jy,{fill:O1[g%O1.length]},`cell-${g}`))}),s.jsx(W1,{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,g)=>{const x=l.reduce((b,v)=>b+v.value,0),y=x>0?(m.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:O1[g%O1.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(G1,{width:"100%",height:200,children:s.jsxs(Mke,{data:c,children:[s.jsx(mS,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),s.jsx(gS,{dataKey:"month",stroke:"#9ca3af",tick:{fontSize:12}}),s.jsx(xS,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:m=>`${m}g`}),s.jsx(W1,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:(m,g)=>[g==="filament"?`${m??0}g`:g==="cost"?`${e}${Number(m??0).toFixed(2)}`:m??0,g==="filament"?"Filament":g==="cost"?"Cost":"Prints"]}),s.jsx(GD,{}),s.jsx(QQ,{dataKey:"filament",name:"Filament (g)",fill:"#00ae42",radius:[4,4,0,0]})]})})]})]})]})}function VWe({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:m}=vre({id:t}),g={transform:Dg.Transform.toString(d),transition:f,opacity:m?.5:1};return r?null:s.jsxs("div",{ref:u,style:{...g,gridColumn:`span ${i}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${m?"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(ag,{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(uW,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):s.jsx(cW,{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(D2,{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 GWe({widgets:t,storageKey:e,columns:n=4,hideControls:r=!1,onResetLayout:i,renderControls:a}){const o=()=>{const A={};return t.forEach(T=>{A[T.id]=T.defaultSize||4}),A},[l,c]=w.useState(()=>{const A=localStorage.getItem(e);if(A)try{const T=JSON.parse(A);return T.sizes||(T.sizes=o()),T}catch{}return{order:t.map(T=>T.id),hidden:t.filter(T=>T.defaultVisible===!1).map(T=>T.id),sizes:o()}}),[u,d]=w.useState(!1);w.useEffect(()=>{const A=()=>d(T=>!T);return window.addEventListener("toggle-hidden-panel",A),()=>window.removeEventListener("toggle-hidden-panel",A)},[]),w.useEffect(()=>{localStorage.setItem(e,JSON.stringify(l))},[l,e]),w.useEffect(()=>{const T=t.map(C=>C.id).filter(C=>!l.order.includes(C));T.length>0&&c(C=>({...C,order:[...C.order,...T]}))},[t,l.order]);const f=Zne(M2(mM,{activationConstraint:{distance:8}}),M2(fM,{coordinateGetter:_re})),m=A=>{const{active:T,over:C}=A;C&&T.id!==C.id&&c(E=>{const D=E.order.indexOf(T.id),k=E.order.indexOf(C.id);return{...E,order:xM(E.order,D,k)}})},g=A=>{c(T=>({...T,hidden:T.hidden.includes(A)?T.hidden.filter(C=>C!==A):[...T.hidden,A]}))},x=A=>{c(T=>{const C=T.sizes[A]||4,E=C===1?2:C===2?4:1;return{...T,sizes:{...T.sizes,[A]:E}}})},y=()=>{const A={order:t.map(T=>T.id),hidden:t.filter(T=>T.defaultVisible===!1).map(T=>T.id),sizes:o()};c(A),i?.()},b=l.order.map(A=>t.find(T=>T.id===A)).filter(Boolean),v=b.filter(A=>!l.hidden.includes(A.id)),N=b.filter(A=>l.hidden.includes(A.id)),S=a?.({hiddenCount:N.length,showHiddenPanel:u,setShowHiddenPanel:d,resetLayout:y});return s.jsxs("div",{className:"space-y-4",children:[S,!r&&!a&&s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsxs(Me,{variant:"secondary",size:"sm",onClick:y,children:[s.jsx(Zf,{className:"w-4 h-4"}),"Reset Layout"]}),N.length>0&&s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>d(!u),children:[s.jsx(ou,{className:"w-4 h-4"}),N.length," Hidden"]})]}),u&&N.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:N.map(A=>s.jsxs("button",{onClick:()=>g(A.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(ou,{className:"w-3 h-3"}),A.title]},A.id))})]}),s.jsx(pre,{sensors:f,collisionDetection:nre,onDragEnd:m,children:s.jsx(bre,{items:v.map(A=>A.id),strategy:$L,children:s.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${n}, minmax(0, 1fr))`},children:v.map(A=>s.jsx(VWe,{id:A.id,title:A.title,component:A.component,isHidden:l.hidden.includes(A.id),size:l.sizes[A.id]||2,onToggleVisibility:()=>g(A.id),onToggleSize:()=>x(A.id)},A.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(Me,{className:"mt-4",onClick:y,children:"Reset Layout"})]})]})}function qWe({stats:t,currency:e}){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(Bl,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Total Prints"}),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(Wn,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Print Time"}),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(Bl,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament Used"}),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(Gj,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Filament Cost"}),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(Vd,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Energy Used"}),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(Gj,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("p",{className:"text-xs text-bambu-gray",children:"Energy Cost"}),s.jsxs("p",{className:"text-xl font-bold text-white",children:[e," ",t?.total_energy_cost.toFixed(2)||"0.00"]})]})]})]})}function WWe({stats:t,printerMap:e,size:n=1}){const r=t?.total_prints?Math.round(t.successful_prints/t.total_prints*100):0,i=n===1?112:n===2?128:144,a=i/2-8,o=a*2*Math.PI;return s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsxs("div",{className:"relative flex-shrink-0",style:{width:i,height:i},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:i/2,cy:i/2,r:a,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:i/2,cy:i/2,r:a,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${r/100*o} ${o}`})]}),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:[r,"%"]})})]}),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(Dn,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:"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(ea,{className:"w-4 h-4 text-status-error flex-shrink-0"}),s.jsx("span",{className:"text-sm text-bambu-gray",children:"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:"Prints by Printer"}),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(([l,c])=>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(l)||`Printer ${l}`}),s.jsx("span",{className:"text-white font-medium",children:c})]},l))})]})]})]})}function KWe({stats:t,printerMap:e,size:n=1}){const r=t?.average_time_accuracy;if(r==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:"No time accuracy data yet"})});const a=(Math.min(150,Math.max(50,r))-50)/100*100,l=(x=>x>=95&&x<=105?"#00ae42":x>105?"#3b82f6":"#f97316")(r),c=r-100,u=n===1?112:n===2?128:144,d=u/2-8,f=d*2*Math.PI,m=n===1?3:n===2?6:999,g=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:u,height:u},children:[s.jsxs("svg",{className:"w-full h-full -rotate-90",children:[s.jsx("circle",{cx:u/2,cy:u/2,r:d,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),s.jsx("circle",{cx:u/2,cy:u/2,r:d,fill:"none",stroke:l,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${a/100*f} ${f}`})]}),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:[r.toFixed(0),"%"]}),s.jsxs("span",{className:`text-xs ${c>=0?"text-blue-400":"text-orange-400"}`,children:[c>=0?"+":"",c.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(pW,{className:"w-3 h-3 flex-shrink-0"}),s.jsx("span",{children:"100% = perfect estimate"})]}),g.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:g.map(([x,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(x)||`Printer ${x}`}),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),"%"]})]},x))})]})]})}function XWe({stats:t,size:e=1}){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:"No filament data available"});const n=Object.entries(t.prints_by_filament_type).sort(([,o],[,l])=>l-o),r=e===1?5:e===2?8:999,i=n.slice(0,r),a=n.length>r;return e===4&&i.length>4?s.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:i.map(([o,l])=>{const c=Math.round(l/(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:o}),s.jsx("span",{className:"text-bambu-gray",children:l})]}),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:`${c}%`}})})]},o)})}):s.jsxs("div",{className:"space-y-3",children:[i.map(([o,l])=>{const c=Math.round(l/(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:o}),s.jsxs("span",{className:"text-bambu-gray",children:[l," 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:`${c}%`}})})]},o)}),a&&s.jsxs("p",{className:"text-xs text-bambu-gray text-center pt-1",children:["+",n.length-r," more types"]})]})}function YWe({printDates:t,size:e=2}){const n=e===1?3:e===2?6:12;return s.jsx(BWe,{printDates:t,months:n})}function QWe({stats:t,printerMap:e}){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:"No printer data available"}):s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:Object.entries(t.prints_by_printer).map(([n,r])=>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(qr,{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(n)||`Printer ${n}`}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[r," prints"]})]})]},n))})}function ZWe({archives:t,currency:e}){return!t||t.length===0?s.jsx("p",{className:"text-bambu-gray text-center py-4",children:"No print data available"}):s.jsx(HWe,{archives:t,currency:e})}function JWe({size:t=1}){const{data:e,isLoading:n}=ct({queryKey:["failureAnalysis"],queryFn:()=>fe.getFailureAnalysis({days:30})});if(n)return s.jsx("div",{className:"flex justify-center py-4",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!e||e.total_prints===0)return s.jsx("p",{className:"text-bambu-gray text-center py-4",children:"No print data in the last 30 days"});const r=t===1?5:t===2?8:999,i=Object.entries(e.failures_by_reason).sort(([,l],[,c])=>c-l),a=i.slice(0,r),o=i.length>r;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(Nn,{className:`w-5 h-5 ${e.failure_rate>20?"text-status-error":e.failure_rate>10?"text-status-warning":"text-status-ok"}`}),s.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[e.failure_rate.toFixed(1),"%"]})]})}),s.jsxs("div",{className:"text-sm text-bambu-gray mt-1",children:[e.failed_prints," / ",e.total_prints," prints failed"]}),e.trend&&e.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(xW,{className:`w-4 h-4 ${e.trend[e.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?"Failure Reasons":"Top Failure Reasons"}),s.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:a.map(([l,c])=>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:l||"Unknown"}),s.jsx("span",{className:"text-bambu-gray ml-2",children:c})]},l))}),o&&s.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:["+",i.length-r," more reasons"]})]})]})}function eKe(){const{showToast:t}=Hn(),[e,n]=w.useState(!1),[r,i]=w.useState(!1),[a,o]=w.useState(0),[l,c]=w.useState(0),[u,d]=w.useState(!1);w.useEffect(()=>{const E=()=>{try{const k=localStorage.getItem("bambusy-dashboard-layout");if(k){const R=JSON.parse(k);c(R.hidden?.length||0)}}catch{c(0)}};E(),window.addEventListener("storage",E);const D=setInterval(E,500);return()=>{window.removeEventListener("storage",E),clearInterval(D)}},[a]);const{data:f,isLoading:m,refetch:g}=ct({queryKey:["archiveStats"],queryFn:fe.getArchiveStats}),{data:x}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:y}=ct({queryKey:["archives"],queryFn:()=>fe.getArchives(void 0,void 0,1e3,0)}),{data:b}=ct({queryKey:["settings"],queryFn:fe.getSettings}),v=async E=>{i(!1),n(!0);try{const{blob:D,filename:k}=await fe.exportStats({format:E,days:90}),R=URL.createObjectURL(D),F=document.createElement("a");F.href=R,F.download=k,F.click(),URL.revokeObjectURL(R),t("Export downloaded")}catch{t("Export failed","error")}finally{n(!1)}},N=async()=>{d(!0);try{const E=await fe.recalculateCosts();await g(),t(`Recalculated costs for ${E.updated} archives`)}catch{t("Failed to recalculate costs","error")}finally{d(!1)}},S=b?.currency||"$",A=new Map(x?.map(E=>[String(E.id),E.name])||[]),T=y?.map(E=>E.created_at)||[];if(m)return s.jsx("div",{className:"p-4 md:p-8",children:s.jsx("div",{className:"text-center py-12 text-bambu-gray",children:"Loading statistics..."})});const C=[{id:"quick-stats",title:"Quick Stats",component:s.jsx(qWe,{stats:f,currency:S}),defaultSize:2},{id:"success-rate",title:"Success Rate",component:E=>s.jsx(WWe,{stats:f,printerMap:A,size:E}),defaultSize:1},{id:"time-accuracy",title:"Time Accuracy",component:E=>s.jsx(KWe,{stats:f,printerMap:A,size:E}),defaultSize:1},{id:"filament-types",title:"Filament Types",component:E=>s.jsx(XWe,{stats:f,size:E}),defaultSize:1},{id:"failure-analysis",title:"Failure Analysis (30 days)",component:E=>s.jsx(JWe,{size:E}),defaultSize:1},{id:"print-activity",title:"Print Activity",component:E=>s.jsx(YWe,{printDates:T,size:E}),defaultSize:2},{id:"prints-by-printer",title:"Prints by Printer",component:s.jsx(QWe,{stats:f,printerMap:A}),defaultSize:2},{id:"filament-trends",title:"Filament Usage Trends",component:s.jsx(ZWe,{archives:y||[],currency:S}),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:"Dashboard"}),s.jsx("p",{className:"text-bambu-gray",children:"Drag widgets to rearrange. Click the eye icon to hide."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[l>0&&s.jsxs(Me,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[s.jsx(ou,{className:"w-4 h-4"}),l," Hidden"]}),s.jsxs(Me,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout"),o(E=>E+1),t("Layout reset")},children:[s.jsx(Zf,{className:"w-4 h-4"}),"Reset Layout"]}),s.jsxs(Me,{variant:"secondary",onClick:N,disabled:u,title:"Recalculate all archive costs using current filament prices",children:[u?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Cce,{className:"w-4 h-4"}),"Recalculate Costs"]}),s.jsxs("div",{className:"relative",children:[s.jsxs(Me,{variant:"secondary",onClick:()=>i(!r),disabled:e,children:[e?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(bw,{className:"w-4 h-4"}),"Export Stats"]}),r&&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:()=>v("csv"),children:[s.jsx(Ga,{className:"w-4 h-4"}),"Export as CSV"]}),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:()=>v("xlsx"),children:[s.jsx(bw,{className:"w-4 h-4"}),"Export as Excel"]})]})]})]})]}),s.jsx(GWe,{widgets:C,storageKey:"bambusy-dashboard-layout",hideControls:!0},a)]})}function tKe({plug:t,onEdit:e}){const n=an(),{showToast:r}=Hn(),[i,a]=w.useState(!1),[o,l]=w.useState(!1),[c,u]=w.useState(!1),[d,f]=w.useState(!1),{data:m,isLoading:g}=ct({queryKey:["smart-plug-status",t.id],queryFn:()=>fe.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:x}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),y=x?.find(k=>k.id===t.printer_id),b=ht({mutationFn:k=>fe.controlSmartPlug(t.id,k),onMutate:async k=>{await n.cancelQueries({queryKey:["smart-plug-status",t.id]});const R=n.getQueryData(["smart-plug-status",t.id]),F=k==="on"?"ON":k==="off"||m?.state==="ON"?"OFF":"ON";return n.setQueryData(["smart-plug-status",t.id],O=>({...O,state:F})),{previousStatus:R}},onError:(k,R,F)=>{F?.previousStatus&&n.setQueryData(["smart-plug-status",t.id],F.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=ht({mutationFn:k=>fe.updateSmartPlug(t.id,k),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&n.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]})}}),N=ht({mutationFn:()=>fe.deleteSmartPlug(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]})}}),S=m?.state==="ON",A=t.plug_type==="mqtt"&&m?.energy?.power!==null&&m?.energy?.power!==void 0,T=(m?.reachable??!1)||A,C=b.isPending,D=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const k=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${k}/`:`http://${k}/`})();return s.jsxs(s.Fragment,{children:[s.jsx(wt,{className:"relative",children:s.jsxs(Nt,{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"?T?"bg-teal-500/20":"bg-red-500/20":T?S?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?s.jsx(fD,{className:`w-5 h-5 ${T?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?s.jsx(U2,{className:`w-5 h-5 ${T?S?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):s.jsx(Gs,{className:`w-5 h-5 ${T?S?"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:[g?s.jsx(ut,{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"}),T&&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:T?S?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?m?.state||"?":"Offline"})]}):T?s.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[s.jsx(Vp,{className:"w-4 h-4 text-status-ok"}),s.jsx("span",{className:S?"text-status-ok":"text-bambu-gray",children:m?.state||"Unknown"})]}):s.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[s.jsx(Pf,{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(Ur,{className:"w-3 h-3"}),"Admin"]})]})]}),y&&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:y.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(ou,{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(df,{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(ii,{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(Me,{size:"sm",variant:S?"primary":"secondary",disabled:!T||C,onClick:()=>l(!0),className:"flex-1",children:[C?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xu,{className:"w-4 h-4"}),"On"]}),s.jsxs(Me,{size:"sm",variant:S?"secondary":"primary",disabled:!T||C,onClick:()=>u(!0),className:"flex-1",children:[C?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(H2,{className:"w-4 h-4"}),"Off"]})]}),t.plug_type==="mqtt"&&m?.energy&&s.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[m.energy.power!==null&&m.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(m.energy.power),"W"]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Power"})]}),m.energy.today!==null&&m.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:m.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($d,{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(z2,{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:k=>v.mutate({show_in_switchbar:k.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:k=>v.mutate({enabled:k.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:k=>v.mutate({auto_on:k.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:k=>v.mutate({auto_off:k.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(Wn,{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(G2,{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:k=>v.mutate({off_delay_minutes:parseInt(k.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:k=>v.mutate({off_temp_threshold:parseInt(k.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(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx($2,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>a(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),i&&s.jsx(Fn,{title:"Delete Smart Plug",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{N.mutate(),a(!1)},onCancel:()=>a(!1)}),o&&s.jsx(Fn,{title:"Turn On Smart Plug",message:`Are you sure you want to turn on "${t.name}"?`,confirmText:"Turn On",variant:"default",onConfirm:()=>{b.mutate("on"),l(!1)},onCancel:()=>l(!1)}),c&&s.jsx(Fn,{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:()=>{b.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function nKe({plug:t,onClose:e}){const n=an(),r=!!t,[i,a]=w.useState(t?.plug_type||"tasmota"),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.ip_address||""),[d,f]=w.useState(t?.username||""),[m,g]=w.useState(t?.password||""),[x,y]=w.useState(t?.ha_entity_id||""),[b,v]=w.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,S]=w.useState(t?.mqtt_power_path||""),[A,T]=w.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[C,E]=w.useState(t?.mqtt_energy_topic||""),[D,k]=w.useState(t?.mqtt_energy_path||""),[R,F]=w.useState((t?.mqtt_energy_multiplier??1).toString()),[O,X]=w.useState(t?.mqtt_state_topic||""),[j,q]=w.useState(t?.mqtt_state_path||""),[Y,W]=w.useState(t?.mqtt_state_on_value||""),[Z,ee]=w.useState(t?.ha_power_entity||""),[ne,z]=w.useState(t?.ha_energy_today_entity||""),[G,ae]=w.useState(t?.ha_energy_total_entity||""),[se,de]=w.useState(""),[me,ue]=w.useState(""),[Ae,pe]=w.useState(!1),Ee=w.useRef(null),[_e,oe]=w.useState(""),[ze,V]=w.useState(!1),H=w.useRef(null),[K,U]=w.useState(""),[Q,le]=w.useState(!1),ke=w.useRef(null),[Re,Ce]=w.useState(""),[B,I]=w.useState(!1),$=w.useRef(null),[te,ye]=w.useState(t?.printer_id||null),[be,Ye]=w.useState(null),[$e,Qe]=w.useState(null),[qe,Xe]=w.useState(t?.power_alert_enabled||!1),[ce,ie]=w.useState(t?.power_alert_high?.toString()||""),[Te,Ve]=w.useState(t?.power_alert_low?.toString()||""),[it,re]=w.useState(t?.schedule_enabled||!1),[De,we]=w.useState(t?.schedule_on_time||""),[Oe,Ue]=w.useState(t?.schedule_off_time||""),[je,Je]=w.useState(t?.show_in_switchbar||!1),[bt,Tt]=w.useState(!1),[Dt,sn]=w.useState({scanned:0,total:0}),[Lt,gn]=w.useState([]),rn=w.useRef(null),{data:zn}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:br}=ct({queryKey:["smart-plugs"],queryFn:fe.getSmartPlugs}),{data:er}=ct({queryKey:["settings"],queryFn:fe.getSettings}),yr=!!(er?.ha_enabled&&er?.ha_url&&er?.ha_token);w.useEffect(()=>{const xe=setTimeout(()=>{ue(se)},300);return()=>clearTimeout(xe)},[se]),w.useEffect(()=>{const xe=Le=>{Ee.current&&!Ee.current.contains(Le.target)&&pe(!1),H.current&&!H.current.contains(Le.target)&&V(!1),ke.current&&!ke.current.contains(Le.target)&&le(!1),$.current&&!$.current.contains(Le.target)&&I(!1)};return document.addEventListener("mousedown",xe),()=>document.removeEventListener("mousedown",xe)},[]);const{data:vr,isLoading:Xn,error:Bt}=ct({queryKey:["ha-entities",me],queryFn:()=>fe.getHAEntities(me||void 0),enabled:i==="homeassistant"&&yr,retry:!1,staleTime:0}),{data:In}=ct({queryKey:["ha-sensor-entities"],queryFn:fe.getHASensorEntities,enabled:i==="homeassistant"&&yr,retry:!1,staleTime:0});w.useEffect(()=>{const xe=Le=>{Le.key==="Escape"&&e()};return window.addEventListener("keydown",xe),()=>{window.removeEventListener("keydown",xe),rn.current&&clearInterval(rn.current)}},[e]);const Ti=async()=>{Tt(!0),gn([]),sn({scanned:0,total:0}),Qe(null);try{await fe.startTasmotaScan();const xe=async()=>{try{const Le=await fe.getTasmotaScanStatus();sn({scanned:Le.scanned,total:Le.total});const Ie=await fe.getDiscoveredTasmotaDevices();gn(Ie),Le.running||(Tt(!1),rn.current&&(clearInterval(rn.current),rn.current=null))}catch(Le){console.error("Polling error:",Le)}};await xe(),rn.current=setInterval(xe,500)}catch(xe){Tt(!1);const Le=xe instanceof Error?xe.message:typeof xe=="string"?xe:JSON.stringify(xe);Qe(Le||"Failed to start scan")}},_r=async()=>{try{await fe.stopTasmotaScan()}catch{}Tt(!1),rn.current&&(clearInterval(rn.current),rn.current=null)},Se=xe=>{u(xe.ip_address),l(xe.name),Ye(null)},We=ht({mutationFn:()=>fe.testSmartPlugConnection(c,d||null,m||null),onSuccess:xe=>{Ye(xe),Qe(null),!o&&xe.device_name&&l(xe.device_name)},onError:xe=>{Ye(null),Qe(xe.message)}}),et=ht({mutationFn:xe=>fe.createSmartPlug(xe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:xe=>{Qe(xe.message)}}),ot=ht({mutationFn:xe=>fe.updateSmartPlug(t.id,xe),onSuccess:()=>{n.invalidateQueries({queryKey:["smart-plugs"]}),e()},onError:xe=>{Qe(xe.message)}}),at=zn?.filter(xe=>!br?.some(Ie=>Ie.printer_id===xe.id&&Ie.id!==t?.id)),At=xe=>{if(xe.preventDefault(),Qe(null),!o.trim()){Qe("Name is required");return}if(i==="tasmota"&&!c.trim()){Qe("IP address is required for Tasmota plugs");return}if(i==="homeassistant"&&!x){Qe("Entity is required for Home Assistant plugs");return}if(i==="mqtt"){const Ie=b.trim(),Ne=C.trim(),ft=O.trim();if(!Ie&&!Ne&&!ft){Qe("At least one MQTT topic must be configured for power, energy, or state monitoring");return}}const Le={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"&&Z||null,ha_energy_today_entity:i==="homeassistant"&&ne||null,ha_energy_total_entity:i==="homeassistant"&&G||null,mqtt_power_topic:i==="mqtt"&&b.trim()||null,mqtt_power_path:i==="mqtt"&&N.trim()||null,mqtt_power_multiplier:i==="mqtt"&&parseFloat(A)||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"&&O.trim()||null,mqtt_state_path:i==="mqtt"&&j.trim()||null,mqtt_state_on_value:i==="mqtt"&&Y.trim()||null,username:i==="tasmota"&&d.trim()||null,password:i==="tasmota"&&m.trim()||null,printer_id:te,power_alert_enabled:qe,power_alert_high:ce?parseFloat(ce):null,power_alert_low:Te?parseFloat(Te):null,schedule_enabled:it,schedule_on_time:De||null,schedule_off_time:Oe||null,show_in_switchbar:je};r?ot.mutate(Le):et.mutate(Le)},he=et.isPending||ot.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:xe=>xe.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(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:At,className:"p-6 space-y-4 overflow-y-auto",children:[$e&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:$e}),!r&&s.jsxs("div",{className:"flex gap-2 mb-2",children:[s.jsxs("button",{type:"button",onClick:()=>{a("tasmota"),Ye(null),Qe(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(Gs,{className:"w-4 h-4"}),"Tasmota"]}),s.jsxs("button",{type:"button",onClick:()=>{a("homeassistant"),Ye(null),Qe(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(U2,{className:"w-4 h-4"}),"HA"]}),s.jsxs("button",{type:"button",onClick:()=>{a("mqtt"),Ye(null),Qe(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(fD,{className:"w-4 h-4"}),"MQTT"]})]}),!r&&i==="tasmota"&&s.jsxs("div",{className:"space-y-3",children:[bt?s.jsxs(Me,{type:"button",variant:"secondary",onClick:_r,className:"w-full",children:[s.jsx(Ut,{className:"w-4 h-4"}),"Stop Scanning"]}):s.jsxs(Me,{type:"button",variant:"primary",onClick:Ti,className:"w-full",children:[s.jsx(_a,{className:"w-4 h-4"}),"Discover Tasmota Devices"]}),bt&&Dt.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:[Dt.scanned," / ",Dt.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:`${Dt.scanned/Dt.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(xe=>s.jsxs("button",{type:"button",onClick:()=>Se(xe),className:"w-full flex items-center justify-between p-2 bg-bambu-dark hover:bg-bambu-dark-tertiary rounded-lg transition-colors text-left border border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Gs,{className:"w-4 h-4 text-bambu-green"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-white",children:xe.name}),s.jsx("p",{className:"text-xs text-bambu-gray",children:xe.ip_address})]})]}),xe.state&&s.jsxs("span",{className:`flex items-center gap-1 text-xs ${xe.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[s.jsx(xu,{className:"w-3 h-3"}),xe.state]})]},xe.ip_address))})]}),!bt&&Lt.length===0&&Dt.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:[!yr&&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..."})})]})]}),yr&&s.jsxs(s.Fragment,{children:[Xn&&s.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[s.jsx(ut,{className:"w-5 h-5 animate-spin mr-2"}),"Loading entities..."]}),Bt&&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: ",Bt.message]}),(()=>{const xe=br?.filter(Ne=>Ne.ha_entity_id&&Ne.id!==t?.id).map(Ne=>Ne.ha_entity_id)||[],Le=(vr||[]).filter(Ne=>!xe.includes(Ne.entity_id)),Ie=vr?.find(Ne=>Ne.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:"Select Entity *"}),s.jsxs("div",{className:"relative",children:[s.jsx(_a,{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:Ae?se:Ie?`${Ie.friendly_name} (${Ie.entity_id})`:"",onChange:Ne=>{de(Ne.target.value),Ae||pe(!0)},onFocus:()=>{pe(!0),de("")},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&&!Ae&&s.jsx("button",{type:"button",onClick:()=>{y(""),de("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),Xn&&s.jsx(ut,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),Ae&&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:[Xn&&s.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[s.jsx(ut,{className:"w-4 h-4 animate-spin"}),"Loading..."]}),!Xn&&Le.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:me?`No entities found matching "${me}"`:"No entities available"}),!Xn&&Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{y(Ne.entity_id),pe(!1),de(""),o||l(Ne.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Ne.entity_id===x?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[s.jsx("span",{children:Ne.entity_id}),s.jsx("span",{className:Ne.state==="on"?"text-bambu-green":"",children:Ne.state})]})]},Ne.entity_id))]}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:me?`Searching all entities (${Le.length} found)`:`Showing switch, light, input_boolean (${Le.length} available)`})]})})(),x&&In&&In.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 xe=In.filter(Ne=>Ne.unit_of_measurement==="W"||Ne.unit_of_measurement==="kW"||Ne.unit_of_measurement==="mW"),Le=_e?xe.filter(Ne=>Ne.entity_id.toLowerCase().includes(_e.toLowerCase())||Ne.friendly_name.toLowerCase().includes(_e.toLowerCase())):xe,Ie=In.find(Ne=>Ne.entity_id===Z);return s.jsxs("div",{ref:H,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(_a,{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:ze?_e:Ie?`${Ie.friendly_name} (${Ie.state} ${Ie.unit_of_measurement})`:"",onChange:Ne=>{oe(Ne.target.value),ze||V(!0)},onFocus:()=>{V(!0),oe("")},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"}),Z&&!ze&&s.jsx("button",{type:"button",onClick:()=>{ee(""),oe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),ze&&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:()=>{ee(""),V(!1),oe("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{ee(Ne.entity_id),V(!1),oe("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ne.entity_id===Z?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ne.entity_id," • ",Ne.state," ",Ne.unit_of_measurement]})]},Ne.entity_id)),Le.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=In.filter(Ne=>Ne.unit_of_measurement==="kWh"||Ne.unit_of_measurement==="Wh"||Ne.unit_of_measurement==="MWh"),Le=K?xe.filter(Ne=>Ne.entity_id.toLowerCase().includes(K.toLowerCase())||Ne.friendly_name.toLowerCase().includes(K.toLowerCase())):xe,Ie=In.find(Ne=>Ne.entity_id===ne);return s.jsxs("div",{ref:ke,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(_a,{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:Q?K:Ie?`${Ie.friendly_name} (${Ie.state} ${Ie.unit_of_measurement})`:"",onChange:Ne=>{U(Ne.target.value),Q||le(!0)},onFocus:()=>{le(!0),U("")},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"}),ne&&!Q&&s.jsx("button",{type:"button",onClick:()=>{z(""),U("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Q&&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(""),le(!1),U("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{z(Ne.entity_id),le(!1),U("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ne.entity_id===ne?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ne.entity_id," • ",Ne.state," ",Ne.unit_of_measurement]})]},Ne.entity_id)),Le.length===0&&s.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:"No matching sensors"})]})]})})(),(()=>{const xe=In.filter(Ne=>Ne.unit_of_measurement==="kWh"||Ne.unit_of_measurement==="Wh"||Ne.unit_of_measurement==="MWh"),Le=Re?xe.filter(Ne=>Ne.entity_id.toLowerCase().includes(Re.toLowerCase())||Ne.friendly_name.toLowerCase().includes(Re.toLowerCase())):xe,Ie=In.find(Ne=>Ne.entity_id===G);return s.jsxs("div",{ref:$,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(_a,{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:B?Re:Ie?`${Ie.friendly_name} (${Ie.state} ${Ie.unit_of_measurement})`:"",onChange:Ne=>{Ce(Ne.target.value),B||I(!0)},onFocus:()=>{I(!0),Ce("")},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"}),G&&!B&&s.jsx("button",{type:"button",onClick:()=>{ae(""),Ce("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:s.jsx(Ut,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),B&&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:()=>{ae(""),I(!1),Ce("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:"None"}),Le.map(Ne=>s.jsxs("button",{type:"button",onClick:()=>{ae(Ne.entity_id),I(!1),Ce("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ne.entity_id===G?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[s.jsx("div",{className:"font-medium",children:Ne.friendly_name}),s.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ne.entity_id," • ",Ne.state," ",Ne.unit_of_measurement]})]},Ne.entity_id)),Le.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:[!er?.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)."]}),er?.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:b,onChange:xe=>v(xe.target.value),placeholder:"zigbee2mqtt/shelly-working-room",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:N,onChange:xe=>S(xe.target.value),placeholder:"power_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Multiplier"}),s.jsx("input",{type:"text",value:A,onChange:xe=>T(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),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:xe=>E(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:xe=>k(xe.target.value),placeholder:"energy_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:xe=>F(xe.target.value),placeholder:"1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),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:O,onChange:xe=>X(xe.target.value),placeholder:"Same as power topic, or different",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:xe=>q(xe.target.value),placeholder:"state_l1",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]}),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:Y,onChange:xe=>W(xe.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:xe=>{u(xe.target.value),Ye(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(Me,{type:"button",variant:"secondary",onClick:()=>We.mutate(),disabled:!c.trim()||We.isPending,children:[We.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Vp,{className:"w-4 h-4"}),"Test"]})]})]}),i==="tasmota"&&be&&s.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${be.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:be.success?s.jsxs(s.Fragment,{children:[s.jsx(Dn,{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:[be.device_name&&`Device: ${be.device_name} - `,"State: ",be.state]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Pf,{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:xe=>l(xe.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:xe=>f(xe.target.value),placeholder:"admin",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Password"}),s.jsx("input",{type:"password",value:m,onChange:xe=>g(xe.target.value),placeholder:"********",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),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:te??"",onChange:xe=>ye(xe.target.value?Number(xe.target.value):null),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[s.jsx("option",{value:"",children:"No printer (manual control only)"}),at?.map(xe=>s.jsx("option",{value:xe.id,children:xe.name},xe.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(df,{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:qe,onChange:xe=>Xe(xe.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"})]})]}),qe&&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:ce,onChange:xe=>ie(xe.target.value),placeholder:"e.g. 200",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),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:Te,onChange:xe=>Ve(xe.target.value),placeholder:"e.g. 10",min:"0",max:"5000",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),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(Wn,{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:it,onChange:xe=>re(xe.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"})]})]}),it&&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:De,onChange:xe=>we(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),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:Oe,onChange:xe=>Ue(xe.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]})]}),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(z2,{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:je,onChange:xe=>Je(xe.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(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:he,className:"flex-1",children:[he?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function $n({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 rKe={callmebot:"CallMeBot/WhatsApp",ntfy:"ntfy",pushover:"Pushover",telegram:"Telegram",email:"Email",discord:"Discord",webhook:"Webhook"};function iKe({provider:t,onEdit:e}){const n=an(),[r,i]=w.useState(!1),[a,o]=w.useState(!1),[l,c]=w.useState(null),{data:u}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),d=u?.find(y=>y.id===t.printer_id),f=ht({mutationFn:y=>fe.updateNotificationProvider(t.id,y),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),m=ht({mutationFn:()=>fe.deleteNotificationProvider(t.id),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]})}}),g=ht({mutationFn:()=>fe.testNotificationProvider(t.id),onSuccess:y=>{c(y),n.invalidateQueries({queryKey:["notification-providers"]})},onError:y=>{c({success:!1,message:y.message})}}),x=y=>y||"";return s.jsxs(s.Fragment,{children:[s.jsx(wt,{className:"relative",children:s.jsxs(Nt,{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(df,{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:rKe[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: ",og(t.last_success)]}),t.last_error&&t.last_error_at&&(!t.last_success||(vi(t.last_error_at)?.getTime()||0)>(vi(t.last_success)?.getTime()||0))&&s.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:"Error"}),s.jsx($n,{checked:t.enabled,onChange:y=>f.mutate({enabled:y})})]})]}),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(yw,{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(ii,{className:"w-3 h-3"}),"Digest ",t.daily_digest_time]})]}),s.jsx("div",{className:"mb-3",children:s.jsxs(Me,{size:"sm",variant:"secondary",disabled:g.isPending,onClick:()=>{c(null),g.mutate()},className:"w-full",children:[g.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(mD,{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(Dn,{className:"w-4 h-4"}):s.jsx(ea,{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($d,{className:"w-4 h-4"}),"Event Settings"]}),a?s.jsx(su,{className:"w-4 h-4"}):s.jsx(Pi,{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($n,{checked:t.enabled,onChange:y=>f.mutate({enabled:y})})]}),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($n,{checked:t.on_print_start,onChange:y=>f.mutate({on_print_start:y})})]}),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($n,{checked:t.on_plate_not_empty??!0,onChange:y=>f.mutate({on_plate_not_empty:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Completed"}),s.jsx($n,{checked:t.on_print_complete,onChange:y=>f.mutate({on_print_complete:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Failed"}),s.jsx($n,{checked:t.on_print_failed,onChange:y=>f.mutate({on_print_failed:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Print Stopped"}),s.jsx($n,{checked:t.on_print_stopped,onChange:y=>f.mutate({on_print_stopped:y})})]}),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($n,{checked:t.on_print_progress,onChange:y=>f.mutate({on_print_progress:y})})]})]}),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($n,{checked:t.on_printer_offline,onChange:y=>f.mutate({on_printer_offline:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Printer Error"}),s.jsx($n,{checked:t.on_printer_error,onChange:y=>f.mutate({on_printer_error:y})})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("p",{className:"text-sm text-white",children:"Low Filament"}),s.jsx($n,{checked:t.on_filament_low,onChange:y=>f.mutate({on_filament_low:y})})]}),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($n,{checked:t.on_maintenance_due??!1,onChange:y=>f.mutate({on_maintenance_due:y})})]})]}),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($n,{checked:t.on_ams_humidity_high??!1,onChange:y=>f.mutate({on_ams_humidity_high:y})})]}),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($n,{checked:t.on_ams_temperature_high??!1,onChange:y=>f.mutate({on_ams_temperature_high:y})})]})]}),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($n,{checked:t.on_ams_ht_humidity_high??!1,onChange:y=>f.mutate({on_ams_ht_humidity_high:y})})]}),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($n,{checked:t.on_ams_ht_temperature_high??!1,onChange:y=>f.mutate({on_ams_ht_temperature_high:y})})]})]}),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(yw,{className:"w-4 h-4 text-purple-400"}),s.jsx("p",{className:"text-sm text-white",children:"Quiet Hours"})]}),s.jsx($n,{checked:t.quiet_hours_enabled,onChange:y=>f.mutate({quiet_hours_enabled:y})})]}),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(Wn,{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(ii,{className:"w-4 h-4 text-emerald-400"}),s.jsx("p",{className:"text-sm text-white",children:"Daily Digest"})]}),s.jsx($n,{checked:t.daily_digest_enabled,onChange:y=>f.mutate({daily_digest_enabled:y})})]}),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(Wn,{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(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[s.jsx($2,{className:"w-4 h-4"}),"Edit"]}),s.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>i(!0),className:"text-red-400 hover:text-red-300",children:s.jsx(ln,{className:"w-4 h-4"})})]})]})]})}),r&&s.jsx(Fn,{title:"Delete Notification Provider",message:`Are you sure you want to delete "${t.name}"? This cannot be undone.`,confirmText:"Delete",variant:"danger",onConfirm:()=>{m.mutate(),i(!1)},onCancel:()=>i(!1)})]})}const ZG=[{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 aKe({provider:t,onClose:e}){const n=an(),r=!!t,[i,a]=w.useState(t?.name||""),[o,l]=w.useState(t?.provider_type||"email"),[c,u]=w.useState(t?.printer_id||null),[d,f]=w.useState(t?.quiet_hours_enabled||!1),[m,g]=w.useState(t?.quiet_hours_start||"22:00"),[x,y]=w.useState(t?.quiet_hours_end||"07:00"),[b,v]=w.useState(t?.daily_digest_enabled||!1),[N,S]=w.useState(t?.daily_digest_time||"08:00"),[A,T]=w.useState(t?.on_print_start??!1),[C,E]=w.useState(t?.on_print_complete??!0),[D,k]=w.useState(t?.on_print_failed??!0),[R,F]=w.useState(t?.on_print_stopped??!0),[O,X]=w.useState(t?.on_print_progress??!1),[j,q]=w.useState(t?.on_printer_offline??!1),[Y,W]=w.useState(t?.on_printer_error??!1),[Z,ee]=w.useState(t?.on_filament_low??!1),[ne,z]=w.useState(t?.on_maintenance_due??!1),[G,ae]=w.useState(t?.config?Object.fromEntries(Object.entries(t.config).map(([U,Q])=>[U,String(Q)])):{}),[se,de]=w.useState(null),[me,ue]=w.useState(null),{data:Ae}=ct({queryKey:["printers"],queryFn:fe.getPrinters});w.useEffect(()=>{const U=Q=>{Q.key==="Escape"&&e()};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[e]);const pe=ht({mutationFn:()=>fe.testNotificationConfig({provider_type:o,config:G}),onSuccess:U=>{de(U),ue(null)},onError:U=>{de({success:!1,message:U.message})}}),Ee=ht({mutationFn:U=>fe.createNotificationProvider(U),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:U=>{ue(U.message)}}),_e=ht({mutationFn:U=>fe.updateNotificationProvider(t.id,U),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:U=>{ue(U.message)}}),oe=U=>{if(U.preventDefault(),ue(null),!i.trim()){ue("Name is required");return}const Q=H(o);for(const ke of Q)if(!G[ke.key]?.trim()){ue(`${ke.label} is required`);return}const le={name:i.trim(),provider_type:o,config:G,printer_id:c,quiet_hours_enabled:d,quiet_hours_start:d?m:null,quiet_hours_end:d?x:null,daily_digest_enabled:b,daily_digest_time:b?N:null,on_print_start:A,on_print_complete:C,on_print_failed:D,on_print_stopped:R,on_print_progress:O,on_printer_offline:j,on_printer_error:Y,on_filament_low:Z,on_maintenance_due:ne};r?_e.mutate(le):Ee.mutate(le)},ze=Ee.isPending||_e.isPending,V=U=>{switch(U){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:Q=>Q.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:Q=>Q.payload_format!=="slack"}];default:return[]}},H=U=>V(U).filter(Q=>Q.required),K=V(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: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.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(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:oe,className:"p-6 space-y-4",children:[me&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:me}),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:U=>a(U.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:U=>{l(U.target.value),ae({}),de(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:ZG.map(U=>s.jsx("option",{value:U.value,children:U.label},U.value))}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:ZG.find(U=>U.value===o)?.description})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Configuration"}),K.filter(U=>!("showIf"in U)||U.showIf?.(G)!==!1).map(U=>s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[U.label," ",U.required&&"*"]}),U.type==="select"&&"options"in U&&U.options?s.jsx("select",{value:G[U.key]||U.options[0]?.value||"",onChange:Q=>{ae({...G,[U.key]:Q.target.value}),de(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:U.options.map(Q=>s.jsx("option",{value:Q.value,children:Q.label},Q.value))}):s.jsx("input",{type:U.type,value:G[U.key]||"",onChange:Q=>{ae({...G,[U.key]:Q.target.value}),de(null)},placeholder:U.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"})]},U.key))]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>{de(null),pe.mutate()},disabled:pe.isPending||!G[H(o)[0]?.key],className:"flex-1",children:[pe.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(mD,{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(Dn,{className:"w-5 h-5"}),s.jsx("span",{children:se.message})]}):s.jsxs(s.Fragment,{children:[s.jsx(ea,{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:U=>u(U.target.value?Number(U.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"}),Ae?.map(U=>s.jsx("option",{value:U.id,children:U.name},U.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($n,{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:m,onChange:U=>g(U.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:U=>y(U.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($n,{checked:b,onChange:v})]}),b&&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:N,onChange:U=>S(U.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($n,{checked:A,onChange:T})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Complete"}),s.jsx($n,{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($n,{checked:D,onChange:k})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Stopped"}),s.jsx($n,{checked:R,onChange:F})]}),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($n,{checked:O,onChange:X})]})]})]}),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($n,{checked:j,onChange:q})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Error"}),s.jsx($n,{checked:Y,onChange:W})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Low Filament"}),s.jsx($n,{checked:Z,onChange:ee})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-sm text-white",children:"Maintenance"}),s.jsx($n,{checked:ne,onChange:z})]})]})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:ze,className:"flex-1",children:[ze?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xs,{className:"w-4 h-4"}),r?"Save":"Add"]})]})]})]})})}function sKe({template:t,onClose:e}){const n=an(),r=w.useRef(null),[i,a]=w.useState(t.title_template),[o,l]=w.useState(t.body_template),[c,u]=w.useState(null),[d,f]=w.useState(!0),{data:m}=ct({queryKey:["template-variables"],queryFn:fe.getTemplateVariables}),g=m?.find(T=>T.event_type===t.event_type),{data:x,isLoading:y}=ct({queryKey:["template-preview",t.event_type,i,o],queryFn:()=>fe.previewTemplate({event_type:t.event_type,title_template:i,body_template:o}),enabled:d&&i.length>0&&o.length>0});w.useEffect(()=>{const T=C=>{C.key==="Escape"&&e()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[e]);const b=ht({mutationFn:T=>fe.updateNotificationTemplate(t.id,T),onSuccess:()=>{n.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:T=>{u(T.message)}}),v=ht({mutationFn:()=>fe.resetNotificationTemplate(t.id),onSuccess:T=>{a(T.title_template),l(T.body_template),n.invalidateQueries({queryKey:["notification-templates"]})},onError:T=>{u(T.message)}}),N=T=>{if(T.preventDefault(),u(null),!i.trim()){u("Title is required");return}if(!o.trim()){u("Body is required");return}b.mutate({title_template:i,body_template:o})},S=T=>{const C=r.current;if(!C)return;const E=C.selectionStart,D=C.selectionEnd,k=o,R=k.substring(0,E),F=k.substring(D),O=R+`{${T}}`+F;l(O),setTimeout(()=>{C.focus();const X=E+T.length+2;C.setSelectionRange(X,X)},0)},A=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(Ut,{className:"w-5 h-5 text-bambu-gray"})})]}),s.jsxs("form",{onSubmit:N,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:T=>a(T.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:T=>l(T.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..."})]}),g&&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:g.variables.map(T=>s.jsxs("button",{type:"button",onClick:()=>S(T),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(Jn,{className:"w-3 h-3"}),T]},T))}),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(ou,{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:y?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[s.jsx(ut,{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(Me,{type:"button",variant:"ghost",onClick:()=>v.mutate(),disabled:v.isPending,className:"text-orange-400 hover:text-orange-300",children:[v.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(Zf,{className:"w-4 h-4 mr-2"}),"Reset to Default"]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:"Cancel"}),s.jsxs(Me,{onClick:N,disabled:b.isPending||!A,children:[b.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin mr-2"}):s.jsx(xs,{className:"w-4 h-4 mr-2"}),"Save"]})]})]})]})})}const oKe={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"},lKe={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 cKe({onClose:t}){const e=an(),{showToast:n}=Hn(),[r,i]=w.useState(7),[a,o]=w.useState(null),[l,c]=w.useState(!1),{data:u}=ct({queryKey:["settings"],queryFn:fe.getSettings}),d=u?.time_format||"system",{data:f,isLoading:m,refetch:g,isRefetching:x}=ct({queryKey:["notification-logs",r,l],queryFn:()=>fe.getNotificationLogs({days:r,limit:100,success:l?!1:void 0})}),{data:y}=ct({queryKey:["notification-log-stats",r],queryFn:()=>fe.getNotificationLogStats(r)}),b=ht({mutationFn:()=>fe.clearNotificationLogs(30),onSuccess:N=>{n(N.message,"success"),e.invalidateQueries({queryKey:["notification-logs"]}),e.invalidateQueries({queryKey:["notification-log-stats"]})},onError:N=>{n(`Failed to clear logs: ${N.message}`,"error")}}),v=N=>{const S=vi(N);if(!S)return"";const T=new Date().getTime()-S.getTime();return T<6e4?"Just now":T<36e5?`${Math.floor(T/6e4)}m ago`:T<864e5?`${Math.floor(T/36e5)}h ago`:S.toLocaleDateString()+" "+Cfe(S,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(f0,{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:"×"})]}),y&&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:y.total})," notifications"]}),s.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[s.jsx(Dn,{className:"w-4 h-4"}),y.success_count," sent"]}),y.failure_count>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(ea,{className:"w-4 h-4"}),y.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:N=>i(Number(N.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:N=>c(N.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(Me,{size:"sm",variant:"secondary",onClick:()=>g(),disabled:x,children:[x?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Refresh"]}),s.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>b.mutate(),disabled:b.isPending,className:"text-red-400 hover:text-red-300",children:[b.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"}),"Clear Old"]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:m?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):f&&f.length>0?s.jsx("div",{className:"space-y-2",children:f.map(N=>s.jsx(uKe,{log:N,isExpanded:a===N.id,onToggle:()=>o(a===N.id?null:N.id),formatDate:v,formatFullDate:S=>lg(S,d)},N.id))}):s.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[s.jsx(f0,{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 uKe({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(Dn,{className:"w-4 h-4 text-bambu-green shrink-0"}):s.jsx(ea,{className:"w-4 h-4 text-red-400 shrink-0"}),s.jsx("span",{className:`text-xs font-medium ${lKe[t.event_type]||"text-bambu-gray"}`,children:oKe[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(su,{className:"w-4 h-4 text-bambu-gray shrink-0"}):s.jsx(Pi,{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 dKe(){const t=await fetch("/api/v1/settings/spoolman");if(!t.ok)throw new Error("Failed to load Spoolman settings");return t.json()}async function hKe(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 fKe(){const t=an(),[e,n]=w.useState(!1),[r,i]=w.useState(""),[a,o]=w.useState("auto"),[l,c]=w.useState(!1),[u,d]=w.useState("all"),[f,m]=w.useState(!1),[g,x]=w.useState(!1),{data:y,isLoading:b}=ct({queryKey:["spoolman-settings"],queryFn:dKe}),{data:v,isLoading:N,refetch:S}=ct({queryKey:["spoolman-status"],queryFn:fe.getSpoolmanStatus,refetchInterval:3e4}),{data:A}=ct({queryKey:["printers"],queryFn:fe.getPrinters});w.useEffect(()=>{y&&(n(y.spoolman_enabled==="true"),i(y.spoolman_url||""),o(y.spoolman_sync_mode||"auto"),m(!0))},[y]),w.useEffect(()=>{if(!f||!y)return;if(y.spoolman_enabled==="true"!==e||(y.spoolman_url||"")!==r||(y.spoolman_sync_mode||"auto")!==a){const q=setTimeout(()=>{T.mutate()},500);return()=>clearTimeout(q)}},[e,r,a,f]);const T=ht({mutationFn:()=>hKe({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=ht({mutationFn:fe.connectSpoolman,onSuccess:()=>{S()}}),E=ht({mutationFn:fe.disconnectSpoolman,onSuccess:()=>{S()}}),D=ht({mutationFn:fe.syncAllPrintersAms,onSuccess:j=>{j.success}}),k=ht({mutationFn:j=>fe.syncPrinterAms(j),onSuccess:j=>{j.success}}),R=()=>{u==="all"?D.mutate():k.mutate(u)},F=D.isPending||k.isPending,O=u==="all"?D.data:k.data,X=u==="all"?D.isSuccess:k.isSuccess;return b?s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Qc,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]})}),s.jsx(Nt,{children:s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Qc,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Spoolman Integration"})]}),T.isPending&&s.jsx(ut,{className:"w-4 h-4 text-bambu-green animate-spin"}),l&&s.jsx(Ya,{className:"w-4 h-4 text-bambu-green"})]})}),s.jsxs(Nt,{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(zl,{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:"}),N?s.jsx(ut,{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(Ya,{className:"w-4 h-4"}),"Connected"]}):s.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[s.jsx(Ut,{className:"w-4 h-4"}),"Disconnected"]})]}),s.jsx("div",{className:"flex gap-2",children:v?.connected?s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>E.mutate(),disabled:E.isPending,children:[E.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(pde,{className:"w-4 h-4"}),"Disconnect"]}):s.jsxs(Me,{size:"sm",onClick:()=>C.mutate(),disabled:C.isPending||!r,children:[C.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Ll,{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"}),A?.map(j=>s.jsx("option",{value:j.id,children:j.name},j.id))]}),s.jsx(Pi,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:R,disabled:F,children:[F?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Sync"]})]})]}),X&&O&&s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx("div",{className:`p-2 rounded text-sm ${O.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:O.success?`Synced ${O.synced_count} spool${O.synced_count!==1?"s":""} successfully`:`Synced ${O.synced_count} spool${O.synced_count!==1?"s":""} with ${O.errors.length} error${O.errors.length!==1?"s":""}`}),O.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(Nn,{className:"w-3.5 h-3.5"}),s.jsxs("span",{className:"font-medium",children:[O.skipped_count," spool",O.skipped_count!==1?"s":""," skipped"]})]}),O.skipped_count>5&&s.jsx("button",{onClick:()=>x(!g),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:g?"Show less":"Show all"})]}),s.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(g?O.skipped:O.skipped.slice(0,5)).map((j,q)=>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]})]},q)),!g&&O.skipped_count>5&&s.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",O.skipped_count-5," more"]})]})]}),O.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:O.errors.map((j,q)=>s.jsx("li",{children:j},q))})]})]})]})]})]})}function mKe({link:t,onClose:e}){const n=an(),{mode:r}=ih(),i=!!t,a=w.useRef(null),[o,l]=w.useState(t?.name||""),[c,u]=w.useState(t?.url||""),[d,f]=w.useState(t?.icon||"link"),[m,g]=w.useState(!!t?.custom_icon),[x,y]=w.useState(t?.custom_icon?fe.getExternalLinkIconUrl(t.id):null),[b,v]=w.useState(null),[N,S]=w.useState(null);w.useEffect(()=>{const F=O=>{O.key==="Escape"&&e()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[e]);const A=ht({mutationFn:async F=>{const O=await fe.createExternalLink(F);return b?await fe.uploadExternalLinkIcon(O.id,b):O},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:F=>{S(F.message)}}),T=ht({mutationFn:async F=>{let O=await fe.updateExternalLink(t.id,F);return b?O=await fe.uploadExternalLinkIcon(t.id,b):!m&&t?.custom_icon&&(O=await fe.deleteExternalLinkIcon(t.id)),O},onSuccess:()=>{n.invalidateQueries({queryKey:["external-links"]}),e()},onError:F=>{S(F.message)}}),C=F=>{const O=F.target.files?.[0];if(O){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(O.type)){S("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(O.size>1024*1024){S("Image file must be less than 1MB");return}v(O),g(!0);const j=new FileReader;j.onload=q=>{y(q.target?.result)},j.readAsDataURL(O)}},E=()=>{v(null),y(null),g(!1),a.current&&(a.current.value="")},D=F=>{if(F.preventDefault(),S(null),!o.trim()){S("Name is required");return}if(!c.trim()){S("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){S("URL must start with http:// or https://");return}const O={name:o.trim(),url:c.trim(),icon:d};i?T.mutate(O):A.mutate(O)},k=A.isPending||T.isPending,R=q2(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:F=>F.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:m&&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(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:D,className:"p-6 space-y-4",children:[N&&s.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:N}),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:F=>l(F.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:F=>u(F.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}),m&&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(ln,{className:"w-4 h-4"})})]}):s.jsxs(Me,{type:"button",variant:"secondary",size:"sm",onClick:()=>a.current?.click(),children:[s.jsx(di,{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."})]}),!m&&s.jsxs("div",{children:[s.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),s.jsx(Sfe,{value:d,onChange:f})]})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:k,className:"flex-1",children:[k?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function pKe(){const t=an(),[e,n]=w.useState(!1),[r,i]=w.useState(null),[a,o]=w.useState(null),[l,c]=w.useState(null),{data:u,isLoading:d}=ct({queryKey:["external-links"],queryFn:fe.getExternalLinks}),f=ht({mutationFn:N=>fe.deleteExternalLink(N),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),m=ht({mutationFn:N=>fe.reorderExternalLinks(N),onSuccess:()=>{t.invalidateQueries({queryKey:["external-links"]})}}),g=(N,S)=>{c(S),N.dataTransfer.effectAllowed="move"},x=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},y=(N,S)=>{if(N.preventDefault(),l===null||l===S||!u)return;const A=u.map(D=>D.id),T=A.indexOf(l),C=A.indexOf(S);if(T===-1||C===-1)return;const E=[...A];E.splice(T,1),E.splice(C,0,l),m.mutate(E),c(null)},b=N=>{o(N)},v=()=>{a&&(f.mutate(a.id),o(null))};return s.jsxs(s.Fragment,{children:[s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ll,{className:"w-5 h-5 text-bambu-green"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),s.jsxs(Me,{size:"sm",onClick:()=>n(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Link"]})]})}),s.jsxs(Nt,{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(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?s.jsx("div",{className:"space-y-2",children:u.map(N=>{const S=q2(N.icon);return s.jsxs("div",{draggable:!0,onDragStart:A=>g(A,N.id),onDragOver:x,onDrop:A=>y(A,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${l===N.id?"opacity-50":""}`,children:[s.jsx(ag,{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(S,{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:N.name}),s.jsx(Ur,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),s.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),s.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[s.jsx("button",{onClick:()=>i(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:"Edit",children:s.jsx(ia,{className:"w-4 h-4"})}),s.jsx("button",{onClick:()=>b(N),disabled:f.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:"Delete",children:s.jsx(ln,{className:"w-4 h-4"})})]})]},N.id)})}):s.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[s.jsx(Ll,{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(mKe,{link:r,onClose:()=>{n(!1),i(null)}}),a&&s.jsx(Fn,{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 gKe(){const t=an(),{showToast:e}=Hn(),[n,r]=w.useState(!1),[i,a]=w.useState(""),[o,l]=w.useState("immediate"),[c,u]=w.useState("3DPrinter-X1-Carbon"),[d,f]=w.useState(!1),[m,g]=w.useState(null),{data:x,isLoading:y}=ct({queryKey:["virtual-printer-settings"],queryFn:z1.getSettings,refetchInterval:1e4}),{data:b}=ct({queryKey:["virtual-printer-models"],queryFn:z1.getModels});w.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=ht({mutationFn:D=>z1.updateSettings(D),onSuccess:()=>{t.invalidateQueries({queryKey:["virtual-printer-settings"]}),e("Virtual printer settings updated"),g(null)},onError:D=>{if(e(D.message||"Failed to update settings","error"),x){r(x.enabled);const k=x.mode==="queue"?"review":x.mode;l(k==="print_queue"||k==="review"?k:"immediate"),u(x.model)}g(null)}}),N=()=>{const D=!n;if(D&&!i&&!x?.access_code_set){e("Please set an access code first","error");return}r(D),g("toggle"),v.mutate({enabled:D,access_code:i||void 0,mode:o})},S=()=>{if(!i){e("Access code cannot be empty","error");return}if(i.length!==8){e("Access code must be exactly 8 characters","error");return}g("accessCode"),v.mutate({access_code:i}),a("")},A=D=>{l(D),g("mode"),v.mutate({mode:D})},T=D=>{u(D),g("model"),v.mutate({model:D})};if(y)return s.jsx(wt,{children:s.jsx(Nt,{className:"py-8 flex justify-center",children:s.jsx(ut,{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(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(qr,{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(Nt,{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:N,disabled:m==="toggle",className:`relative w-12 h-6 rounded-full transition-colors ${n?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${m==="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=>T(D.target.value),disabled:m==="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:b?.models&&Object.entries(b.models).sort(([,D],[,k])=>D.localeCompare(k)).map(([D,k])=>s.jsx("option",{value:D,children:k},D))}),s.jsx(Pi,{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(zl,{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(Ya,{className:"w-4 h-4"}),"Access code is set"]}):s.jsxs("span",{className:"flex items-center gap-1 text-yellow-400",children:[s.jsx(Nn,{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(D2,{className:"w-4 h-4"}):s.jsx(ou,{className:"w-4 h-4"})})]}),s.jsx(Me,{onClick:S,disabled:!i||m==="accessCode",variant:"primary",children:m==="accessCode"?s.jsx(ut,{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:()=>A("immediate"),disabled:m==="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:()=>A("review"),disabled:m==="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:()=>A("print_queue"),disabled:m==="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(wt,{className:"border-l-4 border-l-yellow-500",children:s.jsx(Nt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Nn,{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(Ur,{className:"w-4 h-4"}),"Read the setup guide before enabling"]})]})]})})}),s.jsx(wt,{children:s.jsx(Nt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(zl,{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(wt,{children:[s.jsx(Qn,{children:s.jsx("h3",{className:"text-md font-semibold text-white",children:"Status Details"})}),s.jsx(Nt,{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})]})]})})]})]})]})}const L1=[{id:"settings",labelKey:"backup.categories.settings",defaultLabel:"App Settings",icon:s.jsx(V2,{className:"w-4 h-4"}),default:!0,description:"Language, theme, update preferences"},{id:"notifications",labelKey:"backup.categories.notifications",defaultLabel:"Notification Providers",icon:s.jsx(df,{className:"w-4 h-4"}),default:!0,description:"ntfy, Pushover, Discord, etc."},{id:"templates",labelKey:"backup.categories.templates",defaultLabel:"Notification Templates",icon:s.jsx(Ga,{className:"w-4 h-4"}),default:!0,description:"Custom message templates"},{id:"smart_plugs",labelKey:"backup.categories.smartPlugs",defaultLabel:"Smart Plugs",icon:s.jsx(Gs,{className:"w-4 h-4"}),default:!0,description:"Tasmota plug configurations"},{id:"external_links",labelKey:"backup.categories.externalLinks",defaultLabel:"External Links",icon:s.jsx(zg,{className:"w-4 h-4"}),default:!0,description:"Sidebar links to external services"},{id:"printers",labelKey:"backup.categories.printers",defaultLabel:"Printers",icon:s.jsx(qr,{className:"w-4 h-4"}),default:!1,description:"Printer info (access codes excluded)"},{id:"plate_calibration",labelKey:"backup.categories.plateCalibration",defaultLabel:"Plate Detection",icon:s.jsx(Cf,{className:"w-4 h-4"}),default:!1,description:"Empty plate reference images",requiresPrinters:!0},{id:"filaments",labelKey:"backup.categories.filaments",defaultLabel:"Filament Inventory",icon:s.jsx(dD,{className:"w-4 h-4"}),default:!1,description:"Filament types and costs"},{id:"maintenance",labelKey:"backup.categories.maintenance",defaultLabel:"Maintenance Types",icon:s.jsx(Hd,{className:"w-4 h-4"}),default:!1,description:"Custom maintenance schedules"},{id:"archives",labelKey:"backup.categories.archives",defaultLabel:"Print Archives",icon:s.jsx(Ka,{className:"w-4 h-4"}),default:!1,description:"All print data + files (3MF, thumbnails, photos)"},{id:"projects",labelKey:"backup.categories.projects",defaultLabel:"Projects",icon:s.jsx(wa,{className:"w-4 h-4"}),default:!1,description:"Projects, BOM items, and attachments"},{id:"pending_uploads",labelKey:"backup.categories.pendingUploads",defaultLabel:"Pending Uploads",icon:s.jsx(di,{className:"w-4 h-4"}),default:!1,description:"Virtual printer uploads awaiting review"},{id:"api_keys",labelKey:"backup.categories.apiKeys",defaultLabel:"API Keys",icon:s.jsx(ef,{className:"w-4 h-4"}),default:!1,description:"Webhook API keys (new keys generated on import)"}];function xKe({onClose:t,onExport:e}){const{t:n}=Lg(),[r,i]=w.useState(()=>{const x={};return L1.forEach(y=>{x[y.id]=y.default}),x}),[a,o]=w.useState(!1),[l,c]=w.useState(!1);w.useEffect(()=>{const x=y=>{y.key==="Escape"&&t()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t]);const u=x=>{i(y=>({...y,[x]:!y[x]}))},d=()=>{const x={};L1.forEach(y=>{x[y.id]=!0}),i(x)},f=()=>{const x={};L1.forEach(y=>{x[y.id]=!1}),i(x)},m=Object.values(r).filter(Boolean).length,g=async()=>{c(!0);try{await e({...r,access_codes:a&&r.printers})}finally{c(!1)}};return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:l?void 0:t,children:s.jsx(wt,{className:"w-full max-w-lg",onClick:x=>x.stopPropagation(),children:s.jsxs(Nt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-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:s.jsx($r,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:n("backup.exportTitle",{defaultValue:"Export Backup"})}),s.jsx("p",{className:"text-sm text-bambu-gray",children:n("backup.selectCategories",{defaultValue:"Select data to include"})})]})]}),s.jsx("button",{onClick:t,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx(Ut,{className:"w-5 h-5"})})]}),s.jsxs("div",{className:"flex gap-2 px-4 pt-4",children:[s.jsx("button",{onClick:d,disabled:l,className:"text-sm text-bambu-green hover:text-bambu-green/80 disabled:opacity-50 disabled:cursor-not-allowed",children:n("common.selectAll",{defaultValue:"Select All"})}),s.jsx("span",{className:"text-bambu-gray",children:"|"}),s.jsx("button",{onClick:f,disabled:l,className:"text-sm text-bambu-gray hover:text-white disabled:opacity-50 disabled:cursor-not-allowed",children:n("common.selectNone",{defaultValue:"Select None"})})]}),s.jsx("div",{className:`p-4 space-y-2 max-h-[400px] overflow-y-auto ${l?"opacity-50 pointer-events-none":""}`,children:L1.map(x=>{const y=l||x.requiresPrinters&&!r.printers;return s.jsxs("label",{className:`flex items-center gap-3 p-3 rounded-lg transition-colors ${y?"cursor-not-allowed opacity-50":"cursor-pointer"} ${r[x.id]&&!y?"bg-bambu-green/10 border border-bambu-green/30":"bg-bambu-dark hover:bg-bambu-dark-tertiary border border-transparent"}`,children:[s.jsx("input",{type:"checkbox",checked:r[x.id]&&!y,onChange:()=>u(x.id),disabled:y,className:"w-4 h-4 rounded border-bambu-gray bg-bambu-dark text-bambu-green focus:ring-bambu-green focus:ring-offset-0"}),s.jsx("div",{className:`${r[x.id]&&!y?"text-bambu-green":"text-bambu-gray"}`,children:x.icon}),s.jsxs("div",{className:"flex-1",children:[s.jsx("div",{className:"text-white text-sm font-medium",children:n(x.labelKey,{defaultValue:x.defaultLabel})}),s.jsx("div",{className:"text-xs text-bambu-gray",children:x.requiresPrinters&&!r.printers?"Requires Printers to be selected":x.description})]})]},x.id)})}),r.archives&&s.jsx("div",{className:"mx-4 mb-2 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(Ka,{className:"w-4 h-4 text-yellow-500 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-yellow-200 dark:text-yellow-200 text-yellow-700",children:[s.jsx("span",{className:"font-medium",children:"ZIP file will be created."}),s.jsx("span",{className:"text-yellow-600 dark:text-yellow-200/70",children:" Includes all 3MF files, thumbnails, timelapses, and photos. This may take a while and result in a large file."})]})]})}),r.printers&&s.jsxs("div",{className:"mx-4 mb-2 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(ef,{className:"w-4 h-4 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{children:[s.jsx("p",{className:"text-sm font-medium text-white",children:"Include Access Codes"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"For transferring to another machine"})]})]}),s.jsx($n,{checked:a,onChange:o})]}),a&&s.jsx("div",{className:"mt-2 p-2 rounded bg-orange-500/10 border border-orange-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[s.jsx(Nn,{className:"w-3 h-3 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0"}),s.jsx("span",{className:"text-orange-700 dark:text-orange-200",children:"Access codes will be included in plain text. Keep this backup file secure!"})]})})]}),s.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary",children:[s.jsx("span",{className:"text-sm text-bambu-gray",children:n("backup.selectedCount",{count:m,defaultValue:`${m} categories selected`})}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Me,{variant:"secondary",onClick:t,disabled:l,children:n("common.cancel",{defaultValue:"Cancel"})}),s.jsx(Me,{onClick:g,disabled:m===0||l,className:"bg-bambu-green hover:bg-bambu-green-dark disabled:opacity-50 disabled:cursor-not-allowed min-w-[100px]",children:l?s.jsxs(s.Fragment,{children:[s.jsx(ut,{className:"w-4 h-4 mr-2 animate-spin"}),n("backup.exporting",{defaultValue:"Exporting..."})]}):s.jsxs(s.Fragment,{children:[s.jsx($r,{className:"w-4 h-4 mr-2"}),n("backup.export",{defaultValue:"Export"})]})})]})]})]})})})}const JG={settings:"Settings",notification_providers:"Notification Providers",notification_templates:"Notification Templates",smart_plugs:"Smart Plugs",printers:"Printers",filaments:"Filaments",maintenance_types:"Maintenance Types",archives:"Archives",projects:"Projects",pending_uploads:"Pending Uploads",external_links:"External Links",api_keys:"API Keys"};function bKe({onClose:t,onRestore:e,onSuccess:n}){const[r,i]=w.useState("options"),[a,o]=w.useState(!1),[l,c]=w.useState(null),[u,d]=w.useState(null),[f,m]=w.useState(new Set),g=w.useRef(null);w.useEffect(()=>{const A=T=>{T.key==="Escape"&&r!=="restoring"&&(r==="result"&&u?.success&&n(),t())};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[t,n,r,u]);const x=A=>{const T=A.target.files?.[0];T&&c(T)},y=async()=>{if(l){i("restoring");try{const A=await e(l,a);d(A),i("result")}catch{d({success:!1,message:"Failed to restore backup. Please check the file format."}),i("result")}}},b=()=>{u?.success&&n(),t()},v=A=>{m(T=>{const C=new Set(T);return C.has(A)?C.delete(A):C.add(A),C})},N=u?.restored?Object.values(u.restored).reduce((A,T)=>A+T,0)+(u.files_restored||0):0,S=u?.total_skipped||0;return s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onMouseDown:A=>{A.target===A.currentTarget&&r!=="restoring"&&t()},children:s.jsx(wt,{className:"w-full max-w-lg",children:s.jsxs(Nt,{className:"p-0",children:[s.jsxs("div",{className:"flex items-center justify-between p-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 ${r==="result"&&u?.success?"bg-bambu-green/20 text-bambu-green":r==="result"&&!u?.success?"bg-red-500/20 text-red-500":"bg-blue-500/20 text-blue-500"}`,children:r==="result"&&u?.success?s.jsx(Dn,{className:"w-5 h-5"}):r==="result"&&!u?.success?s.jsx(Nn,{className:"w-5 h-5"}):s.jsx(di,{className:"w-5 h-5"})}),s.jsxs("div",{children:[s.jsxs("h3",{className:"text-lg font-semibold text-white",children:[r==="options"&&"Restore Backup",r==="restoring"&&"Restoring...",r==="result"&&(u?.success?"Restore Complete":"Restore Failed")]}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:[r==="options"&&"Import settings from a backup file",r==="restoring"&&"Please wait while your data is being restored",r==="result"&&u?.message]})]})]}),r!=="restoring"&&s.jsx("button",{onClick:b,className:"p-2 hover:bg-bambu-dark-tertiary rounded-lg transition-colors",children:s.jsx(Ut,{className:"w-5 h-5"})})]}),r==="options"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("input",{ref:g,type:"file",accept:".json,.zip",className:"hidden",onChange:x}),s.jsx("button",{type:"button",onClick:()=>g.current?.click(),className:`w-full p-4 border-2 border-dashed rounded-lg transition-colors ${l?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:l?s.jsxs("div",{className:"flex items-center justify-center gap-2 text-bambu-green",children:[s.jsx(Dn,{className:"w-5 h-5"}),s.jsx("span",{className:"font-medium",children:l.name})]}):s.jsxs("div",{className:"flex flex-col items-center gap-2 text-bambu-gray",children:[s.jsx(di,{className:"w-8 h-8"}),s.jsx("span",{children:"Click to select backup file (.json or .zip)"})]})})]}),s.jsx("div",{className:"p-3 rounded-lg bg-blue-500/10 border border-blue-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Nn,{className:"w-4 h-4 text-blue-500 dark:text-blue-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-blue-700 dark:text-blue-200",children:[s.jsx("p",{className:"font-medium mb-1",children:"How duplicate handling works:"}),s.jsxs("ul",{className:"text-blue-600 dark:text-blue-200/80 space-y-1 text-xs",children:[s.jsxs("li",{children:[s.jsx("strong",{children:"Printers"})," - matched by serial number"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Smart Plugs"})," - matched by IP address"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Notification Providers"})," - matched by name"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Filaments"})," - matched by name + type + brand"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Archives"})," - matched by content hash (always skipped)"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Pending Uploads"})," - matched by filename"]}),s.jsxs("li",{children:[s.jsx("strong",{children:"Settings & Templates"})," - always overwritten"]})]})]})]})}),s.jsx("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsxs("p",{className:"text-white font-medium flex items-center gap-2",children:[a?s.jsx(gr,{className:"w-4 h-4 text-orange-400"}):s.jsx(m0,{className:"w-4 h-4 text-bambu-gray"}),a?"Replace existing data":"Keep existing data"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a?"Overwrite items that already exist with backup data":"Only restore items that don't already exist"})]}),s.jsx($n,{checked:a,onChange:o})]})}),a&&s.jsx("div",{className:"p-3 rounded-lg bg-orange-500/10 border border-orange-500/30",children:s.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[s.jsx(Nn,{className:"w-4 h-4 text-orange-500 dark:text-orange-400 mt-0.5 flex-shrink-0"}),s.jsxs("div",{className:"text-orange-700 dark:text-orange-200",children:[s.jsx("span",{className:"font-medium",children:"Caution:"})," Overwriting will replace your current configurations with data from the backup. Printer access codes are never overwritten for security."]})]})})]}),s.jsxs("div",{className:"flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:[s.jsx(Me,{type:"button",variant:"secondary",onClick:t,children:"Cancel"}),s.jsxs(Me,{type:"button",onClick:y,disabled:!l,className:"bg-bambu-green hover:bg-bambu-green-dark disabled:opacity-50",children:[s.jsx(di,{className:"w-4 h-4 mr-2"}),"Restore"]})]})]}),r==="restoring"&&s.jsxs("div",{className:"p-8 flex flex-col items-center gap-4",children:[s.jsx(ut,{className:"w-12 h-12 text-bambu-green animate-spin"}),s.jsx("p",{className:"text-bambu-gray",children:"Processing backup file..."})]}),r==="result"&&u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-4 space-y-4 max-h-[400px] overflow-y-auto",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{className:"p-3 rounded-lg bg-bambu-green/10 border border-bambu-green/30",children:[s.jsx("div",{className:"text-2xl font-bold text-bambu-green",children:N}),s.jsx("div",{className:"text-sm text-bambu-gray",children:"Items Restored"})]}),s.jsxs("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:[s.jsx("div",{className:"text-2xl font-bold text-yellow-500",children:S}),s.jsx("div",{className:"text-sm text-bambu-gray",children:"Items Skipped"})]})]}),u.restored&&Object.entries(u.restored).some(([,A])=>A>0)&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("h4",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green"}),"Restored"]}),s.jsxs("div",{className:"space-y-1",children:[Object.entries(u.restored).filter(([,A])=>A>0).map(([A,T])=>s.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded bg-bambu-dark",children:[s.jsx("span",{className:"text-white",children:JG[A]||A}),s.jsx("span",{className:"text-bambu-green font-medium",children:T})]},A)),(u.files_restored||0)>0&&s.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded bg-bambu-dark",children:[s.jsx("span",{className:"text-white",children:"Files (3MF, thumbnails, etc.)"}),s.jsx("span",{className:"text-bambu-green font-medium",children:u.files_restored})]})]})]}),u.skipped&&Object.entries(u.skipped).some(([,A])=>A>0)&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("h4",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(m0,{className:"w-4 h-4 text-yellow-500"}),"Skipped (already exist)"]}),s.jsx("div",{className:"space-y-1",children:Object.entries(u.skipped).filter(([,A])=>A>0).map(([A,T])=>{const C=u.skipped_details?.[A]||[],E=f.has(A);return s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>C.length>0&&v(A),className:`w-full flex items-center justify-between text-sm p-2 rounded bg-bambu-dark ${C.length>0?"hover:bg-bambu-dark-tertiary cursor-pointer":""}`,children:[s.jsxs("span",{className:"text-white flex items-center gap-2",children:[JG[A]||A,C.length>0&&(E?s.jsx(su,{className:"w-3 h-3"}):s.jsx(Pi,{className:"w-3 h-3"}))]}),s.jsx("span",{className:"text-yellow-500 font-medium",children:T})]}),E&&C.length>0&&s.jsxs("div",{className:"mt-1 ml-4 p-2 rounded bg-bambu-dark-tertiary text-xs text-bambu-gray space-y-1",children:[C.slice(0,10).map((D,k)=>s.jsx("div",{children:D},k)),C.length>10&&s.jsxs("div",{className:"text-bambu-gray/60",children:["...and ",C.length-10," more"]})]})]},A)})})]}),u.new_api_keys&&u.new_api_keys.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("h4",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[s.jsx(Nn,{className:"w-4 h-4 text-orange-500"}),"New API Keys Generated"]}),s.jsxs("div",{className:"p-3 rounded bg-orange-500/10 border border-orange-500/30",children:[s.jsx("p",{className:"text-xs text-orange-200 mb-2",children:"These keys are only shown once. Copy them now!"}),s.jsx("div",{className:"space-y-2",children:u.new_api_keys.map((A,T)=>s.jsxs("div",{className:"p-2 rounded bg-bambu-dark",children:[s.jsx("div",{className:"text-sm text-white font-medium mb-1",children:A.name}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"text-xs text-bambu-green bg-bambu-dark-tertiary px-2 py-1 rounded font-mono flex-1 break-all",children:A.key}),s.jsx("button",{onClick:()=>navigator.clipboard.writeText(A.key),className:"text-xs text-bambu-gray hover:text-white px-2 py-1 rounded bg-bambu-dark-tertiary",children:"Copy"})]})]},T))})]})]}),N===0&&S===0&&s.jsx("div",{className:"p-4 text-center text-bambu-gray",children:"No data was found to restore in the backup file."})]}),s.jsx("div",{className:"flex items-center justify-end gap-3 p-4 border-t border-bambu-dark-tertiary",children:s.jsx(Me,{onClick:b,children:"Close"})})]})]})})})}function eq({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(Dn,{className:"w-3 h-3"}),failed:s.jsx(ea,{className:"w-3 h-3"}),skipped:s.jsx(m0,{className:"w-3 h-3"}),running:s.jsx(ut,{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 tq(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}=Hn(),[n,r]=w.useState(""),[i,a]=w.useState(""),[o,l]=w.useState("main"),[c,u]=w.useState(!1),[d,f]=w.useState("daily"),[m,g]=w.useState(!0),[x,y]=w.useState(!0),[b,v]=w.useState(!1),[N,S]=w.useState(!0),[A,T]=w.useState(!1),[C,E]=w.useState(!1),[D,k]=w.useState(!1),[R,F]=w.useState(null),O=w.useRef(null),X=w.useRef(!1),{data:j,isLoading:q}=ct({queryKey:["github-backup-config"],queryFn:fe.getGitHubBackupConfig}),{data:Y}=ct({queryKey:["github-backup-status"],queryFn:fe.getGitHubBackupStatus,refetchInterval:oe=>oe.state.data?.is_running?500:1e4}),{data:W}=ct({queryKey:["github-backup-logs"],queryFn:()=>fe.getGitHubBackupLogs(20)}),{data:Z}=ct({queryKey:["cloud-status"],queryFn:fe.getCloudStatus}),{data:ee}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),ne=Jq({queries:(ee??[]).map(oe=>({queryKey:["printerStatus",oe.id],queryFn:()=>fe.getPrinterStatus(oe.id),staleTime:1e4,refetchInterval:3e4}))}),z=(ee??[]).map((oe,ze)=>({printer:oe,connected:ne[ze]?.data?.connected??!1})),G=z.length,ae=z.filter(oe=>oe.connected).length,se=G>0&&ae===0,de=ae>0&&ae{j&&(r(j.repository_url),l(j.branch),u(j.schedule_enabled),f(j.schedule_type),g(j.backup_kprofiles),y(j.backup_cloud_profiles),v(j.backup_settings),S(j.enabled),a(""),setTimeout(()=>{X.current=!0},100))},[j]);const me=w.useCallback(async(oe=!1)=>{if(j?.has_token)try{oe&&i?(await fe.saveGitHubBackupConfig({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:m,backup_cloud_profiles:x,backup_settings:b,enabled:N}),a(""),e("Token updated")):(await fe.updateGitHubBackupConfig({repository_url:n,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:m,backup_cloud_profiles:x,backup_settings:b,enabled:N}),e("Settings saved")),t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(ze){e(`Failed to save: ${ze.message}`,"error")}},[j?.has_token,n,i,o,c,d,m,x,b,N,t,e]);w.useEffect(()=>{if(!(!X.current||!j?.has_token))return O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{me(!1)},500),()=>{O.current&&clearTimeout(O.current)}},[n,o,c,d,m,x,b,N,me,j?.has_token]),w.useEffect(()=>{if(!(!X.current||!j?.has_token||!i))return O.current&&clearTimeout(O.current),O.current=setTimeout(()=>{me(!0)},1e3),()=>{O.current&&clearTimeout(O.current)}},[i,me,j?.has_token]);const ue=ht({mutationFn:oe=>fe.saveGitHubBackupConfig(oe),onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e("GitHub backup enabled"),a(""),X.current=!0},onError:oe=>{e(`Failed to save: ${oe.message}`,"error")}}),Ae=ht({mutationFn:fe.triggerGitHubBackup,onSuccess:oe=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),oe.success?oe.files_changed>0?e(`Backup complete - ${oe.files_changed} files updated`):e("Backup skipped - no changes"):e(`Backup failed: ${oe.message}`,"error")},onError:oe=>{e(`Backup failed: ${oe.message}`,"error")}}),pe=ht({mutationFn:()=>fe.clearGitHubBackupLogs(0),onSuccess:oe=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(`Cleared ${oe.deleted} logs`)},onError:oe=>{e(`Failed to clear logs: ${oe.message}`,"error")}}),Ee=async()=>{k(!0),F(null);try{let oe;if(i){if(!n){e("Enter repository URL","error"),k(!1);return}oe=await fe.testGitHubConnection(n,i)}else if(j?.has_token)oe=await fe.testGitHubStoredConnection();else{e("Enter repository URL and access token","error"),k(!1);return}F({success:oe.success,message:oe.message})}catch(oe){F({success:!1,message:oe.message})}finally{k(!1)}},_e=()=>{if(!n){e("Repository URL is required","error");return}if(!i){e("Access token is required","error");return}ue.mutate({repository_url:n,access_token:i,branch:o,schedule_enabled:c,schedule_type:d,backup_kprofiles:m,backup_cloud_profiles:x,backup_settings:b,enabled:N})};return q?s.jsx("div",{className:"flex items-center justify-center py-12",children:s.jsx(ut,{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(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(qj,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"GitHub Backup"})]}),j&&Z?.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($n,{checked:N,onChange:S})]})]})}),s.jsx(Nt,{className:"space-y-4",children:Z?.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:oe=>{r(oe.target.value),F(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 ",j?.has_token&&s.jsx("span",{className:"text-green-400",children:"(saved)"})]}),s.jsx("input",{type:"password",value:i,onChange:oe=>{a(oe.target.value),F(null)},placeholder:j?.has_token?"Enter new token to update":"ghp_xxxxxxxxxxxx",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),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:oe=>l(oe.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:oe=>{oe.target.value==="disabled"?u(!1):(u(!0),f(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:"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 ${se?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[s.jsx("input",{type:"checkbox",checked:m,onChange:oe=>g(oe.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:se}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`text-sm ${se?"text-bambu-gray":"text-white"}`,children:"K-Profiles"}),se&&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(Nn,{className:"w-3 h-3"}),"No printers connected"]}),de&&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(Nn,{className:"w-3 h-3"}),ae,"/",G," 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:oe=>y(oe.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:!Z?.is_authenticated}),s.jsxs("div",{children:[s.jsx("span",{className:`text-sm ${Z?.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:b,onChange:oe=>v(oe.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:[Y?.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:Y.last_backup_at?s.jsxs(s.Fragment,{children:[s.jsxs("span",{children:["Last backup: ",tq(Y.last_backup_at)]}),s.jsx(eq,{status:Y.last_backup_status})]}):s.jsx("span",{children:"No backups yet"})}),Y.next_scheduled_run&&s.jsxs("span",{className:"text-bambu-gray",children:[s.jsx(Wn,{className:"w-3 h-3 inline mr-1"}),"Next: ",tq(Y.next_scheduled_run)]})]}),R&&s.jsxs("div",{className:`text-sm flex items-center gap-1 ${R.success?"text-green-400":"text-red-400"}`,children:[R.success?s.jsx(Dn,{className:"w-4 h-4"}):s.jsx(ea,{className:"w-4 h-4"}),R.message]}),s.jsx("div",{className:"flex flex-wrap items-center gap-2",children:Y?.configured?s.jsx(s.Fragment,{children:Ae.isPending||Y.is_running?s.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[s.jsx(ut,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{className:"text-sm",children:Y.progress||"Starting backup..."})]}):s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"primary",size:"sm",onClick:()=>Ae.mutate(),disabled:!j?.enabled,children:[s.jsx(Po,{className:"w-4 h-4"}),"Backup Now"]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:Ee,disabled:D,children:[D?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Test"]})]})}):s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"primary",size:"sm",onClick:_e,disabled:ue.isPending||!n||!i,children:[ue.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Dn,{className:"w-4 h-4"}),"Enable Backup"]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:Ee,disabled:D||!n||!i,children:[D?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{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(Nn,{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."})]})})]}),W&&W.length>0&&s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(f0,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"History"})]}),s.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>pe.mutate(),disabled:pe.isPending,children:[s.jsx(ln,{className:"w-4 h-4"}),"Clear"]})]})}),s.jsx(Nt,{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:W.slice(0,10).map(oe=>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(oe.started_at)}),s.jsx("td",{className:"py-2 px-2",children:s.jsx(eq,{status:oe.status})}),s.jsx("td",{className:"py-2 px-2",children:oe.commit_sha?s.jsxs("a",{href:`${j?.repository_url}/commit/${oe.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[oe.commit_sha.substring(0,7),s.jsx(Ur,{className:"w-3 h-3"})]}):s.jsx("span",{className:"text-bambu-gray",children:"-"})})]},oe.id))})]})})})]})]}),s.jsx("div",{className:"space-y-6",children:s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Qc,{className:"w-5 h-5 text-gray-400"}),s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Local Backup"})]})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Export or import your Bambuddy data as a local file for manual backup or migration."}),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:"Export Data"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Download all settings, printers, and profiles"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>T(!0),children:[s.jsx($r,{className:"w-4 h-4"}),"Export"]})]}),s.jsxs("div",{className:"flex items-center justify-between py-3",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Import Backup"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Restore from a previous export file"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>E(!0),children:[s.jsx(di,{className:"w-4 h-4"}),"Import"]})]})]})]})}),A&&s.jsx(xKe,{onClose:()=>T(!1),onExport:async oe=>{T(!1);try{const{blob:ze,filename:V}=await fe.exportBackup(oe),H=URL.createObjectURL(ze),K=document.createElement("a");K.href=H,K.download=V,K.click(),URL.revokeObjectURL(H),e("Backup downloaded successfully")}catch{e("Failed to create backup","error")}}}),C&&s.jsx(bKe,{onClose:()=>E(!1),onRestore:async(oe,ze)=>await fe.importBackup(oe,ze),onSuccess:()=>{E(!1),e("Backup restored successfully"),t.invalidateQueries()}})]})}const _Ke={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 wKe(t,e){const n=e.replace("#/","").split("/");let r=t;for(const i of n)r=r[i];return r}function Lb(t,e,n=0){if(n>5)return"...";if(e.$ref)return Lb(t,wKe(t,e.$ref),n+1);if(e.allOf){const r={};for(const i of e.allOf){const a=Lb(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?[Lb(t,e.items,n+1)]:[];case"object":if(e.properties){const r={};for(const[i,a]of Object.entries(e.properties))r[i]=Lb(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]=w.useState(!1),[l,c]=w.useState({}),[u,d]=w.useState(""),[f,m]=w.useState(null),[g,x]=w.useState(!1),[y,b]=w.useState(!1);w.useEffect(()=>{if(a&&n.parameters){const D={};for(const k of n.parameters)k.schema?.default!==void 0&&(D[k.name]=String(k.schema.default));c(k=>({...D,...k}))}},[a,n.parameters]),w.useEffect(()=>{if(a&&n.requestBody?.content?.["application/json"]?.schema&&!u){const D=n.requestBody.content["application/json"].schema,k=Lb(r,D);d(JSON.stringify(k,null,2))}},[a,n.requestBody,r,u]);const N=(()=>{const D=[];for(const k of n.parameters||[])if(k.in==="path"||k.required){const R=l[k.name];(R===void 0||R==="")&&D.push(k.name)}return D})(),S=async()=>{if(N.length>0){m({status:0,statusText:"Validation Error",headers:{},body:`Missing required parameters: ${N.join(", ")}`,duration:0});return}x(!0),m(null);try{let D=t;const k=new URLSearchParams;for(const ne of n.parameters||[]){const z=l[ne.name];z!==void 0&&z!==""&&(ne.in==="path"?D=D.replace(`{${ne.name}}`,encodeURIComponent(z)):ne.in==="query"&&k.append(ne.name,z))}const R=k.toString(),F=`${D}${R?`?${R}`:""}`,O={"Content-Type":"application/json"};i&&(O["X-API-Key"]=i);const X={method:e.toUpperCase(),headers:O};["post","put","patch"].includes(e)&&u&&(X.body=u);const j=performance.now(),q=await fetch(F,X),Y=Math.round(performance.now()-j),W={};q.headers.forEach((ne,z)=>{W[z]=ne});let Z;q.headers.get("content-type")?.includes("application/json")?Z=await q.json():Z=await q.text(),m({status:q.status,statusText:q.statusText,headers:W,body:Z,duration:Y})}catch(D){m({status:0,statusText:"Network Error",headers:{},body:D instanceof Error?D.message:"Unknown error",duration:0})}finally{x(!1)}},A=async()=>{if(f){const D=typeof f.body=="string"?f.body:JSON.stringify(f.body,null,2);try{await navigator.clipboard.writeText(D),b(!0),setTimeout(()=>b(!1),2e3)}catch{const k=document.createElement("textarea");k.value=D,k.style.position="fixed",k.style.left="-999999px",document.body.appendChild(k),k.select(),document.execCommand("copy"),document.body.removeChild(k),b(!0),setTimeout(()=>b(!1),2e3)}}},T=(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(Pi,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}):s.jsx(Ss,{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 ${_Ke[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}),T.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:T.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:k=>c(R=>({...R,[D.name]:k.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:k=>c(R=>({...R,[D.name]:k.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(k=>s.jsx("option",{value:k,children:k},k))]}):s.jsx("input",{type:"text",value:l[D.name]||"",onChange:k=>c(R=>({...R,[D.name]:k.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(Me,{onClick:S,disabled:g,children:[g?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Po,{className:"w-4 h-4"}),"Execute"]}),N.length>0&&s.jsxs("span",{className:"text-xs text-yellow-400 flex items-center gap-1",children:[s.jsx(ra,{className:"w-3 h-3"}),"Fill in: ",N.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(Me,{variant:"secondary",size:"sm",onClick:A,children:y?s.jsx(Dn,{className:"w-3 h-3 text-green-400"}):s.jsx(ll,{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 NKe({apiKey:t=""}){const[e,n]=w.useState(null),[r,i]=w.useState(!0),[a,o]=w.useState(null),[l,c]=w.useState(new Set),[u,d]=w.useState("");if(w.useEffect(()=>{async function b(){try{const v=await fetch("/openapi.json");if(!v.ok)throw new Error("Failed to fetch OpenAPI schema");const N=await v.json();n(N)}catch(v){o(v instanceof Error?v.message:"Unknown error")}finally{i(!1)}}b()},[]),r)return s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})});if(a||!e)return s.jsx(wt,{children:s.jsx(Nt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-red-400",children:[s.jsx(ra,{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[b,v]of Object.entries(e.paths))for(const[N,S]of Object.entries(v)){if(N==="parameters")continue;const A=S.tags||["Other"];for(const T of A)f[T]||(f[T]=[]),f[T].push({path:b,method:N,spec:S})}const m=Object.entries(f).map(([b,v])=>{if(!u)return{tag:b,endpoints:v};const N=v.filter(({path:S,method:A,spec:T})=>{const C=u.toLowerCase();return S.toLowerCase().includes(C)||A.toLowerCase().includes(C)||(T.summary?.toLowerCase()||"").includes(C)||(T.description?.toLowerCase()||"").includes(C)});return{tag:b,endpoints:N}}).filter(({endpoints:b})=>b.length>0).sort((b,v)=>b.tag.localeCompare(v.tag)),g=b=>{c(v=>{const N=new Set(v);return N.has(b)?N.delete(b):N.add(b),N})},x=()=>{c(new Set(m.map(b=>b.tag)))},y=()=>{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:b=>d(b.target.value),placeholder:"Search endpoints...",className:"w-full max-w-md px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Me,{variant:"secondary",size:"sm",onClick:x,children:"Expand All"}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:y,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(Ur,{className:"w-4 h-4"}),"Swagger UI"]})]})]}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:[m.reduce((b,v)=>b+v.endpoints.length,0)," endpoints in ",m.length," categories"]}),s.jsx("div",{className:"space-y-3",children:m.map(({tag:b,endpoints:v})=>s.jsxs(wt,{children:[s.jsx("button",{onClick:()=>g(b),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(b)?s.jsx(Pi,{className:"w-5 h-5 text-bambu-gray"}):s.jsx(Ss,{className:"w-5 h-5 text-bambu-gray"}),s.jsx("h3",{className:"text-base font-semibold text-white capitalize",children:b.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(b)&&s.jsx(Nt,{className:"pt-0 space-y-2",children:v.map(({path:N,method:S,spec:A})=>s.jsx(SKe,{path:N,method:S,spec:A,schema:e,apiKey:t},`${S}-${N}`))})]},b))})]})}const MKe=["general","network","plugs","notifications","filament","apikeys","virtual-printer","users","backup"];function EKe(){const t=an(),e=fl(),[n,r]=Oq(),{t:i,i18n:a}=Lg(),{showToast:o}=Hn(),{authEnabled:l,user:c,refreshAuth:u}=ah(),{mode:d,darkStyle:f,darkBackground:m,darkAccent:g,lightStyle:x,lightBackground:y,lightAccent:b,setDarkStyle:v,setDarkBackground:N,setDarkAccent:S,setLightStyle:A,setLightBackground:T,setLightAccent:C}=ih(),[E,D]=w.useState(null),[k,R]=w.useState(!1),[F,O]=w.useState(null),[X,j]=w.useState(!1),[q,Y]=w.useState(null),[W,Z]=w.useState(null),[ee,ne]=w.useState(!1),[z,G]=w.useState(SW()),ae=n.get("tab"),se=ae&&MKe.includes(ae)?ae:"general",[de,me]=w.useState(se),ue=ve=>{me(ve),ve==="general"?n.delete("tab"):n.set("tab",ve),r(n,{replace:!0})},[Ae,pe]=w.useState(!1),[Ee,_e]=w.useState(""),[oe,ze]=w.useState({can_queue:!0,can_control_printer:!1,can_read_status:!0}),[V,H]=w.useState(null),[K,U]=w.useState(null),[Q,le]=w.useState(""),[ke,Re]=w.useState(!1),[Ce,B]=w.useState(!1),[I,$]=w.useState(null),[te,ye]=w.useState(!1),[be,Ye]=w.useState(!1),[$e,Qe]=w.useState(null),[qe,Xe]=w.useState(!1),[ce,ie]=w.useState({}),[Te,Ve]=w.useState({}),it=ve=>{G(ve),Tfe(ve)},re=()=>{localStorage.removeItem("sidebarOrder"),window.location.reload()},{data:De,isLoading:we}=ct({queryKey:["settings"],queryFn:fe.getSettings}),{data:Oe,isLoading:Ue}=ct({queryKey:["smart-plugs"],queryFn:fe.getSmartPlugs}),{data:je,isLoading:Je}=ct({queryKey:["smart-plugs-energy",Oe?.map(ve=>ve.id)],queryFn:async()=>{if(!Oe||Oe.length===0)return null;const ve=await Promise.all(Oe.filter(Wt=>Wt.enabled).map(async Wt=>{try{const Kt=await fe.getSmartPlugStatus(Wt.id);return{plug:Wt,status:Kt}}catch{return{plug:Wt,status:null}}}));let Et=0,Be=0,mt=0,jt=0,gt=0;for(const{plug:Wt,status:Kt}of ve){const Bn=Wt.plug_type==="mqtt"&&Kt?.energy?.power!=null;(Kt?.reachable||Bn)&&Kt?.energy&&(gt++,Kt.energy?.power!=null&&(Et+=Kt.energy.power),Kt.energy?.today!=null&&(Be+=Kt.energy.today),Kt.energy?.yesterday!=null&&(mt+=Kt.energy.yesterday),Kt.energy?.total!=null&&(jt+=Kt.energy.total))}return{totalPower:Et,totalToday:Be,totalYesterday:mt,totalLifetime:jt,reachableCount:gt,totalPlugs:Oe.filter(Wt=>Wt.enabled).length}},enabled:de==="plugs"&&!!Oe&&Oe.length>0,refetchInterval:de==="plugs"?1e4:!1}),{data:bt,isLoading:Tt}=ct({queryKey:["notification-providers"],queryFn:fe.getNotificationProviders}),{data:Dt,isLoading:sn}=ct({queryKey:["api-keys"],queryFn:fe.getAPIKeys}),Lt=ht({mutationFn:ve=>fe.createAPIKey(ve),onSuccess:ve=>{H(ve.key||null),pe(!1),_e(""),t.invalidateQueries({queryKey:["api-keys"]}),o("API key created")},onError:ve=>{o(`Failed to create API key: ${ve.message}`,"error")}}),gn=ht({mutationFn:ve=>fe.deleteAPIKey(ve),onSuccess:()=>{t.invalidateQueries({queryKey:["api-keys"]}),o("API key deleted")},onError:ve=>{o(`Failed to delete API key: ${ve.message}`,"error")}}),{data:rn}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:zn,isLoading:br}=ct({queryKey:["notification-templates"],queryFn:fe.getNotificationTemplates}),{data:er}=ct({queryKey:["virtual-printer-settings"],queryFn:z1.getSettings,refetchInterval:1e4}),yr=er?.status?.running??!1,{data:vr}=ct({queryKey:["ffmpeg-status"],queryFn:fe.checkFfmpeg}),{data:Xn}=ct({queryKey:["version"],queryFn:fe.getVersion}),{data:Bt,refetch:In,isRefetching:Ti}=ct({queryKey:["updateCheck"],queryFn:fe.checkForUpdates,staleTime:300*1e3}),{data:_r,refetch:Se}=ct({queryKey:["updateStatus"],queryFn:fe.getUpdateStatus,refetchInterval:ve=>{const Et=ve.state.data;return Et?.status==="downloading"||Et?.status==="installing"?1e3:!1}}),{data:We}=ct({queryKey:["mqtt-status"],queryFn:fe.getMQTTStatus,refetchInterval:de==="network"?5e3:!1}),{data:et}=ct({queryKey:["github-backup-status"],queryFn:fe.getGitHubBackupStatus}),{data:ot}=ct({queryKey:["cloud-status"],queryFn:fe.getCloudStatus}),at=ht({mutationFn:fe.applyUpdate,onSuccess:ve=>{ve.is_docker?o(ve.message,"error"):Se()}}),[At,he]=w.useState(null),xe=ht({mutationFn:fe.testAllNotificationProviders,onSuccess:ve=>{he(ve),t.invalidateQueries({queryKey:["notification-providers"]}),ve.failed===0?o(`All ${ve.tested} providers tested successfully!`,"success"):o(`${ve.success}/${ve.tested} providers succeeded`,ve.failed>0?"error":"success")},onError:ve=>{o(`Failed to test providers: ${ve.message}`,"error")}}),Le=ht({mutationFn:async ve=>{if(!Oe)return{success:0,failed:0};const Et=Oe.filter(mt=>mt.enabled),Be=await Promise.all(Et.map(async mt=>{try{return await fe.controlSmartPlug(mt.id,ve),{success:!0}}catch{return{success:!1}}}));return{success:Be.filter(mt=>mt.success).length,failed:Be.filter(mt=>!mt.success).length}},onSuccess:(ve,Et)=>{t.invalidateQueries({queryKey:["smart-plugs"]}),t.invalidateQueries({queryKey:["smart-plugs-energy"]}),ve.failed===0?o(`All ${ve.success} plugs turned ${Et}`,"success"):o(`${ve.success} plugs turned ${Et}, ${ve.failed} failed`,"error")},onError:ve=>{o(`Failed: ${ve.message}`,"error")}}),Ie=w.useRef(null),Ne=w.useRef(!1),ft=w.useRef(!0);w.useEffect(()=>{if(De&&!E){const ve={...De,external_url:De.external_url||window.location.origin};D(ve),setTimeout(()=>{ft.current=!1},100)}},[De,E]);const _t=ht({mutationFn:fe.updateSettings,onSuccess:ve=>{t.setQueryData(["settings"],ve),D(ve),t.invalidateQueries({queryKey:["archiveStats"]}),o("Settings saved","success")},onError:ve=>{o(`Failed to save: ${ve.message}`,"error")},onSettled:()=>{Ne.current=!1}}),kt=ht({mutationFn:({id:ve,data:Et})=>fe.updatePrinter(ve,Et),onSuccess:()=>{t.invalidateQueries({queryKey:["printers"]}),o("Camera settings saved","success")},onError:ve=>{o(`Failed to update printer: ${ve.message}`,"error")}});w.useEffect(()=>{if(!(ft.current||!E||!De||!(De.auto_archive!==E.auto_archive||De.save_thumbnails!==E.save_thumbnails||De.capture_finish_photo!==E.capture_finish_photo||De.default_filament_cost!==E.default_filament_cost||De.currency!==E.currency||De.energy_cost_per_kwh!==E.energy_cost_per_kwh||De.energy_tracking_mode!==E.energy_tracking_mode||De.check_updates!==E.check_updates||(De.check_printer_firmware??!0)!==(E.check_printer_firmware??!0)||De.notification_language!==E.notification_language||De.ams_humidity_good!==E.ams_humidity_good||De.ams_humidity_fair!==E.ams_humidity_fair||De.ams_temp_good!==E.ams_temp_good||De.ams_temp_fair!==E.ams_temp_fair||De.ams_history_retention_days!==E.ams_history_retention_days||De.per_printer_mapping_expanded!==E.per_printer_mapping_expanded||De.date_format!==E.date_format||De.time_format!==E.time_format||De.default_printer_id!==E.default_printer_id||De.ftp_retry_enabled!==E.ftp_retry_enabled||De.ftp_retry_count!==E.ftp_retry_count||De.ftp_retry_delay!==E.ftp_retry_delay||De.ftp_timeout!==E.ftp_timeout||De.mqtt_enabled!==E.mqtt_enabled||De.mqtt_broker!==E.mqtt_broker||De.mqtt_port!==E.mqtt_port||De.mqtt_username!==E.mqtt_username||De.mqtt_password!==E.mqtt_password||De.mqtt_topic_prefix!==E.mqtt_topic_prefix||De.mqtt_use_tls!==E.mqtt_use_tls||De.external_url!==E.external_url||De.ha_enabled!==E.ha_enabled||De.ha_url!==E.ha_url||De.ha_token!==E.ha_token||(De.library_archive_mode??"ask")!==(E.library_archive_mode??"ask")||Number(De.library_disk_warning_gb??5)!==Number(E.library_disk_warning_gb??5)||(De.camera_view_mode??"window")!==(E.camera_view_mode??"window")||De.prometheus_enabled!==E.prometheus_enabled||De.prometheus_token!==E.prometheus_token))&&!Ne.current)return Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{if(Ne.current)return;Ne.current=!0;const Et={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};_t.mutate(Et)},500),()=>{Ie.current&&clearTimeout(Ie.current)}},[E,De,_t]);const pt=w.useCallback((ve,Et)=>{D(Be=>Be?{...Be,[ve]:Et}:null)},[]),$t=async(ve,Et,Be)=>{if(!Et){o("Please enter a camera URL","error");return}Ve(mt=>({...mt,[ve]:!0})),ie(mt=>({...mt,[ve]:null}));try{const mt=await fe.testExternalCamera(ve,Et,Be);ie(jt=>({...jt,[ve]:mt})),mt.success?o(`Camera connected${mt.resolution?` (${mt.resolution})`:""}`,"success"):o(mt.error||"Connection failed","error")}catch(mt){const jt=mt instanceof Error?mt.message:"Test failed";ie(gt=>({...gt,[ve]:{success:!1,error:jt}})),o(jt,"error")}finally{Ve(mt=>({...mt,[ve]:!1}))}},[Pt,St]=w.useState({}),Yt=w.useRef({});w.useEffect(()=>{if(rn){const ve={};rn.forEach(Et=>{Et.external_camera_url&&Pt[Et.id]===void 0&&(ve[Et.id]=Et.external_camera_url)}),Object.keys(ve).length>0&&St(Et=>({...Et,...ve}))}},[rn]);const qt=(ve,Et)=>{St(Be=>({...Be,[ve]:Et})),Yt.current[ve]&&clearTimeout(Yt.current[ve]),Yt.current[ve]=setTimeout(()=>{kt.mutate({id:ve,data:{external_camera_url:Et||null}})},800)},dn=(ve,Et)=>{const Be={};Et.type!==void 0&&(Be.external_camera_type=Et.type||null),Et.enabled!==void 0&&(Be.external_camera_enabled=Et.enabled),kt.mutate({id:ve,data:Be})};return we||!E?s.jsx("div",{className:"p-4 md:p-8 flex justify-center",children:s.jsx(ut,{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:"Settings"}),s.jsx("p",{className:"text-bambu-gray",children:"Configure Bambuddy"})]}),s.jsxs("div",{className:"flex gap-1 mb-6 border-b border-bambu-dark-tertiary overflow-x-auto",children:[s.jsx("button",{onClick:()=>ue("general"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${de==="general"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:"General"}),s.jsxs("button",{onClick:()=>ue("plugs"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="plugs"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Gs,{className:"w-4 h-4"}),"Smart Plugs",Oe&&Oe.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Oe.length})]}),s.jsxs("button",{onClick:()=>ue("notifications"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="notifications"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(df,{className:"w-4 h-4"}),"Notifications",bt&&bt.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:bt.length})]}),s.jsxs("button",{onClick:()=>ue("filament"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="filament"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(due,{className:"w-4 h-4"}),"Filament"]}),s.jsxs("button",{onClick:()=>ue("network"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="network"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Vp,{className:"w-4 h-4"}),"Network",s.jsx("span",{className:`w-2 h-2 rounded-full ${We?.enabled?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>ue("apikeys"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="apikeys"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(ef,{className:"w-4 h-4"}),"API Keys",Dt&&Dt.length>0&&s.jsx("span",{className:"text-xs bg-bambu-dark-tertiary px-1.5 py-0.5 rounded-full",children:Dt.length})]}),s.jsxs("button",{onClick:()=>ue("virtual-printer"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="virtual-printer"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(qr,{className:"w-4 h-4"}),"Virtual Printer",s.jsx("span",{className:`w-2 h-2 rounded-full ${yr?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>ue("users"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="users"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(tf,{className:"w-4 h-4"}),"Users",l&&s.jsx("span",{className:`w-2 h-2 rounded-full ${l?"bg-green-400":"bg-gray-500"}`})]}),s.jsxs("button",{onClick:()=>ue("backup"),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px flex items-center gap-2 ${de==="backup"?"text-bambu-green border-bambu-green":"text-bambu-gray hover:text-gray-900 dark:hover:text-white border-transparent"}`,children:[s.jsx(Qc,{className:"w-4 h-4"}),"Backup",s.jsx("span",{className:`w-2 h-2 rounded-full ${ot?.is_authenticated&&et?.configured&&et?.enabled?"bg-green-400":"bg-gray-500"}`})]})]}),de==="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(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:i("settings.general")})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[s.jsx(jd,{className:"w-4 h-4 inline mr-1"}),i("settings.language")]}),s.jsx("select",{value:a.language,onChange:ve=>a.changeLanguage(ve.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:JU.map(ve=>s.jsxs("option",{value:ve.code,children:[ve.nativeName," (",ve.name,")"]},ve.code))}),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.jsx("select",{value:z,onChange:ve=>it(ve.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:g0.map(ve=>s.jsx("option",{value:ve.to,children:i(ve.labelKey)},ve.id))}),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("select",{value:E.date_format||"system",onChange:ve=>pt("date_format",ve.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:"system",children:"System Default"}),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.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Time Format"}),s.jsxs("select",{value:E.time_format||"system",onChange:ve=>pt("time_format",ve.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:"system",children:"System Default"}),s.jsx("option",{value:"12h",children:"12-hour (3:30 PM)"}),s.jsx("option",{value:"24h",children:"24-hour (15:30)"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Default Printer"}),s.jsxs("select",{value:E.default_printer_id??"",onChange:ve=>pt("default_printer_id",ve.target.value?Number(ve.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 default (ask each time)"}),rn?.map(ve=>s.jsx("option",{value:ve.id,children:ve.name},ve.id))]}),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:"Sidebar order"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Drag items in the sidebar to reorder. Reset to default order here."})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:re,children:[s.jsx(Zf,{className:"w-4 h-4"}),"Reset"]})]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(dD,{className:"w-5 h-5"}),"Appearance"]})}),s.jsxs(Nt,{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:m,onChange:ve=>{N(ve.target.value),o("Settings saved","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:g,onChange:ve=>{S(ve.target.value),o("Settings saved","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:ve=>{v(ve.target.value),o("Settings saved","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:y,onChange:ve=>{T(ve.target.value),o("Settings saved","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:b,onChange:ve=>{C(ve.target.value),o("Settings saved","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:ve=>{A(ve.target.value),o("Settings saved","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(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Archive Settings"})}),s.jsxs(Nt,{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:ve=>pt("auto_archive",ve.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:"Save thumbnails"}),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:ve=>pt("save_thumbnails",ve.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:"Capture finish photo"}),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:ve=>pt("capture_finish_photo",ve.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&&vr&&!vr.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(Nn,{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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(gD,{className:"w-5 h-5 text-bambu-green"}),"Camera"]})}),s.jsxs(Nt,{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:ve=>pt("camera_view_mode",ve.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:"New Window"}),s.jsx("option",{value:"embedded",children:"Embedded Overlay"})]}),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:"External Cameras"}),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."}),rn&&rn.length>0?s.jsx("div",{className:"space-y-3",children:rn.map(ve=>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:ve.name}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:ve.external_camera_enabled,onChange:Et=>dn(ve.id,{enabled:Et.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"})]})]}),ve.external_camera_enabled&&s.jsxs("div",{className:"space-y-2 mt-2",children:[s.jsx("input",{type:"text",placeholder:ve.external_camera_type==="usb"?"Device path (/dev/video0)":"Camera URL (rtsp://... or http://...)",value:Pt[ve.id]??ve.external_camera_url??"",onChange:Et=>qt(ve.id,Et.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsxs("select",{value:ve.external_camera_type||"mjpeg",onChange:Et=>dn(ve.id,{type:Et.target.value}),className:"flex-1 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",children:[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(Me,{size:"sm",variant:"secondary",onClick:()=>$t(ve.id,Pt[ve.id]??ve.external_camera_url??"",ve.external_camera_type||"mjpeg"),disabled:Te[ve.id]||!(Pt[ve.id]??ve.external_camera_url),children:Te[ve.id]?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):"Test"})]}),ce[ve.id]&&s.jsx("div",{className:`text-xs flex items-center gap-1 ${ce[ve.id]?.success?"text-green-500":"text-red-500"}`,children:ce[ve.id]?.success?s.jsxs(s.Fragment,{children:[s.jsx(Dn,{className:"w-3 h-3"}),"Connected",ce[ve.id]?.resolution&&` (${ce[ve.id]?.resolution})`]}):s.jsxs(s.Fragment,{children:[s.jsx(ea,{className:"w-3 h-3"}),ce[ve.id]?.error||"Connection failed"]})})]})]},ve.id))}):s.jsx("p",{className:"text-xs text-bambu-gray italic",children:"No printers configured"})]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Cost Tracking"})}),s.jsxs(Nt,{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:ve=>pt("default_filament_cost",parseFloat(ve.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:ve=>pt("currency",ve.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:ve=>pt("energy_cost_per_kwh",parseFloat(ve.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:ve=>pt("energy_tracking_mode",ve.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:"Prints Only"}),s.jsx("option",{value:"total",children:"Total Consumption"})]}),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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Ga,{className:"w-5 h-5 text-bambu-green"}),"File Manager"]})}),s.jsxs(Nt,{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:ve=>pt("library_archive_mode",ve.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:"Always create archive entry"}),s.jsx("option",{value:"never",children:"Never create archive entry"}),s.jsx("option",{value:"ask",children:"Ask each time"})]}),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:ve=>pt("library_disk_warning_gb",parseFloat(ve.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(pKe,{}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Updates"})}),s.jsxs(Nt,{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:"Check for updates"}),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:ve=>pt("check_updates",ve.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:"Check printer firmware"}),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:ve=>pt("check_printer_firmware",ve.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:"Current version"}),s.jsxs("p",{className:"text-sm text-bambu-gray",children:["v",Xn?.version||"..."]})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>In(),disabled:Ti,children:[Ti?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(gr,{className:"w-4 h-4"}),"Check now"]})]}),Bt?.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",Bt.latest_version]}),Bt.release_name&&Bt.release_name!==Bt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:Bt.release_name})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[Bt.release_notes&&s.jsx("button",{onClick:()=>ye(!0),className:"text-bambu-gray hover:text-white transition-colors text-sm underline",children:"Release Notes"}),Bt.release_url&&s.jsx("a",{href:Bt.release_url,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-gray hover:text-white transition-colors",title:"View release on GitHub",children:s.jsx(Ur,{className:"w-4 h-4"})})]})]}),_r?.status==="downloading"||_r?.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(ut,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{children:_r.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:`${_r.progress}%`}})})]}):_r?.status==="complete"?s.jsx("div",{className:"mt-3 p-2 bg-bambu-green/20 rounded text-sm text-bambu-green",children:_r.message}):_r?.status==="error"?s.jsx("div",{className:"mt-3 p-2 bg-red-500/20 rounded text-sm text-red-400",children:_r.error||_r.message}):Bt?.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(Me,{className:"mt-3",onClick:()=>at.mutate(),disabled:at.isPending,children:[at.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx($r,{className:"w-4 h-4"}),"Install Update"]})]}):Bt?.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: ",Bt.error]}):Bt&&!Bt.update_available?s.jsx("p",{className:"mt-2 text-sm text-bambu-gray",children:"You're running the latest version"}):null]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"Data Management"})}),s.jsxs(Nt,{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:"Clear Notification Logs"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Delete notification logs older than 30 days"})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>Re(!0),children:[s.jsx(ln,{className:"w-4 h-4"}),"Clear"]})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Reset UI Preferences"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Reset sidebar order, theme, view modes, and layout preferences. Printers, archives, and settings are not affected."})]}),s.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>B(!0),children:[s.jsx(ln,{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(Me,{variant:"secondary",size:"sm",onClick:()=>ue("backup"),children:[s.jsx(Qc,{className:"w-4 h-4"}),"Go to Backup"]})]})]})]})]})]}),de==="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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(jd,{className:"w-5 h-5 text-blue-400"}),"External URL"]})}),s.jsxs(Nt,{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:ve=>pt("external_url",ve.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(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(gr,{className:"w-5 h-5 text-blue-400"}),"FTP Retry"]})}),s.jsxs(Nt,{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:"Enable retry"}),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:ve=>pt("ftp_retry_enabled",ve.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:ve=>pt("ftp_retry_count",Math.min(10,Math.max(1,parseInt(ve.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:ve=>pt("ftp_retry_delay",Math.min(30,Math.max(1,parseInt(ve.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:ve=>pt("ftp_timeout",Math.min(120,Math.max(10,parseInt(ve.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(wt,{children:[s.jsx(Qn,{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(U2,{className:"w-5 h-5 text-bambu-green"}),"Home Assistant"]}),E.ha_enabled&&$e&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${$e.success?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${$e.success?"text-green-400":"text-red-400"}`,children:$e.success?"Connected":"Disconnected"})]})]})}),s.jsxs(Nt,{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, and input_boolean entities."}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-white",children:"Enable Home Assistant"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Control smart plugs via Home Assistant"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.ha_enabled??!1,onChange:ve=>pt("ha_enabled",ve.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:ve=>pt("ha_url",ve.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:ve=>pt("ha_token",ve.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(Me,{variant:"secondary",size:"sm",disabled:qe,onClick:async()=>{Xe(!0),Qe(null);try{const ve=await fe.testHAConnection(E.ha_url,E.ha_token);Qe(ve)}catch(ve){Qe({success:!1,message:null,error:ve instanceof Error?ve.message:"Unknown error"})}finally{Xe(!1)}},children:[qe?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Vp,{className:"w-4 h-4"}),"Test Connection"]})})]})]})]}),s.jsxs(wt,{children:[s.jsx(Qn,{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(Vp,{className:"w-5 h-5 text-blue-400"}),"MQTT Publishing"]}),We?.enabled&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2.5 h-2.5 rounded-full ${We.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:`text-sm ${We.connected?"text-green-400":"text-red-400"}`,children:We.connected?"Connected":"Disconnected"})]})]})}),s.jsxs(Nt,{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:"Enable MQTT"}),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:ve=>pt("mqtt_enabled",ve.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:ve=>pt("mqtt_broker",ve.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:ve=>pt("mqtt_port",Math.min(65535,Math.max(1,parseInt(ve.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:ve=>{const Et=ve.target.checked;pt("mqtt_use_tls",Et);const Be=E.mqtt_port??1883;Et&&Be===1883?pt("mqtt_port",8883):!Et&&Be===8883&&pt("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:"Use TLS"})]})]}),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:ve=>pt("mqtt_username",ve.target.value),placeholder:"Leave empty for anonymous",className:"w-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:ve=>pt("mqtt_password",ve.target.value),placeholder:"Leave empty for anonymous",className:"w-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:ve=>pt("mqtt_topic_prefix",ve.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."]})]}),We&&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 ${We.connected?"bg-green-400":"bg-red-400"}`}),s.jsx("span",{className:"text-bambu-gray",children:We.connected?s.jsxs(s.Fragment,{children:["Connected to ",s.jsxs("span",{className:"text-white",children:[We.broker,":",We.port]})]}):"Not connected"})]})})]})]})]})]}),s.jsx("div",{className:"flex-1 lg:max-w-md space-y-4",children:s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2",children:[s.jsx(Jj,{className:"w-5 h-5 text-orange-400"}),"Prometheus Metrics"]})}),s.jsxs(Nt,{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:"Enable Metrics Endpoint"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Expose printer data in Prometheus format"})]}),s.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:E.prometheus_enabled??!1,onChange:ve=>pt("prometheus_enabled",ve.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:ve=>pt("prometheus_token",ve.target.value),placeholder:"Leave empty for no authentication",className:"w-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:"Available Metrics"}),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)"})]})]})]})]})]})})]}),$e&&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:[$e.success?s.jsx(Dn,{className:"w-8 h-8 text-green-400"}):s.jsx(ea,{className:"w-8 h-8 text-red-400"}),s.jsx("h3",{className:"text-lg font-medium text-white",children:$e.success?"Connection Successful":"Connection Failed"})]}),s.jsx("p",{className:"text-bambu-gray mb-6",children:$e.success?$e.message||"Successfully connected to Home Assistant.":$e.error||"Failed to connect to Home Assistant."}),s.jsx("div",{className:"flex justify-end",children:s.jsx(Me,{variant:"primary",onClick:()=>Qe(null),children:"OK"})})]})}),de==="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(Gs,{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:[Oe&&Oe.filter(ve=>ve.enabled).length>1&&s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>$("on"),disabled:Le.isPending,title:"Turn all plugs on",children:[Le.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(xu,{className:"w-4 h-4 text-bambu-green"}),"All On"]}),s.jsxs(Me,{variant:"secondary",size:"sm",className:"whitespace-nowrap",onClick:()=>$("off"),disabled:Le.isPending,title:"Turn all plugs off",children:[Le.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(H2,{className:"w-4 h-4 text-red-400"}),"All Off"]})]}),s.jsxs(Me,{className:"whitespace-nowrap",onClick:()=>{O(null),R(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Smart Plug"]})]})]}),Oe&&Oe.length>0&&s.jsxs(wt,{className:"mb-6",children:[s.jsx(Qn,{children:s.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[s.jsx(Vd,{className:"w-4 h-4 text-yellow-400"}),"Energy Summary",Je&&s.jsx(ut,{className:"w-4 h-4 animate-spin text-bambu-gray ml-2"})]})}),s.jsx(Nt,{children:je?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(Vd,{className:"w-3 h-3"}),"Current Power"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:[je.reachableCount,"/",je.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(ii,{className:"w-3 h-3"}),"Today"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:["~",(je.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(Jj,{className:"w-3 h-3"}),"Yesterday"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:["~",(je.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(Gj,{className:"w-3 h-3"}),"Total"]}),s.jsxs("div",{className:"text-xl font-bold text-white",children:[je.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:["~",(je.totalLifetime*E.energy_cost_per_kwh).toFixed(2)," ",E.currency]})]})]}):Je?null:s.jsx("p",{className:"text-sm text-bambu-gray",children:"Enable plugs to see energy summary"})})]}),Ue?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Oe&&Oe.length>0?s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Oe.map(ve=>s.jsx(tKe,{plug:ve,onEdit:Et=>{O(Et),R(!0)}},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(Gs,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:"No smart plugs configured"}),s.jsx("p",{className:"text-sm mb-4",children:"Add a Tasmota-based smart plug to track energy usage and automate power control."}),s.jsxs(Me,{onClick:()=>{O(null),R(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Your First Smart Plug"]})]})})})]}),de==="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(df,{className:"w-5 h-5 text-bambu-green"}),"Providers"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>ne(!0),children:[s.jsx(f0,{className:"w-4 h-4"}),"Log"]}),bt&&bt.length>0&&s.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>{he(null),xe.mutate()},disabled:xe.isPending,children:[xe.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(mD,{className:"w-4 h-4"}),"Test All"]}),s.jsxs(Me,{size:"sm",onClick:()=>{Y(null),j(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add"]})]})]}),s.jsx(wt,{className:"mb-4",children:s.jsx(Nt,{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:ve=>pt("notification_language",ve.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:JU.map(ve=>s.jsx("option",{value:ve.code,children:ve.nativeName},ve.code))})]})})}),At&&s.jsx(wt,{className:"mb-4",children:s.jsxs(Nt,{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:"Test Results"}),s.jsx("button",{onClick:()=>he(null),className:"text-bambu-gray hover:text-white text-xs",children:"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(Dn,{className:"w-4 h-4"}),At.success," passed"]}),At.failed>0&&s.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[s.jsx(ea,{className:"w-4 h-4"}),At.failed," failed"]})]}),At.results.filter(ve=>!ve.success).length>0&&s.jsx("div",{className:"space-y-1 mt-2 pt-2 border-t border-bambu-dark-tertiary",children:At.results.filter(ve=>!ve.success).map(ve=>s.jsxs("div",{className:"text-xs text-red-400",children:[s.jsxs("span",{className:"font-medium",children:[ve.provider_name,":"]})," ",ve.message]},ve.provider_id))})]})}),Tt?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):bt&&bt.length>0?s.jsx("div",{className:"space-y-3",children:bt.map(ve=>s.jsx(iKe,{provider:ve,onEdit:Et=>{Y(Et),j(!0)}},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(df,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm font-medium text-white mb-2",children:"No providers configured"}),s.jsx("p",{className:"text-xs mb-3",children:"Add a provider to receive alerts."}),s.jsxs(Me,{size:"sm",onClick:()=>{Y(null),j(!0)},children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Provider"]})]})})})]}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-lg font-semibold text-white flex items-center gap-2 mb-4",children:[s.jsx(Ga,{className:"w-5 h-5 text-bambu-green"}),"Message Templates"]}),s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Customize notification messages for each event."}),br?s.jsx("div",{className:"flex justify-center py-8",children:s.jsx(ut,{className:"w-6 h-6 text-bambu-green animate-spin"})}):zn&&zn.length>0?s.jsx("div",{className:"space-y-2",children:zn.map(ve=>s.jsx(wt,{className:"cursor-pointer hover:border-bambu-green/50 transition-colors",onClick:()=>Z(ve),children:s.jsx(Nt,{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:ve.name}),s.jsx("p",{className:"text-bambu-gray text-xs truncate mt-0.5",children:ve.title_template})]}),s.jsx("button",{className:"p-1.5 hover:bg-bambu-dark-tertiary rounded transition-colors shrink-0 ml-2",onClick:Et=>{Et.stopPropagation(),Z(ve)},children:s.jsx($2,{className:"w-4 h-4 text-bambu-gray"})})]})})},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-8",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(Ga,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),s.jsx("p",{className:"text-sm",children:"No templates available. Restart the backend to seed default templates."})]})})})]})]}),de==="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(ef,{className:"w-5 h-5 text-bambu-green"}),"API Keys"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Create API keys for external integrations and webhooks."})]}),s.jsxs(Me,{size:"sm",onClick:()=>pe(!0),className:"flex-shrink-0",children:[s.jsx(Jn,{className:"w-4 h-4"}),"Create Key"]})]}),V&&s.jsx(wt,{className:"mb-6 border-bambu-green",children:s.jsx(Nt,{className:"py-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(Dn,{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:"API Key Created Successfully"}),s.jsx("p",{className:"text-sm text-bambu-gray mb-2",children:"Copy this key now - it won't be shown again!"}),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:V}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:async()=>{try{if(navigator.clipboard&&navigator.clipboard.writeText)await navigator.clipboard.writeText(V);else{const ve=document.createElement("textarea");ve.value=V,ve.style.position="fixed",ve.style.left="-999999px",document.body.appendChild(ve),ve.select(),document.execCommand("copy"),document.body.removeChild(ve)}o("Key copied to clipboard")}catch{o("Failed to copy key","error")}},children:s.jsx(ll,{className:"w-4 h-4"})})]}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>{le(V),o("Key added to API Browser")},children:"Use in API Browser"}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>H(null),children:"Dismiss"})]})]})]})})}),Ae&&s.jsxs(wt,{className:"mb-6",children:[s.jsx(Qn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:"Create New API Key"})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Key Name"}),s.jsx("input",{type:"text",value:Ee,onChange:ve=>_e(ve.target.value),placeholder:"e.g., Home Assistant, OctoPrint",className:"w-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:"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:oe.can_read_status,onChange:ve=>ze(Et=>({...Et,can_read_status:ve.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:"Read Status"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"View printer status and queue"})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:oe.can_queue,onChange:ve=>ze(Et=>({...Et,can_queue:ve.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:"Manage Queue"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Add and remove items from print queue"})]})]}),s.jsxs("label",{className:"flex items-center gap-3 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:oe.can_control_printer,onChange:ve=>ze(Et=>({...Et,can_control_printer:ve.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:"Control Printer"}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Pause, resume, and stop prints"})]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[s.jsxs(Me,{onClick:()=>Lt.mutate({name:Ee||"Unnamed Key",...oe}),disabled:Lt.isPending,children:[Lt.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(Jn,{className:"w-4 h-4"}),"Create Key"]}),s.jsx(Me,{variant:"secondary",onClick:()=>pe(!1),children:"Cancel"})]})]})]}),sn?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):Dt&&Dt.length>0?s.jsx("div",{className:"space-y-3",children:Dt.map(ve=>s.jsx(wt,{children:s.jsx(Nt,{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(ef,{className:`w-5 h-5 ${ve.enabled?"text-bambu-green":"text-bambu-gray"}`}),s.jsxs("div",{children:[s.jsx("p",{className:"text-white font-medium",children:ve.name}),s.jsxs("p",{className:"text-xs text-bambu-gray",children:[ve.key_prefix,"••••••••",ve.last_used&&` · Last used: ${og(ve.last_used)}`]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:"flex gap-1 text-xs",children:[ve.can_read_status&&s.jsx("span",{className:"px-1.5 py-0.5 bg-blue-500/20 text-blue-400 rounded",children:"Read"}),ve.can_queue&&s.jsx("span",{className:"px-1.5 py-0.5 bg-green-500/20 text-green-400 rounded",children:"Queue"}),ve.can_control_printer&&s.jsx("span",{className:"px-1.5 py-0.5 bg-orange-500/20 text-orange-400 rounded",children:"Control"})]}),s.jsx(Me,{variant:"secondary",size:"sm",onClick:()=>U(ve.id),children:s.jsx(ln,{className:"w-4 h-4 text-red-400"})})]})]})})},ve.id))}):s.jsx(wt,{children:s.jsx(Nt,{className:"py-12",children:s.jsxs("div",{className:"text-center text-bambu-gray",children:[s.jsx(ef,{className:"w-16 h-16 mx-auto mb-4 opacity-30"}),s.jsx("p",{className:"text-lg font-medium text-white mb-2",children:"No API keys"}),s.jsx("p",{className:"text-sm mb-4",children:"Create an API key to integrate with external services."}),s.jsxs(Me,{onClick:()=>pe(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Create Your First Key"]})]})})}),s.jsxs(wt,{className:"mt-6",children:[s.jsx(Qn,{children:s.jsx("h3",{className:"text-base font-semibold text-white",children:"Webhook Endpoints"})}),s.jsxs(Nt,{className:"space-y-3 text-sm",children:[s.jsxs("p",{className:"text-bambu-gray",children:["Use your API key in the ",s.jsx("code",{className:"text-bambu-green",children:"X-API-Key"})," header."]}),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.jsx("span",{className:"text-bambu-gray",children:" - Get all printer status"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Get specific printer status"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Add to print queue"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Pause print"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Resume print"})]}),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.jsx("span",{className:"text-bambu-gray",children:" - Stop print"})]})]})]})]})]}),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(jd,{className:"w-5 h-5 text-bambu-green"}),"API Browser"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Explore and test all available API endpoints."})]}),s.jsx(wt,{className:"mb-4",children:s.jsxs(Nt,{className:"py-3",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:"API Key for Testing"}),s.jsx("input",{type:"text",value:Q,onChange:ve=>le(ve.target.value),placeholder:"Paste your API key here to test authenticated endpoints...",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.jsxs("p",{className:"text-xs text-bambu-gray mt-2",children:["This key will be sent as ",s.jsx("code",{className:"text-bambu-green",children:"X-API-Key"})," header with requests."]})]})}),s.jsx(NKe,{apiKey:Q})]})]}),de==="virtual-printer"&&s.jsx(gKe,{}),de==="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(wt,{children:[s.jsx(Qn,{children:s.jsx("h2",{className:"text-lg font-semibold text-white",children:"AMS Display Thresholds"})}),s.jsxs(Nt,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Configure color thresholds for AMS humidity and temperature indicators."}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-white",children:[s.jsx(uD,{className:"w-4 h-4 text-blue-400"}),s.jsx("span",{className:"font-medium",children:"Humidity"})]}),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:"Good (green) ≤"}),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:ve=>pt("ams_humidity_good",parseInt(ve.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.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Fair (orange) ≤"}),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:ve=>pt("ams_humidity_fair",parseInt(ve.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:"Above fair threshold shows as red (bad)"})]}),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(G2,{className:"w-4 h-4 text-orange-400"}),s.jsx("span",{className:"font-medium",children:"Temperature"})]}),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:"Good (blue) ≤"}),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:ve=>pt("ams_temp_good",parseFloat(ve.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.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Fair (orange) ≤"}),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:ve=>pt("ams_temp_fair",parseFloat(ve.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:"Above fair threshold shows as red (hot)"})]}),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(Qc,{className:"w-4 h-4 text-purple-400"}),s.jsx("span",{className:"font-medium",children:"History Retention"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Keep sensor history for"}),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:ve=>pt("ams_history_retention_days",parseInt(ve.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:"days"})]})]}),s.jsx("p",{className:"text-xs text-bambu-gray",children:"Older humidity and temperature data will be automatically deleted"})]}),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(qr,{className:"w-4 h-4 text-bambu-green"}),s.jsx("span",{className:"font-medium",children:"Print Modal"})]}),s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-white",children:"Expand custom mapping by default"}),s.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:"When printing to multiple printers, show per-printer AMS mapping expanded"})]}),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:ve=>pt("per_printer_mapping_expanded",ve.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(fKe,{})})]}),K!==null&&s.jsx(Fn,{title:"Delete API Key",message:"Are you sure you want to delete this API key? Any integrations using this key will stop working.",confirmText:"Delete Key",variant:"danger",onConfirm:()=>{gn.mutate(K),U(null)},onCancel:()=>U(null)}),k&&s.jsx(nKe,{plug:F,onClose:()=>{R(!1),O(null)}}),X&&s.jsx(aKe,{provider:q,onClose:()=>{j(!1),Y(null)}}),W&&s.jsx(sKe,{template:W,onClose:()=>Z(null)}),ee&&s.jsx(cKe,{onClose:()=>ne(!1)}),ke&&s.jsx(Fn,{title:"Clear Notification Logs",message:"This will permanently delete all notification logs older than 30 days. This action cannot be undone.",confirmText:"Clear Logs",variant:"warning",onConfirm:async()=>{Re(!1);try{const ve=await fe.clearNotificationLogs(30);o(ve.message,"success")}catch{o("Failed to clear logs","error")}},onCancel:()=>Re(!1)}),Ce&&s.jsx(Fn,{title:"Reset UI Preferences",message:"This will reset all UI preferences to defaults: sidebar order, theme, dashboard layout, view modes, and sorting preferences. Your printers, archives, and server settings will NOT be affected. The page will reload after clearing.",confirmText:"Reset Preferences",variant:"default",onConfirm:()=>{B(!1),localStorage.clear(),o("UI preferences reset. Refreshing...","success"),setTimeout(()=>window.location.reload(),1e3)},onCancel:()=>B(!1)}),I&&s.jsx(Fn,{title:`Turn All Plugs ${I==="on"?"On":"Off"}`,message:`This will turn ${I==="on"?"ON":"OFF"} all ${Oe?.filter(ve=>ve.enabled).length||0} enabled smart plugs. ${I==="off"?"Any running printers may be affected!":""}`,confirmText:`Turn All ${I==="on"?"On":"Off"}`,variant:I==="off"?"danger":"warning",onConfirm:()=>{const ve=I;$(null),Le.mutate(ve)},onCancel:()=>$(null)}),te&&Bt?.release_notes&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:()=>ye(!1),children:s.jsxs(wt,{className:"w-full max-w-2xl max-h-[80vh] flex flex-col",onClick:ve=>ve.stopPropagation(),children:[s.jsxs(Qn,{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",Bt.latest_version]}),Bt.release_name&&Bt.release_name!==Bt.latest_version&&s.jsx("p",{className:"text-sm text-bambu-gray",children:Bt.release_name})]}),s.jsx("button",{onClick:()=>ye(!1),className:"p-1 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:s.jsx(Ut,{className:"w-5 h-5"})})]}),s.jsx(Nt,{className:"overflow-y-auto flex-1",children:s.jsx("pre",{className:"text-sm text-bambu-gray whitespace-pre-wrap font-sans",children:Bt.release_notes})}),s.jsxs("div",{className:"p-4 border-t border-bambu-dark-tertiary shrink-0 flex gap-2",children:[Bt.release_url&&s.jsx("a",{href:Bt.release_url,target:"_blank",rel:"noopener noreferrer",className:"flex-1",children:s.jsxs(Me,{variant:"secondary",className:"w-full",children:[s.jsx(Ur,{className:"w-4 h-4"}),"View on GitHub"]})}),s.jsx(Me,{onClick:()=>ye(!1),className:"flex-1",children:"Close"})]})]})}),de==="users"&&s.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-8",children:[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(tf,{className:"w-5 h-5 text-bambu-green"}),"User Authentication"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Enable authentication to secure your Bambuddy instance and manage user access."})]}),s.jsx(wt,{children:s.jsx(Nt,{className:"py-6",children:l?s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"w-12 h-12 rounded-full flex items-center justify-center bg-green-500/20",children:s.jsx(LT,{className:"w-6 h-6 text-green-400"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-white font-medium",children:"Authentication Enabled"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Your Bambuddy instance is secured with authentication."})]})]}),c&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-bambu-gray",children:"Current User"}),s.jsx("p",{className:"text-white font-medium",children:c.username}),s.jsxs("p",{className:"text-xs text-bambu-gray mt-1",children:["Role: ",s.jsx("span",{className:"capitalize",children:c.role})]})]}),s.jsx("div",{className:`px-3 py-1 rounded-full text-xs font-medium ${c.role==="admin"?"bg-purple-500/20 text-purple-300":"bg-blue-500/20 text-blue-300"}`,children:c.role==="admin"?"Admin":"User"})]})}),s.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary space-y-3",children:[s.jsxs(Me,{onClick:()=>e("/users"),className:"w-full",variant:"secondary",children:[s.jsx(tf,{className:"w-4 h-4"}),"Manage Users"]}),c?.role==="admin"&&s.jsxs(Me,{onClick:()=>Ye(!0),className:"w-full",variant:"secondary",children:[s.jsx(bz,{className:"w-4 h-4"}),"Disable Authentication"]})]})]}):s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:`w-12 h-12 rounded-full flex items-center justify-center ${l?"bg-green-500/20":"bg-gray-500/20"}`,children:l?s.jsx(LT,{className:"w-6 h-6 text-green-400"}):s.jsx(bz,{className:"w-6 h-6 text-gray-400"})}),s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-white font-medium",children:"Authentication Disabled"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"Your Bambuddy instance is currently accessible without authentication."})]})]}),s.jsxs("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:[s.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Enable authentication to:"}),s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray mb-4",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Require login to access the system"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage multiple users with different roles"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Control access to printer settings and user management"})]})]}),s.jsxs(Me,{type:"button",onClick:ve=>{ve.preventDefault(),e("/setup")},className:"w-full",children:[s.jsx(LT,{className:"w-4 h-4"}),"Activate Authentication"]})]})]})})})]}),l&&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(Zj,{className:"w-5 h-5 text-bambu-green"}),"Role Permissions"]}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Overview of what each role can do."})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-purple-500/20 flex items-center justify-center",children:s.jsx(Zj,{className:"w-4 h-4 text-purple-300"})}),s.jsx("h3",{className:"text-white font-medium",children:"Admin"})]})}),s.jsx(Nt,{children:s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage printer settings"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Create, edit, and delete users"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Access all system features"})]})]})})]}),s.jsxs(wt,{children:[s.jsx(Qn,{children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-blue-500/20 flex items-center justify-center",children:s.jsx(tf,{className:"w-4 h-4 text-blue-300"})}),s.jsx("h3",{className:"text-white font-medium",children:"User"})]})}),s.jsx(Nt,{children:s.jsxs("ul",{className:"space-y-2 text-sm text-bambu-gray",children:[s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Send print jobs"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage files and archives"})]}),s.jsxs("li",{className:"flex items-start gap-2",children:[s.jsx(Dn,{className:"w-4 h-4 text-bambu-green mt-0.5 flex-shrink-0"}),s.jsx("span",{children:"Manage filament"})]})]})})]})]})]})]}),de==="backup"&&s.jsx(vKe,{}),be&&s.jsx(Fn,{title:"Disable Authentication",message:"Are you sure you want to disable authentication? This will make your Bambuddy instance accessible without login. All users will remain in the database but authentication will be disabled.",confirmText:"Disable Authentication",variant:"danger",onConfirm:async()=>{try{await fe.disableAuth(),o("Authentication disabled successfully","success"),await u(),Ye(!1),window.location.href="/"}catch(ve){const Et=ve instanceof Error?ve.message:"Failed to disable authentication";o(Et,"error")}},onCancel:()=>Ye(!1)})]})}const Nre=t=>{const e=parseFloat(t);return(Math.trunc(e*1e3)/1e3).toFixed(3)},TKe=t=>t.startsWith("HH")?"HF":"S",AKe=t=>{const e=t.match(/^([A-Z]{2}\d{2})/);return e?e[1]:"HH00"},GR=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 wj({profile:t,onEdit:e,onCopy:n,selectionMode:r,isSelected:i,onToggleSelect:a,note:o}){const l=TKe(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(Ro,{className:"w-4 h-4 text-bambu-green"}):s.jsx(Do,{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:Nre(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(mW,{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(ll,{className:"w-4 h-4"})})]})}function Sj({profile:t,printerId:e,nozzleDiameter:n,existingProfiles:r=[],isDualNozzle:i=!1,initialNote:a="",initialNoteKey:o=null,onClose:l,onSave:c,onSaveNote:u}){const{showToast:d}=Hn(),[f,m]=w.useState(t?.name||""),[g,x]=w.useState(t?.k_value?Nre(t.k_value):"0.020"),[y,b]=w.useState(t?.filament_id||""),[v,N]=w.useState(t?.nozzle_id?AKe(t.nozzle_id):"HH00"),[S,A]=w.useState(t?.nozzle_diameter||n),[T,C]=w.useState(t?[t.extruder_id]:i?[0,1]:[0]),[E,D]=w.useState(!1),[k,R]=w.useState({current:0,total:0}),[F,O]=w.useState(a),X=Fr.useMemo(()=>{const ne=new Map;for(const z of r)if(z.filament_id&&!ne.has(z.filament_id)){const G=GR(z.name||"");ne.set(z.filament_id,{id:z.filament_id,name:G||z.filament_id})}return Array.from(ne.values()).sort((z,G)=>z.name.localeCompare(G.name))},[r]),j=ht({mutationFn:ne=>(console.log("[KProfile] Calling API..."),fe.setKProfile(e,ne)),onSuccess:ne=>{if(console.log("[KProfile] Save success:",ne),d("K-profile saved"),u&&F!==a){let z;F===""&&o?z=o:t&&t.slot_id>0?z=t.setting_id||`slot_${t.slot_id}_${t.filament_id}_${t.extruder_id}`:z=`name_${f}_${y}`,u(z,F)}D(!0),setTimeout(()=>{D(!1),c()},2500)},onError:ne=>{console.error("[KProfile] Save error:",ne),d(ne.message,"error"),D(!1)}}),q=ht({mutationFn:ne=>(console.log("[KProfile] Deleting profile..."),fe.deleteKProfile(e,ne)),onSuccess:ne=>{console.log("[KProfile] Delete success:",ne),d("K-profile deleted"),D(!0),setTimeout(()=>{D(!1),l()},4e3)},onError:ne=>{console.error("[KProfile] Delete error:",ne),d(ne.message,"error"),D(!1)}}),[Y,W]=w.useState(!1),Z=()=>{t&&q.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})},ee=async ne=>{if(ne.preventDefault(),i&&!t&&T.length===0){d("Please select at least one extruder","error");return}const z=parseFloat(g).toFixed(6),G=`${v}-${S}`;if(t||T.length===1){const se={name:f,k_value:z,filament_id:y,nozzle_id:G,nozzle_diameter:S,extruder_id:t?t.extruder_id:T[0],setting_id:t?.setting_id,slot_id:t?.slot_id??0};console.log("[KProfile] Saving profile:",se),j.mutate(se);return}D(!0),R({current:1,total:T.length});const ae=T.map(se=>({name:f,k_value:z,filament_id:y,nozzle_id:G,nozzle_diameter:S,extruder_id:se,setting_id:void 0,slot_id:0}));console.log(`[KProfile] Saving ${ae.length} profiles in batch:`,ae);try{if(await fe.setKProfilesBatch(e,ae),d(`K-profile saved to ${T.length} extruders`),u&&F){const se=`name_${f}_${y}`;u(se,F)}}catch(se){console.error("[KProfile] Failed to save batch:",se),d("Failed to save K-profiles","error"),D(!1),R({current:0,total:0});return}R({current:T.length,total:T.length}),setTimeout(()=>{D(!1),R({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(wt,{className:"w-full max-w-md relative",children:[E&&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(ut,{className:"w-8 h-8 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:k.total>1?`Saving to extruder ${k.current}/${k.total}...`:"Syncing with printer..."}),s.jsx("p",{className:"text-bambu-gray text-sm mt-1",children:"Please wait"})]}),s.jsxs(Nt,{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:t?"Edit K-Profile":"Add K-Profile"}),s.jsx("button",{onClick:l,className:"text-bambu-gray hover:text-white transition-colors",disabled:E,children:s.jsx(Ut,{className:"w-5 h-5"})})]}),s.jsxs("form",{onSubmit:ee,className:"p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Profile Name"}),s.jsx("input",{type:"text",value:f,onChange:ne=>m(ne.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,placeholder:"My PLA Profile",required:!t})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"K-Value"}),s.jsx("input",{type:"text",inputMode:"decimal",value:g,onChange:ne=>{const z=ne.target.value;(z===""||/^\d*\.?\d*$/.test(z))&&x(z)},onBlur:ne=>{const z=parseFloat(ne.target.value);isNaN(z)||x((Math.trunc(z*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:"0.020",required:!0}),s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"Typical range: 0.01 - 0.06 for PLA, 0.02 - 0.10 for PETG"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Filament"}),s.jsxs("select",{value:y,onChange:ne=>{const z=ne.target.value;if(b(z),!t&&z&&!f){const G=X.find(ae=>ae.id===z);G&&m(`${v==="HH00"?"HF":"S"} ${G.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:"Select filament..."}),t?.filament_id&&s.jsx("option",{value:t.filament_id,children:X.find(ne=>ne.id===t.filament_id)?.name||t.filament_id},t.filament_id),!t&&X.map(ne=>s.jsx("option",{value:ne.id,children:ne.name},ne.id))]}),!t&&X.length===0&&s.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:"No filaments found. Create a K-profile in Bambu Studio first."})]}),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:"Flow Type"}),s.jsxs("select",{value:v,onChange:ne=>{const z=ne.target.value;if(N(z),!t&&y&&!f){const G=X.find(ae=>ae.id===y);G&&m(`${z==="HS00"?"HF":"S"} ${G.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:"High Flow"}),s.jsx("option",{value:"HS00",children:"Standard"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Nozzle Size"}),s.jsxs("select",{value:S,onChange:ne=>A(ne.target.value),disabled:!!t,className:`w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none ${t?"opacity-60 cursor-not-allowed":""}`,children:[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:t?"Extruder":"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?"Left":"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:T.includes(1),onChange:ne=>{ne.target.checked?C([...T,1]):C(T.filter(z=>z!==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:"Left"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:T.includes(0),onChange:ne=>{ne.target.checked?C([...T,0]):C(T.filter(z=>z!==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:"Right"})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Notes (stored locally)"}),s.jsx("textarea",{value:F,onChange:ne=>O(ne.target.value),placeholder:"Add notes about this profile...",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:"Notes are saved in Bambuddy, not on the printer"})]}),s.jsxs("div",{className:"flex gap-2 pt-4",children:[t&&s.jsx(Me,{type:"button",variant:"secondary",onClick:()=>W(!0),disabled:q.isPending||E,className:"text-red-500 hover:bg-red-500/10",children:q.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"})}),s.jsx(Me,{type:"button",variant:"secondary",onClick:l,disabled:E,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{type:"submit",disabled:j.isPending||E,className:"flex-1",children:[j.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(I2,{className:"w-4 h-4"}),"Save"]})]})]})]})]}),Y&&s.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-[60]",children:s.jsx(wt,{className:"w-full max-w-sm",children:s.jsxs(Nt,{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(ln,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:"Delete Profile"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"This cannot be undone"})]})]}),s.jsxs("p",{className:"text-bambu-gray mb-6",children:["Are you sure you want to delete ",s.jsxs("span",{className:"text-white font-medium",children:['"',t?.name,'"']})," from the printer?"]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Me,{variant:"secondary",onClick:()=>W(!1),className:"flex-1",children:"Cancel"}),s.jsxs(Me,{onClick:()=>{W(!1),Z()},disabled:q.isPending,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[q.isPending?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"}),"Delete"]})]})]})})})]})}const I1={NOZZLE_DIAMETER:"bambusy_kprofiles_nozzle",SORT_OPTION:"bambusy_kprofiles_sort"};function CKe(){const{showToast:t}=Hn(),[e,n]=w.useState(null),[r,i]=w.useState(()=>localStorage.getItem(I1.NOZZLE_DIAMETER)||"0.4"),[a,o]=w.useState(null),[l,c]=w.useState(!1),[u,d]=w.useState(null),[f,m]=w.useState(""),[g,x]=w.useState("all"),[y,b]=w.useState("all"),[v,N]=w.useState(()=>localStorage.getItem(I1.SORT_OPTION)||"name"),[S,A]=w.useState(!1),[T,C]=w.useState(new Set),[E,D]=w.useState(!1),[k,R]=w.useState(!1),F=w.useCallback(U=>`${U.slot_id}_${U.extruder_id}`,[]);w.useEffect(()=>{localStorage.setItem(I1.NOZZLE_DIAMETER,r)},[r]),w.useEffect(()=>{localStorage.setItem(I1.SORT_OPTION,v)},[v]);const{data:O,isLoading:X}=ct({queryKey:["printers"],queryFn:fe.getPrinters}),{data:j,isLoading:q,isFetching:Y,error:W,refetch:Z}=ct({queryKey:["kprofiles",e,r],queryFn:async()=>{console.log("[KProfiles] Fetching profiles for printer",e,"nozzle",r);const U=await fe.getKProfiles(e,r);return console.log("[KProfiles] Received profiles:",U?.profiles?.length||0,"profiles"),U},enabled:!!e,retry:!1,staleTime:0,gcTime:0,refetchOnMount:"always"}),{data:ee}=ct({queryKey:["kprofiles",e,"0.4"],queryFn:()=>fe.getKProfiles(e,"0.4"),enabled:!!e,staleTime:6e4}),{data:ne,refetch:z}=ct({queryKey:["kprofile-notes",e],queryFn:()=>fe.getKProfileNotes(e),enabled:!!e,staleTime:3e4}),G=W?.message?.includes("not connected");w.useEffect(()=>{if(!e&&O&&O.length>0){const U=O.find(Q=>Q.is_active);U&&n(U.id)}},[e,O]),w.useEffect(()=>{if(e){const U=setTimeout(()=>{Z()},150);return()=>clearTimeout(U)}},[e,r]);const ae=O?.filter(U=>U.is_active)||[],se=Fr.useMemo(()=>j?.profiles?j.profiles.filter(Q=>{const le=f.toLowerCase(),ke=!le||Q.name.toLowerCase().includes(le)||Q.filament_id.toLowerCase().includes(le),Re=g==="all"||g==="left"&&Q.extruder_id===1||g==="right"&&Q.extruder_id===0,Ce=y==="all"||y==="hf"&&Q.nozzle_id.startsWith("HH")||y==="s"&&Q.nozzle_id.startsWith("HS");return ke&&Re&&Ce}).sort((Q,le)=>{switch(v){case"k_value":return parseFloat(Q.k_value)-parseFloat(le.k_value);case"filament":return GR(Q.name).localeCompare(GR(le.name));case"name":default:return Q.name.localeCompare(le.name)}}):[],[j?.profiles,f,g,y,v]),de=O?.find(U=>U.id===e),me=de?.nozzle_count===2;w.useEffect(()=>{const U=Q=>{Q.target instanceof HTMLInputElement||Q.target instanceof HTMLTextAreaElement||Q.target instanceof HTMLSelectElement||a||l||u||(Q.key==="r"||Q.key==="R"?(Q.preventDefault(),Z()):Q.key==="n"||Q.key==="N"?(Q.preventDefault(),c(!0)):Q.key==="Escape"&&S&&(Q.preventDefault(),A(!1),C(new Set)))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[a,l,u,S,Z]);const ue=w.useCallback(()=>{if(!j?.profiles||j.profiles.length===0){t("No profiles to export","error");return}const U={version:1,exported_at:new Date().toISOString(),printer:de?.name||"Unknown",nozzle_diameter:r,profiles:j.profiles.map(Re=>({name:Re.name,k_value:Re.k_value,filament_id:Re.filament_id,nozzle_id:Re.nozzle_id,nozzle_diameter:Re.nozzle_diameter,extruder_id:Re.extruder_id}))},Q=new Blob([JSON.stringify(U,null,2)],{type:"application/json"}),le=URL.createObjectURL(Q),ke=document.createElement("a");ke.href=le,ke.download=`kprofiles_${de?.name||"printer"}_${r}mm_${new Date().toISOString().split("T")[0]}.json`,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke),URL.revokeObjectURL(le),t(`Exported ${j.profiles.length} profiles`)},[j?.profiles,de,r,t]),Ae=w.useCallback(()=>{const U=document.createElement("input");U.type="file",U.accept=".json",U.onchange=async Q=>{const le=Q.target.files?.[0];if(le)try{const ke=await le.text(),Re=JSON.parse(ke);if(!Re.profiles||!Array.isArray(Re.profiles)){t("Invalid file format","error");return}let Ce=0;for(const B of Re.profiles)if(!(!B.name||!B.k_value||!B.filament_id))try{await fe.setKProfile(e,{name:B.name,k_value:parseFloat(B.k_value).toFixed(6),filament_id:B.filament_id,nozzle_id:B.nozzle_id||`HH00-${r}`,nozzle_diameter:B.nozzle_diameter||r,extruder_id:B.extruder_id??0,slot_id:0}),Ce++,await new Promise(I=>setTimeout(I,500))}catch(I){console.error("Failed to import profile:",B.name,I)}t(`Imported ${Ce} of ${Re.profiles.length} profiles`),Z()}catch(ke){console.error("Import error:",ke),t("Failed to parse import file","error")}},U.click()},[e,r,t,Z]),pe=w.useCallback(U=>{C(Q=>{const le=new Set(Q);return le.has(U)?le.delete(U):le.add(U),le})},[]),Ee=w.useCallback(()=>{C(new Set(se.map(U=>F(U))))},[se,F]),_e=w.useCallback(()=>{T.size!==0&&D(!0)},[T.size]),oe=w.useCallback(async()=>{const U=se.filter(le=>T.has(F(le)));R(!0);let Q=0;for(const le of U)try{await fe.deleteKProfile(e,{slot_id:le.slot_id,extruder_id:le.extruder_id,nozzle_id:le.nozzle_id,nozzle_diameter:le.nozzle_diameter,filament_id:le.filament_id,setting_id:le.setting_id}),Q++,await new Promise(ke=>setTimeout(ke,300))}catch(ke){console.error("Failed to delete profile:",le.name,ke)}t(`Deleted ${Q} profiles`),R(!1),D(!1),A(!1),C(new Set),Z()},[e,T,se,t,Z,F]),ze=w.useCallback(U=>{const Q=[];return U.setting_id&&Q.push(U.setting_id),Q.push(`slot_${U.slot_id}_${U.filament_id}_${U.extruder_id}`),Q.push(`name_${U.name}_${U.filament_id}`),Q},[]),V=w.useCallback(async(U,Q)=>{if(e)try{await fe.setKProfileNote(e,U,Q),z()}catch(le){console.error("Failed to save note:",le),t("Failed to save note","error")}},[e,z,t]),H=w.useCallback(U=>{if(!ne?.notes)return{note:"",key:null};const Q=ze(U);for(const le of Q)if(ne.notes[le])return{note:ne.notes[le],key:le};return{note:"",key:null}},[ne,ze]),K=w.useCallback(U=>H(U).note,[H]);return X?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):!O||O.length===0?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(ra,{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:"No Printers Configured"}),s.jsx("p",{className:"text-bambu-gray",children:"Add a printer in Settings to manage K-profiles"})]})}):ae.length===0?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(qr,{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:"No Active Printers"}),s.jsx("p",{className:"text-bambu-gray",children:"Enable a printer connection to view its K-profiles"})]})}):s.jsxs(s.Fragment,{children:[Y&&!q&&s.jsxs("div",{className:"fixed inset-0 bg-black/50 flex flex-col items-center justify-center z-40",children:[s.jsx(ut,{className:"w-10 h-10 text-bambu-green animate-spin mb-3"}),s.jsx("p",{className:"text-white font-medium",children:"Loading K-Profiles..."})]}),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:"Printer"}),s.jsx("select",{value:e||"",onChange:U=>n(parseInt(U.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:ae.map(U=>s.jsx("option",{value:U.id,children:U.name},U.id))})]}),s.jsxs("div",{className:"w-32",children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Nozzle"}),s.jsxs("select",{value:r,onChange:U=>i(U.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(Me,{variant:"secondary",onClick:()=>Z(),disabled:Y,children:[s.jsx(gr,{className:`w-4 h-4 ${Y?"animate-spin":""}`}),"Refresh"]}),s.jsxs(Me,{onClick:()=>c(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Add Profile"]})]})]}),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(_a,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),s.jsx("input",{type:"text",value:f,onChange:U=>m(U.target.value),placeholder:"Search by name or filament...",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"})]}),me&&s.jsx("div",{className:"w-36",children:s.jsxs("select",{value:g,onChange:U=>x(U.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:"All Extruders"}),s.jsx("option",{value:"left",children:"Left Only"}),s.jsx("option",{value:"right",children:"Right Only"})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:y,onChange:U=>b(U.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:"All Flow"}),s.jsx("option",{value:"hf",children:"HF Only"}),s.jsx("option",{value:"s",children:"S Only"})]})}),s.jsx("div",{className:"w-32",children:s.jsxs("select",{value:v,onChange:U=>N(U.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:"Sort: Name"}),s.jsx("option",{value:"k_value",children:"Sort: K-Value"}),s.jsx("option",{value:"filament",children:"Sort: Filament"})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[s.jsxs(Me,{variant:"secondary",onClick:ue,disabled:!j?.profiles?.length,title:"Export profiles to JSON",children:[s.jsx($r,{className:"w-4 h-4"}),"Export"]}),s.jsxs(Me,{variant:"secondary",onClick:Ae,title:"Import profiles from JSON",children:[s.jsx(di,{className:"w-4 h-4"}),"Import"]}),s.jsx("div",{className:"flex-1"}),S?s.jsxs(s.Fragment,{children:[s.jsxs(Me,{variant:"secondary",onClick:Ee,title:"Select all visible profiles",children:[s.jsx(Ro,{className:"w-4 h-4"}),"Select All"]}),s.jsxs(Me,{variant:"secondary",onClick:_e,disabled:T.size===0,className:"text-red-500 hover:bg-red-500/10",title:`Delete ${T.size} selected profiles`,children:[s.jsx(ln,{className:"w-4 h-4"}),"Delete (",T.size,")"]}),s.jsxs(Me,{variant:"secondary",onClick:()=>{A(!1),C(new Set)},children:[s.jsx(Ut,{className:"w-4 h-4"}),"Cancel"]})]}):s.jsxs(Me,{variant:"secondary",onClick:()=>A(!0),disabled:!se.length,title:"Enter selection mode for bulk delete",children:[s.jsx(Ro,{className:"w-4 h-4"}),"Select"]})]}),q?s.jsx("div",{className:"flex justify-center py-12",children:s.jsx(ut,{className:"w-8 h-8 text-bambu-green animate-spin"})}):G?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(Pf,{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:"Printer Offline"}),s.jsx("p",{className:"text-bambu-gray mb-4",children:"The selected printer is not connected. Power it on to view K-profiles."}),s.jsxs(Me,{variant:"secondary",onClick:()=>Z(),children:[s.jsx(gr,{className:"w-4 h-4"}),"Retry"]})]})}):se.length>0?me?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:"Left Extruder"}),s.jsx("div",{className:"space-y-1",children:se.filter(U=>U.extruder_id===1).map(U=>s.jsx(wj,{profile:U,onEdit:()=>o(U),onCopy:()=>d(U),selectionMode:S,isSelected:T.has(F(U)),onToggleSelect:()=>pe(F(U)),note:K(U)},F(U)))})]}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-medium text-bambu-gray mb-2 px-1",children:"Right Extruder"}),s.jsx("div",{className:"space-y-1",children:se.filter(U=>U.extruder_id===0).map(U=>s.jsx(wj,{profile:U,onEdit:()=>o(U),onCopy:()=>d(U),selectionMode:S,isSelected:T.has(F(U)),onToggleSelect:()=>pe(F(U)),note:K(U)},F(U)))})]})]}):s.jsx("div",{className:"space-y-1",children:se.map(U=>s.jsx(wj,{profile:U,onEdit:()=>o(U),onCopy:()=>d(U),selectionMode:S,isSelected:T.has(F(U)),onToggleSelect:()=>pe(F(U)),note:K(U)},F(U)))}):f||g!=="all"||y!=="all"?s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(_a,{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:"No Matching Profiles"}),s.jsx("p",{className:"text-bambu-gray",children:"No profiles match your search criteria"})]})}):s.jsx(wt,{children:s.jsxs(Nt,{className:"py-12 text-center",children:[s.jsx(I2,{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:"No K-Profiles"}),s.jsxs("p",{className:"text-bambu-gray mb-4",children:["No pressure advance profiles found for ",r,"mm nozzle"]}),s.jsxs(Me,{onClick:()=>c(!0),children:[s.jsx(Jn,{className:"w-4 h-4"}),"Create First Profile"]})]})}),a&&e&&(()=>{const{note:U,key:Q}=H(a);return s.jsx(Sj,{profile:a,printerId:e,nozzleDiameter:r,existingProfiles:ee?.profiles||j?.profiles,isDualNozzle:me,initialNote:U,initialNoteKey:Q,onSaveNote:V,onClose:()=>{console.log("[KProfiles] Edit modal onClose - refetching profiles..."),o(null),Z()},onSave:()=>{o(null),Z()}})})(),l&&e&&s.jsx(Sj,{printerId:e,nozzleDiameter:r,existingProfiles:ee?.profiles||j?.profiles,isDualNozzle:me,onSaveNote:V,onClose:()=>{c(!1),Z()},onSave:()=>{c(!1),Z()}}),u&&e&&s.jsx(Sj,{printerId:e,nozzleDiameter:r,existingProfiles:ee?.profiles||j?.profiles,isDualNozzle:me,onSaveNote:V,profile:{...u,slot_id:0,name:`${u.name} (Copy)`},onClose:()=>{d(null),Z()},onSave:()=>{d(null),Z()}}),E&&s.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:s.jsx(wt,{className:"w-full max-w-sm",children:s.jsxs(Nt,{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(ln,{className:"w-5 h-5 text-red-500"})}),s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-semibold text-white",children:"Delete Profiles"}),s.jsx("p",{className:"text-sm text-bambu-gray",children:"This cannot be undone"})]})]}),s.jsxs("p",{className:"text-bambu-gray mb-6",children:["Are you sure you want to delete ",s.jsx("span",{className:"text-white font-medium",children:T.size})," selected profiles from the printer?"]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsx(Me,{variant:"secondary",onClick:()=>D(!1),disabled:k,className:"flex-1",children:"Cancel"}),s.jsxs(Me,{onClick:oe,disabled:k,className:"flex-1 bg-red-500 hover:bg-red-600 text-white",children:[k?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(ln,{className:"w-4 h-4"}),"Delete"]})]})]})})})]})}function HL(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 ny(t){return/^(P[FPM]US|PF\d|PP\d)/.test(t)}function kKe(t){const e=vi(t);if(!e)return"";const r=new Date().getTime()-e.getTime(),i=Math.floor(r/6e4),a=Math.floor(r/36e5),o=Math.floor(r/864e5);return i<1?"Just now":i<60?`${i}m ago`:a<24?`${a}h ago`:o<7?`${o}d ago`:e.toLocaleDateString()}function jKe({onSuccess:t}){const{showToast:e}=Hn(),[n,r]=w.useState("email"),[i,a]=w.useState(""),[o,l]=w.useState(""),[c,u]=w.useState(""),[d,f]=w.useState(""),[m,g]=w.useState("global"),x=ht({mutationFn:()=>fe.cloudLogin(i,o,m),onSuccess:S=>{S.success?(e("Logged in successfully"),t()):S.needs_verification?(e("Verification code sent to your email"),r("code")):e(S.message,"error")},onError:S=>e(S.message,"error")}),y=ht({mutationFn:()=>fe.cloudVerify(i,c),onSuccess:S=>{S.success?(e("Logged in successfully"),t()):e(S.message,"error")},onError:S=>e(S.message,"error")}),b=ht({mutationFn:()=>fe.cloudSetToken(d),onSuccess:()=>{e("Token set successfully"),t()},onError:S=>e(S.message,"error")}),v=S=>{S.preventDefault(),n==="email"?x.mutate():n==="code"?y.mutate():n==="token"&&b.mutate()},N=x.isPending||y.isPending||b.isPending;return s.jsx(wt,{className:"max-w-md mx-auto",children:s.jsxs(Nt,{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(R2,{className:"w-6 h-6 text-bambu-green"})}),s.jsx("h2",{className:"text-xl font-semibold text-white",children:"Connect to Bambu Cloud"}),s.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:"Sync your slicer presets across devices"})]}),s.jsxs("form",{onSubmit:v,className:"space-y-4",children:[n==="email"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Email"}),s.jsx("input",{type:"email",value:i,onChange:S=>a(S.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:"Password"}),s.jsx("input",{type:"password",value:o,onChange:S=>l(S.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:"Region"}),s.jsxs("select",{value:m,onChange:S=>g(S.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:"Global"}),s.jsx("option",{value:"china",children:"China"})]})]})]}),n==="code"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Verification Code"}),s.jsxs("p",{className:"text-xs text-bambu-gray mb-2",children:["Check your email (",i,") for a 6-digit code"]}),s.jsx("input",{type:"text",value:c,onChange:S=>u(S.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})]}),n==="token"&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Access Token"}),s.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:"Paste your Bambu Lab access token (from Bambu Studio)"}),s.jsx("textarea",{value:d,onChange:S=>f(S.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:[n==="code"&&s.jsx(Me,{type:"button",variant:"secondary",onClick:()=>r("email"),className:"flex-1",children:"Back"}),s.jsxs(Me,{type:"submit",disabled:N,className:"flex-1",children:[N?s.jsx(ut,{className:"w-4 h-4 animate-spin"}):s.jsx(yz,{className:"w-4 h-4"}),n==="email"?"Login":n==="code"?"Verify":"Set Token"]})]}),n==="email"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>r("token"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx(ef,{className:"w-4 h-4"}),"Use access token instead"]})}),n==="token"&&s.jsx("div",{className:"pt-4 border-t border-bambu-dark-tertiary",children:s.jsxs("button",{type:"button",onClick:()=>r("email"),className:"text-sm text-bambu-gray hover:text-white flex items-center gap-2 transition-colors",children:[s.jsx(yz,{className:"w-4 h-4"}),"Login with email instead"]})})]})]})})}function Tp({label:t,value:e,options:n,onChange:r}){const[i,a]=w.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(Pi,{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]=w.useState(!1);w.useEffect(()=>{const r=()=>{e(window.scrollY>300)};return window.addEventListener("scroll",r),()=>window.removeEventListener("scroll",r)},[]);const n=()=>{window.scrollTo({top:0,behavior:"smooth"})};return t?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 Nj({setting:t,onClick:e,onDuplicate:n,compareMode:r,isCompareSelected:i,compareIndex:a,compareDisabled:o}){const l=HL(t.name),c=ny(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&&c&&s.jsx("span",{className:"flex-shrink-0 w-1.5 h-1.5 rounded-full bg-bambu-green",title:"My preset (editable)"}),s.jsx("span",{className:"text-white text-sm truncate flex-1",title:t.name,children:t.name}),l.filamentType&&t.type==="filament"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:l.filamentType}),l.layerHeight&&t.type==="process"&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:l.layerHeight}),l.printer&&s.jsx("span",{className:"text-xs text-bambu-gray whitespace-nowrap",children:l.printer})]})}),s.jsx("button",{onClick:u=>{u.stopPropagation(),n()},className:"opacity-0 group-hover:opacity-100 text-bambu-gray hover:text-white transition-all p-1",title:"Duplicate",children:s.jsx(ll,{className:"w-4 h-4"})})]})}function qR(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 2295fda05..659bf3229 100644 --- a/static/index.html +++ b/static/index.html @@ -23,7 +23,7 @@ - +