From 4cce575bcc95e6c97142b081cf723bd89b487b43 Mon Sep 17 00:00:00 2001 From: maziggy Date: Mon, 25 May 2026 08:55:34 +0200 Subject: [PATCH] fix(stats): cancelled bucket icon now uses semantic warning token (orange) (#1390 follow-up) Reporter flagged that the new Cancelled row's Ban icon rendered colourless while Successful and Failed used green/red icons in the same widget. Switch the Cancelled icon to text-status-warning (amber-500) so all three rows now use semantic status tokens consistently, and the colour matches the orange Archives + notification badges already use for cancelled status. --- CHANGELOG.md | 2 +- frontend/src/pages/StatsPage.tsx | 2 +- static/assets/{index-BW850Rth.js => index-RpiIrueH.js} | 2 +- static/index.html | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename static/assets/{index-BW850Rth.js => index-RpiIrueH.js} (97%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c59bc56b..56ce1a7e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ All notable changes to Bambuddy will be documented in this file. - **Trivy DS-0026 (`Dockerfile.test` missing HEALTHCHECK): silenced via `HEALTHCHECK NONE`** — The test image runs `pytest` and exits; there is no long-running service to probe, so any HEALTHCHECK we added would be cargo-cult noise. `HEALTHCHECK NONE` is the documented Docker directive to explicitly opt out of any inherited healthcheck and is the way Trivy expects projects to signal "this image is not a service." Closes code-scanning alert #813. ### Fixed -- **Quick Stats: user-cancelled prints now have their own bucket and no longer drag down the Success Rate gauge (#1390 follow-up, reported by @IndividualGhost1905)** — Reporter saw `Total prints: 20 / Success: 18 / Failed: 1` and asked where the 20th print went; the breakdown only showed Successful + Failed, so a cancelled run silently inflated the total without appearing anywhere. The earlier #1390 round had committed a test that *locked in* the bug — `it('uses total_prints as denominator so cancelled/stopped events count')` asserted the gauge should divide by `total_prints`, which lumped user/queue-cancelled jobs in with quality outcomes and conflated user intent with printer performance. **Cause**: `PrintLogEntry.status` has six values in production (`completed`, `failed`, `aborted`, `stopped`, `cancelled`, `skipped`) but the Quick Stats endpoint in `api/routes/archives.py` only counted two — `completed` → Successful, `status == "failed"` → Failed — and used a raw `count(*)` for Total Prints, so the other four statuses ended up in Total without surfacing in any breakdown row. `aborted` was particularly silent: classified as a failure elsewhere in the codebase (`failure_analysis.py`, `main.py:430,1729`) but not counted toward `failed_prints` in stats. **Fix**: three-bucket classification across the whole stats surface, matching how the rest of the codebase already groups these statuses. Quick Stats now returns `successful_prints` (completed), `failed_prints` (failed + aborted — printer-detected quality failures), and a new `cancelled_prints` (stopped + cancelled + skipped — user/queue interruptions). The SuccessRateWidget gauge divides by `successful + failed` only, so cancelling a roll because you changed your mind doesn't ding the printer's success rate — a Cancelled row in the breakdown surfaces the count so it doesn't silently vanish from Total Prints. The Failure Analysis service applies the same denominator change (`failure_rate = failed / (successful + failed)`) to both the headline rate and the per-week trend, so a week with no failures but several cancellations no longer reads as a misleading 0/N. **Schema change is additive-safe**: `ArchiveStats.cancelled_prints` defaults to `0` so any historical fixture validating against the model still parses; the frontend type also defaults the display to `0` when the field is missing. **i18n**: new `stats.cancelled` key with real translations across all 9 locales (de/es/fr/it/ja/pt-BR/zh-CN/zh-TW) per [[feedback_translate_dont_fallback]]; parity script clean at 4994 leaves per locale. **Tests**: existing `it('uses total_prints as denominator …')` test inverted to assert the new behaviour (40 completed / 20 failed / 35 cancelled → gauge shows 67%, Cancelled row reads 35), `cancelled_prints: 0` added to the shared mock so the unchanged-display assertion (140/150 → 93%) still holds since `140 / (140 + 10) = 93.33%` rounds identically. 33 StatsPage tests + 6 backend stats/failure tests green; frontend build + backend ruff clean. +- **Quick Stats: user-cancelled prints now have their own bucket and no longer drag down the Success Rate gauge (#1390 follow-up, reported by @IndividualGhost1905)** — Reporter saw `Total prints: 20 / Success: 18 / Failed: 1` and asked where the 20th print went; the breakdown only showed Successful + Failed, so a cancelled run silently inflated the total without appearing anywhere. The earlier #1390 round had committed a test that *locked in* the bug — `it('uses total_prints as denominator so cancelled/stopped events count')` asserted the gauge should divide by `total_prints`, which lumped user/queue-cancelled jobs in with quality outcomes and conflated user intent with printer performance. **Cause**: `PrintLogEntry.status` has six values in production (`completed`, `failed`, `aborted`, `stopped`, `cancelled`, `skipped`) but the Quick Stats endpoint in `api/routes/archives.py` only counted two — `completed` → Successful, `status == "failed"` → Failed — and used a raw `count(*)` for Total Prints, so the other four statuses ended up in Total without surfacing in any breakdown row. `aborted` was particularly silent: classified as a failure elsewhere in the codebase (`failure_analysis.py`, `main.py:430,1729`) but not counted toward `failed_prints` in stats. **Fix**: three-bucket classification across the whole stats surface, matching how the rest of the codebase already groups these statuses. Quick Stats now returns `successful_prints` (completed), `failed_prints` (failed + aborted — printer-detected quality failures), and a new `cancelled_prints` (stopped + cancelled + skipped — user/queue interruptions). The SuccessRateWidget gauge divides by `successful + failed` only, so cancelling a roll because you changed your mind doesn't ding the printer's success rate — a Cancelled row in the breakdown surfaces the count so it doesn't silently vanish from Total Prints. The Failure Analysis service applies the same denominator change (`failure_rate = failed / (successful + failed)`) to both the headline rate and the per-week trend, so a week with no failures but several cancellations no longer reads as a misleading 0/N. **Schema change is additive-safe**: `ArchiveStats.cancelled_prints` defaults to `0` so any historical fixture validating against the model still parses; the frontend type also defaults the display to `0` when the field is missing. **i18n**: new `stats.cancelled` key with real translations across all 9 locales (de/es/fr/it/ja/pt-BR/zh-CN/zh-TW) per [[feedback_translate_dont_fallback]]; parity script clean at 4994 leaves per locale. **Tests**: existing `it('uses total_prints as denominator …')` test inverted to assert the new behaviour (40 completed / 20 failed / 35 cancelled → gauge shows 67%, Cancelled row reads 35), `cancelled_prints: 0` added to the shared mock so the unchanged-display assertion (140/150 → 93%) still holds since `140 / (140 + 10) = 93.33%` rounds identically. 33 StatsPage tests + 6 backend stats/failure tests green; frontend build + backend ruff clean. **Follow-up (cosmetic):** the new Cancelled row's Ban icon rendered in `text-bambu-gray` while the Successful and Failed icons used semantic `text-status-ok` / `text-status-error` tokens — reporter (@IndividualGhost1905) noted the asymmetry and asked for an orange to match what Archives + notification badges use for cancelled. Switched the Cancelled row to `text-status-warning` (amber-500, same token family as the other two rows), so all three icons are now semantic-token-driven and the new row matches the colour the user already associates with cancelled status elsewhere in the UI. - **Support bundle + bug-report submission now include the live diagnostic snapshot** — Three diagnostics (Connection Diagnostic per printer, Virtual Printer Setup Diagnostic per enabled VP, Log Health Scanner) have shipped on the System page and inline in the bug-report bubble since 6bc6a1d6 / e222a0ef / ed31b8f4, but the results were only ever shown to the *user* — never persisted into the downloadable support ZIP or the submitted GitHub issue. A report saying "looks broken in Bambuddy" arrived with no actionable signal beyond raw logs. **Fix**: new `services/diagnostic_snapshot.collect_diagnostic_snapshot` runs all three concurrently with an outer per-probe 15 s wall-clock cap (so a hung interface adds at most ~15 s to bundle generation regardless of fleet size — `asyncio.gather`, total ≈ max(per-cap) not sum). Fail-soft per probe: a crash inside one printer's check emits `{"printer_id": N, "error": "..."}` for that entry rather than nuking the whole snapshot — partial result beats a 500. Wired into `_collect_support_info()` so both flows (`POST /support/bundle` and `POST /bug-report/submit` via `support_info=...`) pick up the new `diagnostics` top-level key without their own changes. **Private-data sanitization** — the diagnostic schemas embed raw IPv4 in three places (`PrinterDiagnosticResult.ip_address`, network-mode check's `params.{printer_ip, host_ip}`, VP diagnostic's `params.bind_ip`), and the snapshot adds printer names. None of those should leak. The snapshot now runs a recursive sanitizer on the full result tree before returning: known DB-listed values (printer name, IP, serial, access code) get the same `[PRINTER]/[IP]/[SERIAL]/[ACCESS_CODE]` labels the log sanitizer already applies (via the shared `collect_sensitive_strings`), and an IPv4-regex fallback catches IPs the DB doesn't know about — most importantly the Bambuddy host IP returned by `_get_host_ip()` and any VP `bind_ip` the user picked at setup. Live-DB smoke test confirms zero raw IPv4 instances in the serialized snapshot output. **Progress indicators**: the bubble's "submitting" view and the System page's Download button now render a static four-line checklist showing what's running (printer connectivity → VP setup → log scan → submit/build ZIP) — communicates the longer wait honestly without faking server-side phase progress we can't actually track. **Tests**: 6 new in `test_diagnostic_snapshot.py` — empty-input shape stable, per-printer / per-VP result coverage, fail-soft on a single-probe crash, `timed_out` marker when a probe exceeds the per-probe cap (test patches the cap to 0.05 s), end-to-end IP sanitization across all five field shapes (top-level `ip_address`, `printer_ip`, `host_ip`, `bind_ip`, plus IPs embedded in log-health sample lines) with a final regex sweep over the JSON-serialized result asserting zero raw IPv4 escapes, concurrent execution proof (4 × 0.2 s probes complete in < 0.5 s, would be 0.8 s sequential). Existing 27 BugReportBubble + SystemInfoPage frontend tests still pass; 9-locale i18n parity check clean (4993 leaves per locale, 9 new keys added with real translations everywhere — no English fallback). Backend ruff clean. - **"Prefer Lowest Remaining Filament" now uses Bambuddy's inventory weight, not just the printer's RFID counter (#1508, reported by @kleinwareio)** — Reporter has an inventory spool cloned to slot 1 and the original (much further used) in slot 4 of the same P1S AMS, with the preference enabled, and the dispatch consistently picked slot 1 (the fresh clone) instead of slot 4 (the original they wanted to finish first). Root cause is the `prefer_lowest` sort in `_match_filaments_to_slots` (`print_scheduler.py`): the sort key reads `f.get("remain", -1)` straight out of `_build_loaded_filaments`, which sources it from MQTT AMS `tray.remain` — the printer firmware's own RFID-decremented value. Two problems with that signal: (a) it's only populated for Bambu RFID spools, so every non-RFID / 3rd-party / user-loaded tray reports `-1` and gets clamped to a sentinel — multiple non-RFID spools then tie in the sort and Python's stable sort collapses to AMS-slot insertion order, so slot 1 always wins; (b) even when set, it's the *printer's* counter, not Bambuddy's `label_weight - weight_used` (internal mode) or Spoolman's `remaining_weight` (Spoolman mode) — the two diverge any time the user re-spools, swaps cardboard, or runs a print outside Bambuddy. The reporter is on internal-inventory mode with non-RFID spools — both failure modes apply, hence slot 1 every time. **Fix**: when a slot is bound to a Bambuddy / Spoolman spool, that inventory record's remaining weight becomes the sort signal. New async helper `_build_inventory_remain_overrides(db, printer_id, loaded)` returns `{global_tray_id: remaining_grams}` for slots with an assignment — internal mode joins `SpoolAssignment` → `Spool` once per dispatch, Spoolman mode joins `SpoolmanSlotAssignment` then fetches each spool through the existing `_spoolman_remaining_grams` (shared with `filament_deficit.py`, parity rule per [[feedback_inventory_modes_parity]]). The new `_prefer_lowest_sort_key` consumes that map alongside the legacy MQTT field with a **two-tier** comparison: inventory-tracked spools always sort BEFORE MQTT-only spools, then ascending by remaining within each tier, then ascending by `ams_id * 4 + tray_id` as the deterministic slot tie-breaker. The tier flag dominates so we never compare grams (inventory) against percent (MQTT) — no unit-conversion contortions. MQTT-only behaviour is preserved exactly: `remain = -1` still maps to the 101 sentinel and slot order still decides on ties, so users who haven't bound any spools see no change. External / VT tray slots are skipped (tracked separately from AMS bindings). Lookup runs only when `prefer_lowest_filament` is enabled — no extra DB hit for users who don't use the preference. **Tests**: 6 new in `TestPreferLowestInventoryOverride` in `test_scheduler_ams_mapping.py` (inventory override beats MQTT remain — the literal reporter scenario with 950 g clone vs 50 g original; zero-grams still sorts first within its tier; inventory tier beats MQTT tier regardless of value; tied inventory grams break to lower slot; no-override falls through to MQTT — regression guard for un-tracked spools; legacy `remain = -1` still sentinel-sorts last when override map is None) + 7 new in `test_scheduler_inventory_remain.py` covering `_build_inventory_remain_overrides` directly (internal mode returns label_weight − weight_used per bound slot; external slots skipped; empty loaded short-circuits; over-consumed spool clamps to 0 g; unbound slots absent from map; Spoolman mode uses `_spoolman_remaining_grams` for parity; Spoolman unreachability silently omits that slot). 102 scheduler + inventory tests green; backend ruff clean. - **X1/H2/P2 live camera no longer fails with `Address already in use` on transitional ffmpeg builds (#1504, reported by @rage03usa, confirmed by @PawseHaxor)** — On a native Ubuntu install with the Jammy-era system ffmpeg, the RTSP live-view path retried indefinitely with `Unable to open RTSP for listening … Address already in use`. Snapshots, the camera diagnostic, and OrcaSlicer all kept working — only live view was broken. Cause: the ffmpeg argv built in `backend/app/api/routes/camera.py` (added in 530a7a46 as part of an RTSP-stability bundle) passed `-timeout 30000000`. That ffmpeg version *deprecated* the original `-timeout` (socket I/O microseconds) and repurposed the name to mean the *RTSP listen-mode incoming-connection timeout* — any non-zero value **implies `-listen`**. ffmpeg then flipped into RTSP server mode and tried to bind the same localhost port Bambuddy's TLS proxy was already listening on, hence EADDRINUSE on every retry (the odd-port pattern @PawseHaxor noticed is coincidence — the ephemeral allocator just picked odd values that run). The reporter's own workaround (drop the option) works but silently loses the socket-level read timeout, so a hung TLS handshake would block past the OS TCP timeout instead of failing fast into the existing reconnect loop. **Why this can't be a one-line literal swap**: ffmpeg has shipped *three* arrangements of this option over time and Bambuddy supports the full range. Pre-deprecation builds: `-timeout` is the socket I/O timeout. Transitional builds (~late-4.x, what the reporter is on): `-timeout` is the broken listen-mode option, `-stimeout` is the replacement. **Modern ffmpeg (5.x / 6.x / 7.x — current Debian 13, Ubuntu 24.04, current Homebrew)**: `-stimeout` was removed entirely and `-timeout` is back to socket I/O. So both literals regress one half of the install base. **Fix**: a new `rtsp_socket_timeout_flag()` helper in `backend/app/services/camera.py` probes `ffmpeg -h demuxer=rtsp` once at first use and picks `-stimeout` when ffmpeg advertises it (transitional window) or `-timeout` otherwise (modern + very old). The result is cached for the process lifetime — ffmpeg won't swap mid-run. The function returns the option name without a leading dash so callers prepend it themselves (no empty-flag formatting bug). Wired into both RTSP ffmpeg call sites — `routes/camera.py` (printer camera) and `services/external_camera.py` (external RTSP) — in lockstep, same TLS-proxy + ffmpeg pattern, same regression. The reporter had tried `-listen_timeout` (doesn't help — we *don't* want listen mode) and `-rw_timeout` (AVIO-level, RTSP demuxer doesn't honour it on its control socket), but no manual swap could be correct for both transitional and modern installs simultaneously. **Tests**: 8 in `test_ffmpeg_rtsp_timeout_flag.py` — 6 unit tests for the probe (picks `-stimeout` when advertised, falls back to `-timeout` on modern, defaults to `-timeout` when ffmpeg missing or probe raises, caches across calls, substring-match guard against false-positives on `-listen_timeout`), 2 parametrised regression guards against either RTSP ffmpeg argv re-hard-coding a literal flag instead of consuming the probe. 37 (probe + existing external-camera) tests green; backend ruff clean. diff --git a/frontend/src/pages/StatsPage.tsx b/frontend/src/pages/StatsPage.tsx index e4475c516..4c55fe00f 100644 --- a/frontend/src/pages/StatsPage.tsx +++ b/frontend/src/pages/StatsPage.tsx @@ -253,7 +253,7 @@ function SuccessRateWidget({ {stats?.failed_prints || 0}
- + {t('stats.cancelled')} {stats?.cancelled_prints || 0}
diff --git a/static/assets/index-BW850Rth.js b/static/assets/index-RpiIrueH.js similarity index 97% rename from static/assets/index-BW850Rth.js rename to static/assets/index-RpiIrueH.js index 482ad1679..40aa58214 100644 --- a/static/assets/index-BW850Rth.js +++ b/static/assets/index-RpiIrueH.js @@ -8703,7 +8703,7 @@ Accuracy: ${t.time_accuracy.toFixed(0)}%`:t.actual_time_seconds?`Actual: ${hs(t. `,onClick:ee?()=>{window.innerWidth<640&&u()}:void 0,children:[ee&&d&&n.jsx("div",{className:"sm:hidden absolute left-0 top-3 bottom-3 w-1 rounded-full bg-bambu-green"}),n.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-4 p-3 sm:p-4",children:[R&&u&&n.jsx("button",{onClick:Q=>{Q.stopPropagation(),u()},className:`hidden sm:flex items-center justify-center w-6 h-6 rounded border transition-colors shrink-0 ${d?"bg-bambu-green border-bambu-green text-white":"border-white/30 bg-black/30 hover:border-bambu-green/50"}`,children:d&&n.jsx(_n,{className:"w-4 h-4"})}),R?n.jsx("div",{...T,...j,className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark cursor-grab active:cursor-grabbing hover:bg-bambu-dark-tertiary transition-colors touch-manipulation shrink-0",children:n.jsx(Mh,{className:"w-4 h-4 text-bambu-gray"})}):e!==void 0?n.jsxs("div",{className:"hidden sm:flex items-center justify-center w-8 h-8 rounded-lg bg-bambu-dark text-bambu-gray text-sm font-medium shrink-0",children:["#",e]}):n.jsx("div",{className:"hidden sm:block w-8 shrink-0"}),n.jsx("div",{className:"w-10 h-10 sm:w-14 sm:h-14 flex-shrink-0 bg-bambu-dark rounded-lg overflow-hidden",children:t.archive_thumbnail?n.jsx("img",{src:t.plate_id!=null?ne.getArchivePlateThumbnail(t.archive_id,t.plate_id):ne.getArchiveThumbnail(t.archive_id),alt:"",className:"w-full h-full object-cover"}):t.library_file_thumbnail?n.jsx("img",{src:t.plate_id!=null?ne.getLibraryFilePlateThumbnail(t.library_file_id,t.plate_id):ne.getLibraryFileThumbnailUrl(t.library_file_id),alt:"",className:"w-full h-full object-cover"}):n.jsx("div",{className:"w-full h-full flex items-center justify-center text-bambu-gray",children:n.jsx(cr,{className:"w-5 h-5 sm:w-6 sm:h-6"})})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsxs("p",{className:"text-sm sm:text-base text-white font-medium truncate",children:[t.archive_name||t.library_file_name||`File #${t.archive_id||t.library_file_id}`,(N?.is_multi_plate??!1)&&t.plate_id!==void 0&&t.plate_id!==null&&` • ${C.find(Q=>Q.index===t.plate_id)?.name||g("queue.plateNumber",{index:t.plate_id})}`]}),t.archive_id?n.jsx(Is,{to:`/archives?highlight=${t.archive_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:g("queue.viewArchive"),children:n.jsx(En,{className:"w-3.5 h-3.5"})}):t.library_file_id?n.jsx(Is,{to:`/library?highlight=${t.library_file_id}`,className:"text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:g("queue.viewInFileManager"),children:n.jsx(En,{className:"w-3.5 h-3.5"})}):null,t.batch_name&&n.jsx("span",{className:"flex-shrink-0 px-1.5 py-0.5 text-[10px] sm:text-xs bg-purple-500/20 text-purple-300 rounded border border-purple-500/30",children:t.batch_name})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs sm:text-sm text-bambu-gray",children:[n.jsxs("span",{className:`flex items-center gap-1 sm:gap-1.5 ${t.printer_id===null&&!t.target_model?"text-orange-400":""} ${t.target_model&&!t.printer_id?"text-blue-400":""}`,children:[n.jsx(bn,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),n.jsx("span",{className:"truncate max-w-[120px] sm:max-w-none",children:t.target_model&&!t.printer_id?`${g("queue.filter.any")} ${t.target_model}${t.target_location?` @ ${t.target_location}`:""}${t.required_filament_types?.length?` (${t.required_filament_types.join(", ")})`:""}`:t.printer_id===null?g("queue.filter.unassigned"):t.printer_name||`${g("common.printer")} #${t.printer_id}`})]}),t.print_time_seconds&&n.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[n.jsx(Zd,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),hs(t.print_time_seconds)]}),t.filament_used_grams&&n.jsxs("span",{className:"flex items-center gap-1 sm:gap-1.5",children:[n.jsx(oJ,{className:"w-3 h-3 sm:w-3.5 sm:h-3.5"}),Jnt(t.filament_used_grams)]}),t.created_by_username&&n.jsxs("span",{className:"hidden sm:flex items-center gap-1.5",title:g("queue.addedBy",{name:t.created_by_username}),children:[n.jsx(Xm,{className:"w-3.5 h-3.5"}),t.created_by_username]}),R&&!t.manual_start&&n.jsxs("span",{className:"flex items-center gap-1.5",children:[n.jsx(Za,{className:"w-3.5 h-3.5"}),t.scheduled_time?(Qa(t.scheduled_time)?.getTime()??0)-Date.now()<-6e4?g?.("queue.time.overdue")??"Overdue":Fh(t.scheduled_time,c,g):g?.("queue.time.asap")??"ASAP"]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 sm:gap-2 mt-1.5 sm:mt-2",children:[t.manual_start&&n.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm: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:[n.jsx(XZ,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),g("queue.badges.staged")]}),t.require_previous_success&&n.jsx("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-orange-500/10 text-orange-400 rounded-full border border-orange-500/20",children:g("queue.badges.requiresPrevious")}),t.auto_off_after&&n.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm: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:[n.jsx(Su,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),g("queue.badges.autoPowerOff")]}),t.gcode_injection&&n.jsxs("span",{className:"text-[10px] sm:text-xs px-1.5 sm:px-2 py-0.5 bg-emerald-500/10 text-emerald-400 rounded-full border border-emerald-500/20 flex items-center gap-1",children:[n.jsx(Zy,{className:"w-2.5 h-2.5 sm:w-3 sm:h-3"}),g("queue.badges.gcodeInjection")]})]}),B&&w&&(()=>{const Q=w.state==="RUNNING"||w.state==="PAUSE",le=Q&&w.progress||0,de=Q?w.remaining_time:null,ue=Q?w.layer_num:null,Z=Q?w.total_layers:null;return n.jsxs("div",{className:"mt-2 sm:mt-3",children:[n.jsxs("div",{className:"flex items-center justify-between text-xs sm:text-sm",children:[n.jsx("div",{className:"flex-1 bg-bambu-dark-tertiary rounded-full h-1.5 sm:h-2 mr-3",children:n.jsx("div",{className:"bg-bambu-green h-1.5 sm:h-2 rounded-full transition-all",style:{width:`${le}%`}})}),n.jsxs("span",{className:"text-white",children:[Math.round(le),"%"]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mt-1.5 sm:mt-2 text-[10px] sm:text-xs text-bambu-gray",children:[de!=null&&de>0&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(Za,{className:"w-3 h-3"}),hs(de*60)]}),n.jsxs("span",{className:"text-bambu-green font-medium",title:g("printers.estimatedCompletion"),children:["ETA ",UO(de,c,g)]})]}),ue!=null&&Z!=null&&Z>0&&n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(cr,{className:"w-3 h-3"}),ue,"/",Z]})]})]})})(),t.waiting_reason&&t.status==="pending"&&n.jsxs("p",{className:"text-[10px] sm:text-xs text-purple-400 mt-1.5 sm:mt-2 flex items-start gap-1",children:[n.jsx(zr,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),n.jsx("span",{children:t.waiting_reason})]}),t.filament_short&&t.status==="pending"&&n.jsxs("p",{className:"text-[10px] sm:text-xs text-yellow-400 mt-1.5 sm:mt-2 flex items-start gap-1",title:g("queue.filamentShort.rowTooltip"),children:[n.jsx(zr,{className:"w-3 h-3 mt-0.5 flex-shrink-0"}),n.jsx("span",{children:g("queue.filamentShort.rowBadge")})]}),t.error_message&&n.jsxs("p",{className:"text-[10px] sm:text-xs text-red-400 mt-1.5 sm:mt-2 flex items-center gap-1",children:[n.jsx(zr,{className:"w-3 h-3"}),t.error_message]})]}),n.jsxs("div",{className:"flex flex-col sm:flex-row items-end sm:items-center gap-2 sm:gap-1 shrink-0",onClick:Q=>Q.stopPropagation(),children:[n.jsx(ert,{status:t.status,waitingReason:t.waiting_reason,printerState:f,t:g}),n.jsxs("div",{className:"flex items-center gap-0.5 sm:gap-1",children:[B&&n.jsx(Me,{variant:"ghost",size:"sm",onClick:s,disabled:!m("printers:control"),title:m("printers:control")?g("queue.actions.stopPrint"):g("queue.permissions.noStopPrint"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:n.jsx(Uge,{className:"w-4 h-4"})}),R&&n.jsxs(n.Fragment,{children:[t.manual_start&&n.jsx(Me,{variant:"ghost",size:"sm",onClick:l,disabled:!m("printers:control"),title:m("printers:control")?g("queue.actions.startPrint"):g("queue.permissions.noStartPrint"),className:"text-bambu-green hover:text-bambu-green-light hover:bg-bambu-green/10 p-1.5 sm:p-2",children:n.jsx(ys,{className:"w-4 h-4"})}),n.jsx(Me,{variant:"ghost",size:"sm",onClick:a,disabled:!p("queue","update",t.created_by_id),title:p("queue","update",t.created_by_id)?g("common.edit"):g("queue.permissions.noEdit"),className:"p-1.5 sm:p-2",children:n.jsx(yi,{className:"w-4 h-4"})}),n.jsx(Me,{variant:"ghost",size:"sm",onClick:r,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?g("common.cancel"):g("queue.permissions.noCancel"),className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 p-1.5 sm:p-2",children:n.jsx($t,{className:"w-4 h-4"})})]}),X&&n.jsxs(n.Fragment,{children:[n.jsx(Me,{variant:"ghost",size:"sm",onClick:o,disabled:!m("queue:create"),title:m("queue:create")?g("queue.actions.requeue"):g("queue.permissions.noRequeue"),className:"text-bambu-green hover:text-bambu-green/80 hover:bg-bambu-green/10 p-1.5 sm:p-2",children:n.jsx(Xa,{className:"w-4 h-4"})}),n.jsx(Me,{variant:"ghost",size:"sm",onClick:i,disabled:!p("queue","delete",t.created_by_id),title:p("queue","delete",t.created_by_id)?g("common.remove"):g("queue.permissions.noRemove"),className:"p-1.5 sm:p-2",children:n.jsx(ea,{className:"w-4 h-4"})})]})]})]})]})]})}function art(){const{t}=vt(),e=ta(),{showToast:a}=ra(),{hasPermission:r,hasAnyPermission:i,canModify:s}=un(),[o,l]=y.useState(null),[c,d]=y.useState(""),[u,m]=y.useState(""),[p,f]=y.useState(!1),[g,w]=y.useState(null),[b,x]=y.useState(null),[S,N]=y.useState(null),[C,P]=y.useState([]),[T,j]=y.useState(!1),[F,k]=y.useState(()=>localStorage.getItem("queue.historySortBy")||"date"),[M,q]=y.useState(()=>{const we=localStorage.getItem("queue.historySortAsc");return we!==null?we==="true":!1}),[I,B]=y.useState(()=>localStorage.getItem("queue.pendingSortBy")||"position"),[R,X]=y.useState(()=>{const we=localStorage.getItem("queue.pendingSortAsc");return we!==null?we==="true":!0}),[ee,Q]=y.useState(()=>localStorage.getItem("queue.historyCollapsed")!=="false"),[le,de]=y.useState(()=>localStorage.getItem("queue.viewMode")||"list");y.useEffect(()=>{localStorage.setItem("queue.historySortBy",F)},[F]),y.useEffect(()=>{localStorage.setItem("queue.historySortAsc",String(M))},[M]),y.useEffect(()=>{localStorage.setItem("queue.pendingSortBy",I)},[I]),y.useEffect(()=>{localStorage.setItem("queue.pendingSortAsc",String(R))},[R]),y.useEffect(()=>{localStorage.setItem("queue.historyCollapsed",String(ee))},[ee]),y.useEffect(()=>{localStorage.setItem("queue.viewMode",le)},[le]);const ue=Tce(yT(cj,{activationConstraint:{distance:8}}),yT(lj,{coordinateGetter:Xce})),{data:Z}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),oe=Z?.time_format||"system",{data:fe,isLoading:me}=Qe({queryKey:["queue",o,c],queryFn:()=>ne.getQueue(o||void 0,c||void 0),refetchInterval:5e3}),{data:be}=Qe({queryKey:["printers"],queryFn:()=>ne.getPrinters()}),H=lt({mutationFn:we=>ne.updateSettings({queue_shortest_first:we}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]})}}),J=lt({mutationFn:we=>ne.cancelQueueItem(we),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),a(t("queue.toast.cancelled"))},onError:()=>a(t("queue.toast.cancelFailed"),"error")}),A=lt({mutationFn:we=>ne.removeFromQueue(we),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),a(t("queue.toast.removed"))},onError:()=>a(t("queue.toast.removeFailed"),"error")}),E=lt({mutationFn:we=>ne.stopQueueItem(we),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),a(t("queue.toast.stopped"))},onError:()=>a(t("queue.toast.stopFailed"),"error")}),[z,W]=y.useState(null),O=lt({mutationFn:({id:we,skipFilamentCheck:ze})=>ne.startQueueItem(we,{skipFilamentCheck:ze}),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]}),a(t("queue.toast.released")),W(null)},onError:(we,ze)=>{if(we instanceof Hi&&we.status===409&&we.code==="insufficient_filament"){const De=we.detail?.deficit??[];W({itemId:ze.id,deficit:De});return}a(t("queue.toast.startFailed"),"error")}}),re=lt({mutationFn:we=>ne.reorderQueue(we),onSuccess:()=>{e.invalidateQueries({queryKey:["queue"]})},onError:()=>a(t("queue.toast.reorderFailed"),"error")}),U=lt({mutationFn:async()=>{const we=fe?.filter(ze=>["completed","failed","skipped","cancelled"].includes(ze.status))||[];for(const ze of we)await ne.removeFromQueue(ze.id);return we.length},onSuccess:we=>{e.invalidateQueries({queryKey:["queue"]}),a(t("queue.toast.historyCleared",{count:we}))},onError:()=>a(t("queue.toast.clearHistoryFailed"),"error")}),V=lt({mutationFn:we=>ne.bulkUpdateQueue(we),onSuccess:we=>{e.invalidateQueries({queryKey:["queue"]}),P([]),j(!1),a(we.message)},onError:()=>a(t("queue.toast.updateFailed"),"error")}),K=lt({mutationFn:async we=>{for(const ze of we)await ne.cancelQueueItem(ze);return we.length},onSuccess:we=>{e.invalidateQueries({queryKey:["queue"]}),P([]),a(t("queue.toast.bulkCancelled",{count:we}))},onError:()=>a(t("queue.toast.bulkCancelFailed"),"error")}),Y=we=>{P(ze=>ze.includes(we)?ze.filter(De=>De!==we):[...ze,we])},ie=y.useMemo(()=>{const we=new Set;return be?.forEach(ze=>{ze.location&&we.add(ze.location)}),fe?.forEach(ze=>{ze.target_location&&we.add(ze.target_location)}),Array.from(we).sort()},[be,fe]),se=y.useCallback(we=>u?we.target_location?we.target_location===u:we.printer_id?be?.find(De=>De.id===we.printer_id)?.location===u:!1:!0,[u,be]),pe=y.useMemo(()=>{let we=fe?.filter(De=>De.status==="pending")||[];u&&(we=we.filter(se));const ze=De=>{if(!De.scheduled_time)return 0;const Le=Qa(De.scheduled_time)?.getTime()??0,Re=Date.now()+4320*60*60*1e3;return Le>Re?0:Le};return Z?.queue_shortest_first?[...we].sort((De,Le)=>{const Re=De.printer_id??-(De.target_model?.charCodeAt(0)??0),We=Le.printer_id??-(Le.target_model?.charCodeAt(0)??0);if(Re!==We)return Re-We;const Be=De.been_jumped?1:0,ot=Le.been_jumped?1:0;if(Be!==ot)return ot-Be;const Ee=De.print_time_seconds??1/0,it=Le.print_time_seconds??1/0;return Ee!==it?Ee-it:De.position-Le.position}):[...we].sort((De,Le)=>{let Re;if(I==="name"){const We=De.archive_name||De.library_file_name||"",Be=Le.archive_name||Le.library_file_name||"";Re=We.localeCompare(Be)}else I==="printer"?Re=(De.printer_name||"").localeCompare(Le.printer_name||""):I==="time"?Re=ze(De)-ze(Le):Re=De.position-Le.position;return R?Re:-Re})},[fe,I,R,se,u,Z?.queue_shortest_first]),ce=()=>{const we=pe.map(ze=>ze.id);C.length===we.length?P([]):P(we)},he=y.useMemo(()=>{let we=fe?.filter(ze=>ze.status==="printing")||[];return u&&(we=we.filter(se)),we},[fe,u,se]),$=y.useMemo(()=>{const we=new Set;return he.forEach(ze=>{ze.printer_id&&we.add(ze.printer_id)}),Array.from(we)},[he]),L=rf({queries:$.map(we=>({queryKey:["printerStatus",we],queryFn:()=>ne.getPrinterStatus(we),refetchInterval:5e3}))}),ae=y.useMemo(()=>{const we={};return $.forEach((ze,De)=>{const Le=L[De];Le?.data?.state&&(we[ze]=Le.data.state)}),we},[$,L]),ge=y.useMemo(()=>{const we={};return $.forEach((ze,De)=>{const Le=L[De];Le?.data&&(we[ze]={progress:Le.data.progress??void 0,remaining_time:Le.data.remaining_time??void 0,state:Le.data.state??void 0})}),we},[$,L]),xe=y.useMemo(()=>{let we=fe?.filter(ze=>["completed","failed","skipped","cancelled"].includes(ze.status))||[];return u&&(we=we.filter(se)),[...we].sort((ze,De)=>{let Le;if(F==="name"){const Re=ze.archive_name||ze.library_file_name||"",We=De.archive_name||De.library_file_name||"";Le=Re.localeCompare(We)}else F==="printer"?Le=(ze.printer_name||"").localeCompare(De.printer_name||""):Le=(Qa(De.completed_at||De.created_at)?.getTime()??0)-(Qa(ze.completed_at||ze.created_at)?.getTime()??0);return M?-Le:Le})},[fe,F,M,se,u]),Se=y.useMemo(()=>pe.reduce((we,ze)=>we+(ze.print_time_seconds||0),0),[pe]),Te=y.useMemo(()=>pe.reduce((we,ze)=>we+(ze.filament_used_grams||0),0),[pe]),ve=we=>{const{active:ze,over:De}=we;if(!De||ze.id===De.id)return;const Le=pe.findIndex(We=>We.id===ze.id),Re=pe.findIndex(We=>We.id===De.id);if(Le!==-1&&Re!==-1){const Be=mj(pe,Le,Re).map((ot,Ee)=>({id:ot.id,position:Ee+1}));re.mutate(Be)}};return n.jsxs("div",{className:"p-4 md:p-8",children:[n.jsx("div",{className:"flex items-center justify-between mb-8",children:n.jsxs("div",{children:[n.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[n.jsx(Rw,{className:"w-7 h-7 text-bambu-green"}),t("queue.title")]}),n.jsx("p",{className:"text-bambu-gray mt-1",children:t("queue.subtitle")})]})}),n.jsx(Vnt,{activeCount:he.length,pendingCount:pe.length,totalTime:Se,totalWeight:Te,historyCount:xe.length,t}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6",children:[n.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:o===-1?"unassigned":o||"",onChange:we=>{const ze=we.target.value;l(ze==="unassigned"?-1:ze===""?null:Number(ze))},children:[n.jsx("option",{value:"",children:t("queue.filter.allPrinters")}),n.jsx("option",{value:"unassigned",children:t("queue.filter.unassigned")}),be?.map(we=>n.jsx("option",{value:we.id,children:we.name},we.id))]}),n.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:c,onChange:we=>d(we.target.value),children:[n.jsx("option",{value:"",children:t("queue.filter.allStatus")}),n.jsx("option",{value:"pending",children:t("queue.status.pending")}),n.jsx("option",{value:"printing",children:t("queue.status.printing")}),n.jsx("option",{value:"completed",children:t("queue.status.completed")}),n.jsx("option",{value:"failed",children:t("queue.status.failed")}),n.jsx("option",{value:"skipped",children:t("queue.status.skipped")}),n.jsx("option",{value:"cancelled",children:t("queue.status.cancelled")})]}),ie.length>0&&n.jsxs("select",{className:"px-2 sm:px-3 py-2 text-sm sm:text-base bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none min-w-0 flex-1 sm:flex-none",value:u,onChange:we=>m(we.target.value),children:[n.jsx("option",{value:"",children:t("queue.filter.allLocations")}),ie.map(we=>n.jsx("option",{value:we,children:we},we))]}),n.jsx("div",{className:"hidden sm:block flex-1"}),xe.length>0&&n.jsxs(Me,{className:"w-full sm:w-auto",variant:"secondary",size:"sm",onClick:()=>f(!0),disabled:!r("queue:delete_all"),title:r("queue:delete_all")?void 0:t("queue.permissions.noClearHistory"),children:[n.jsx(ea,{className:"w-4 h-4"}),t("queue.clearHistory")]})]}),n.jsxs("div",{className:"flex items-center gap-3 mb-6",children:[n.jsxs("div",{className:"hidden sm:flex items-center border border-bambu-dark-tertiary rounded-lg overflow-hidden",children:[n.jsx("button",{className:`p-2 transition-colors ${le==="list"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>de("list"),title:t("queue.timeline.listView"),children:n.jsx(FS,{className:"w-4 h-4"})}),n.jsx("button",{className:`p-2 transition-colors ${le==="timeline"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,onClick:()=>de("timeline"),title:t("queue.timeline.timelineView"),children:n.jsx(_ge,{className:"w-4 h-4"})})]}),n.jsxs("button",{onClick:()=>{const we=!(Z?.queue_shortest_first??!1);H.mutate(we)},className:`flex items-center gap-1 px-2 py-1.5 text-xs rounded-lg border transition-colors ${Z?.queue_shortest_first?"bg-bambu-green/20 border-bambu-green text-bambu-green":"bg-bambu-dark-secondary border-bambu-dark-tertiary text-bambu-gray hover:text-white hover:border-bambu-gray"}`,title:t("queue.sjf.tooltip","Shortest Job First — scheduler prioritizes shorter prints"),children:[n.jsx(cve,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("queue.sjf.label","SJF")}),n.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Z?.queue_shortest_first?"bg-bambu-green":"bg-bambu-gray"}`})]})]}),me?n.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("common.loading")}):fe?.length===0?n.jsxs(Tt,{className:"p-12 text-center border-dashed",children:[n.jsx(vr,{className:"w-16 h-16 text-bambu-gray mx-auto mb-4 opacity-50"}),n.jsx("h3",{className:"text-xl font-medium text-white mb-2",children:t("queue.empty.title")}),n.jsx("p",{className:"text-bambu-gray max-w-md mx-auto",children:t("queue.empty.description")})]}):le==="timeline"?n.jsx(Znt,{queueItems:fe||[],printerStatuses:ge,onItemClick:we=>{["completed","failed","skipped","cancelled"].includes(we.status)?x(we):we.status==="pending"?w(we):we.status==="printing"&&N({type:"stop",item:we})},t}):n.jsxs("div",{className:"space-y-6 sm:space-y-8",children:[he.length>0&&n.jsxs("div",{children:[n.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white mb-3 sm:mb-4 flex items-center gap-2",children:[n.jsx("div",{className:"w-2 h-2 rounded-full bg-blue-400 animate-pulse"}),t("queue.sections.currentlyPrinting")]}),n.jsx("div",{className:"space-y-2 sm:space-y-3",children:he.map(we=>n.jsx(gX,{item:we,onEdit:()=>{},onCancel:()=>{},onRemove:()=>{},onStop:()=>N({type:"stop",item:we}),onRequeue:()=>{},onStart:()=>{},timeFormat:oe,hasPermission:r,canModify:s,printerState:we.printer_id?ae[we.printer_id]:null,t},we.id))})]}),pe.length>0&&n.jsxs("div",{children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[n.jsxs("h2",{className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2",children:[n.jsx(Za,{className:"w-4 h-4 sm:w-5 sm:h-5 text-yellow-400"}),t("queue.sections.queued"),n.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:pe.length}),")"]}),n.jsx("span",{className:"hidden sm:inline text-xs text-bambu-gray ml-2",title:t("queue.reorderHint"),children:t("queue.dragToReorder")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:I,onChange:we=>B(we.target.value),children:[n.jsx("option",{value:"position",children:t("queue.sort.byPosition")}),n.jsx("option",{value:"name",children:t("queue.sort.byName")}),n.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")}),n.jsx("option",{value:"time",children:t("queue.sort.bySchedule")})]}),n.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>X(!R),title:t(R?"common.ascending":"common.descending"),className:"px-2",children:R?n.jsx(Km,{className:"w-4 h-4"}):n.jsx(Vh,{className:"w-4 h-4"})})]})]}),n.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:gap-3 mb-3 sm:mb-4 p-2 sm:p-3 bg-bambu-dark rounded-lg",children:[n.jsxs(Me,{variant:"ghost",size:"sm",onClick:ce,className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm",children:[C.length===pe.length&&pe.length>0?n.jsx(ws,{className:"w-4 h-4 text-bambu-green"}):n.jsx(lo,{className:"w-4 h-4"}),C.length===pe.length&&pe.length>0?t("queue.bulkEdit.deselectAll"):t("queue.bulkEdit.selectAll")]}),C.length>0&&n.jsxs(n.Fragment,{children:[n.jsx("span",{className:"text-xs sm:text-sm text-bambu-gray",children:t("queue.bulkEdit.selected",{count:C.length})}),n.jsx("div",{className:"hidden sm:block h-4 w-px bg-bambu-dark-tertiary"}),n.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>j(!0),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-bambu-green hover:text-bambu-green-light",disabled:!i("queue:update_own","queue:update_all"),title:i("queue:update_own","queue:update_all")?t("queue.bulkEdit.editSelected"):t("queue.permissions.noEditItems"),children:[n.jsx(yi,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.editSelected")})]}),n.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>K.mutate(C),className:"flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm text-red-400 hover:text-red-300",disabled:K.isPending||!i("queue:delete_own","queue:delete_all"),title:i("queue:delete_own","queue:delete_all")?t("queue.bulkEdit.cancelSelected"):t("queue.permissions.noCancelItems"),children:[n.jsx($t,{className:"w-3.5 h-3.5 sm:w-4 sm:h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("queue.bulkEdit.cancelSelected")})]})]})]}),n.jsx(Vce,{sensors:ue,collisionDetection:Ece,onDragEnd:ve,children:n.jsx(Kce,{items:pe.map(we=>we.id),strategy:Dnt,children:n.jsx("div",{className:"space-y-2 sm:space-y-3",children:pe.map((we,ze)=>n.jsx(gX,{item:we,position:ze+1,onEdit:()=>w(we),onCancel:()=>N({type:"cancel",item:we}),onRemove:()=>{},onStop:()=>{},onRequeue:()=>{},onStart:()=>O.mutate({id:we.id}),timeFormat:oe,isSelected:C.includes(we.id),onToggleSelect:()=>Y(we.id),hasPermission:r,canModify:s,t},we.id))})})})]}),xe.length>0&&n.jsxs("div",{children:[n.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 mb-3 sm:mb-4",children:[n.jsxs("button",{onClick:()=>Q(!ee),className:"text-base sm:text-lg font-semibold text-white flex items-center gap-2 hover:text-bambu-green transition-colors",children:[ee?n.jsx(Hr,{className:"w-4 h-4 sm:w-5 sm:h-5"}):n.jsx(Da,{className:"w-4 h-4 sm:w-5 sm:h-5"}),t("queue.sections.history"),n.jsxs("span",{className:"text-xs sm:text-sm font-normal text-bambu-gray",children:["(",t("queue.itemCount",{count:xe.length}),")"]})]}),!ee&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("select",{className:"px-2 sm:px-3 py-1.5 text-xs sm:text-sm bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:F,onChange:we=>k(we.target.value),children:[n.jsx("option",{value:"date",children:t("queue.sort.byDate")}),n.jsx("option",{value:"name",children:t("queue.sort.byName")}),n.jsx("option",{value:"printer",children:t("queue.sort.byPrinter")})]}),n.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>q(!M),title:t(M?"queue.sort.ascendingOldest":"queue.sort.descendingNewest"),className:"px-2",children:M?n.jsx(Km,{className:"w-4 h-4"}):n.jsx(Vh,{className:"w-4 h-4"})})]})]}),!ee&&n.jsx("div",{className:"space-y-1.5 sm:space-y-2",children:xe.slice(0,50).map(we=>n.jsx(Gnt,{item:we,onRemove:()=>N({type:"remove",item:we}),onRequeue:()=>x(we),timeFormat:oe,hasPermission:r,canModify:s,t},we.id))})]})]}),g&&n.jsx(wc,{mode:"edit-queue-item",archiveId:g.archive_id??void 0,libraryFileId:g.library_file_id??void 0,archiveName:g.archive_name||g.library_file_name||`File #${g.archive_id||g.library_file_id}`,queueItem:g,onClose:()=>w(null)}),b&&n.jsx(wc,{mode:"add-to-queue",archiveId:b.archive_id??void 0,libraryFileId:b.library_file_id??void 0,archiveName:b.archive_name||b.library_file_name||`File #${b.archive_id||b.library_file_id}`,onClose:()=>x(null)}),z&&n.jsx(ya,{title:t("queue.filamentShort.confirmTitle"),message:t("queue.filamentShort.confirmIntro")+` `+z.deficit.map(we=>t("queue.filamentShort.lineItem",{slot:we.slot_id,required:Math.round(we.required_grams),remaining:we.remaining_grams==null?t("queue.filamentShort.unknown"):Math.round(we.remaining_grams)})).join(` -`),confirmText:t("queue.filamentShort.printAnyway"),variant:"warning",onConfirm:()=>{O.mutate({id:z.itemId,skipFilamentCheck:!0})},onCancel:()=>W(null)}),S&&n.jsx(ya,{title:S.type==="cancel"?t("queue.confirm.cancelTitle"):S.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:S.type==="cancel"?t("queue.confirm.cancelMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):S.type==="stop"?t("queue.confirm.stopMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:S.type==="cancel"?t("queue.confirm.cancelButton"):S.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{S.type==="cancel"?J.mutate(S.item.id):S.type==="stop"?E.mutate(S.item.id):A.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),p&&n.jsx(ya,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:xe.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{U.mutate(),f(!1)},onCancel:()=>f(!1)}),T&&n.jsx(trt,{selectedCount:C.length,printers:be?.map(we=>({id:we.id,name:we.name}))||[],onSave:we=>{Object.keys(we).length>0&&V.mutate({item_ids:C,...we})},onClose:()=>j(!1),isSaving:V.isPending,canControlPrinter:r("printers:control"),t})]})}function nrt({printDates:t,months:e=3}){const a=y.useRef(null),[r,i]=y.useState(0);y.useEffect(()=>{const S=a.current;if(!S)return;const N=new ResizeObserver(C=>{const P=C[0]?.contentRect.width||0;i(P)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=y.useMemo(()=>{const S={};t.forEach(q=>{const I=xE(q);I&&(S[I]=(S[I]||0)+1)});const N=new Date,C=new Date(N);C.setMonth(C.getMonth()-e),C.setDate(C.getDate()-C.getDay());const P=[],T=[];let j=[],F=-1;const k=new Date(C);let M=0;for(;k<=N;)k.getDay()===0&&j.length>0&&(P.push(j),j=[],M++),k.getMonth()!==F&&(T.push({month:k.toLocaleDateString("en-US",{month:"short"}),weekIndex:M}),F=k.getMonth()),j.push(new Date(k)),k.setDate(k.getDate()+1);return j.length>0&&P.push(j),{weeks:P,monthLabels:T,printCounts:S}},[t,e]),c=Math.max(1,...Object.values(l)),d=S=>{if(S===0)return"bg-bambu-dark";const N=S/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,g=r-p-16,w=m>0?Math.floor((g-(m-1)*f)/m):12,b=Math.max(8,Math.min(20,w)),x=b<=10?10:12;return n.jsx("div",{ref:a,className:"w-full flex justify-center",children:r>0&&n.jsxs("div",{children:[n.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:S,weekIndex:N},C)=>n.jsx("div",{className:"text-bambu-gray",style:{fontSize:x,marginLeft:C===0?0:`${(N-(o[C-1]?.weekIndex||0))*(b+f)-24}px`},children:S},C))}),n.jsxs("div",{className:"flex",style:{gap:f},children:[n.jsx("div",{className:"flex flex-col",style:{gap:f,marginRight:4,width:p},children:u.map((S,N)=>n.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:x,visibility:N%2===1?"visible":"hidden"},children:S},S))}),s.map((S,N)=>n.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(C=>{const P=S.find(k=>k.getDay()===C);if(!P)return n.jsx("div",{style:{width:b,height:b}},C);const T=xE(P),j=l[T]||0,F=T===xE(new Date);return n.jsx("div",{className:`rounded-sm ${d(j)} ${F?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${P.toLocaleDateString()}: ${j} print${j!==1?"s":""}`},C)})},N))]}),n.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:x},children:[n.jsx("span",{children:"Less"}),n.jsxs("div",{className:"flex",style:{gap:f},children:[n.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),n.jsx("span",{children:"More"})]})]})})}const bX=["weight","prints","time"];function ST({value:t,onChange:e,exclude:a}){const{t:r}=vt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=a?bX.filter(o=>!a.includes(o)):bX;return n.jsx("div",{className:"flex gap-0.5 bg-bambu-dark rounded-lg p-0.5",children:s.map(o=>n.jsx("button",{onClick:()=>e(o),className:`px-2 py-0.5 text-xs rounded-md transition-colors ${t===o?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:i[o]},o))})}function yh(t){if(t>=1e6){const e=t/1e6;return`${e%1===0?e.toFixed(0):e.toFixed(1)}t`}if(t>=1e3){const e=t/1e3;return`${e%1===0?e.toFixed(0):e.toFixed(1)}kg`}return`${Math.round(t)}g`}const pN=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],rrt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],xX=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"];function irt({archives:t,currency:e="$",dateFrom:a,dateTo:r}){const{t:i}=vt(),[s,o]=y.useState("weight"),[l,c]=y.useState("weight"),d=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{const M=Qa(k.completed_at||k.created_at)||new Date,q=`${M.getFullYear()}-${String(M.getMonth()+1).padStart(2,"0")}-${String(M.getDate()).padStart(2,"0")}`,I=F.get(q)||{date:q,filament:0,cost:0,prints:0};I.filament+=k.filament_used_grams||0,I.cost+=k.cost||0,I.prints+=k.quantity||1,F.set(q,I)}),Array.from(F.values()).sort((k,M)=>k.date.localeCompare(M.date)).map(k=>({...k,dateLabel:new Date(k.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[t]),u=y.useMemo(()=>{if(a&&r)return Math.max((new Date(r).getTime()-new Date(a).getTime())/864e5,0)+1;if(a)return Math.max((Date.now()-new Date(a).getTime())/864e5,0)+1;if(t.length<2)return 0;const F=t.map(k=>new Date(k.completed_at||k.created_at).getTime());return(Math.max(...F)-Math.min(...F))/864e5},[t,a,r]),m=y.useMemo(()=>{if(u>7)return[];const F=new Map,k=u>1;return t.forEach(M=>{const q=Qa(M.completed_at||M.created_at)||new Date,I=q.getHours(),B=`${q.getFullYear()}-${String(q.getMonth()+1).padStart(2,"0")}-${String(q.getDate()).padStart(2,"0")}T${String(I).padStart(2,"0")}`,R=F.get(B)||{date:B,filament:0,cost:0,prints:0};R.filament+=M.filament_used_grams||0,R.cost+=M.cost||0,R.prints+=M.quantity||1,F.set(B,R)}),Array.from(F.values()).sort((M,q)=>M.date.localeCompare(q.date)).map(M=>{const[q,I]=M.date.split("T"),B=new Date(q),R=parseInt(I,10),X=k?`${rrt[B.getDay()]} ${xX[R]}`:xX[R];return{...M,dateLabel:X}})},[t,u]),p=y.useMemo(()=>{if(d.length<=60)return d;const F=new Map;return d.forEach(k=>{const M=new Date(k.date),q=new Date(M);q.setDate(M.getDate()-M.getDay());const I=`${q.getFullYear()}-${String(q.getMonth()+1).padStart(2,"0")}-${String(q.getDate()).padStart(2,"0")}`,B=F.get(I)||{week:I,filament:0,cost:0,prints:0};B.filament+=k.filament,B.cost+=k.cost,B.prints+=k.prints,F.set(I,B)}),Array.from(F.values()).sort((k,M)=>k.week.localeCompare(M.week)).map(k=>({date:k.week,dateLabel:`Week of ${new Date(k.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...k}))},[d]),f=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{const q=(k.filament_type||"Unknown").split(", ");q.forEach(I=>{const B=(k.filament_used_grams||0)/q.length;F.set(I,(F.get(I)||0)+B)})}),Array.from(F.entries()).map(([k,M])=>({name:k,value:Math.round(M)})).sort((k,M)=>M.value-k.value)},[t]),g=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{(k.filament_type||"Unknown").split(", ").forEach(I=>{F.set(I,(F.get(I)||0)+1)})}),Array.from(F.entries()).map(([k,M])=>({name:k,value:M})).sort((k,M)=>M.value-k.value)},[t]),w=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{const q=(k.filament_type||"Unknown").split(", "),I=(k.actual_time_seconds||k.print_time_seconds||0)/q.length;q.forEach(B=>{F.set(B,(F.get(B)||0)+I)})}),Array.from(F.entries()).map(([k,M])=>({name:k,value:Math.round(M/3600*10)/10})).sort((k,M)=>M.value-k.value)},[t]),b=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(k.status!=="completed"&&k.status!=="failed")return;(k.filament_type||"Unknown").split(", ").forEach(q=>{const I=F.get(q)||{completed:0,failed:0};k.status==="completed"?I.completed++:I.failed++,F.set(q,I)})}),Array.from(F.entries()).filter(([,k])=>k.completed+k.failed>=2).map(([k,M])=>{const q=M.completed+M.failed,I=Math.round(M.completed/q*100);return{name:k,rate:I,total:q}}).sort((k,M)=>M.rate-k.rate)},[t]),x=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(!k.filament_color)return;const M=k.filament_color.split(",").map(I=>I.trim()),q=(k.filament_used_grams||0)/M.length;M.forEach(I=>{const B=F.get(I)||{count:0,weight:0};B.count++,B.weight+=q,F.set(I,B)})}),Array.from(F.entries()).map(([k,M])=>({hex:k,value:l==="prints"?M.count:Math.round(M.weight)})).sort((k,M)=>M.value-k.value)},[t,l]),S=s==="weight"?f:s==="prints"?g:w,N=u<=7&&m.length>0?m:p,C=t.reduce((F,k)=>F+(k.filament_used_grams||0),0),P=t.reduce((F,k)=>F+(k.cost||0),0),T=t.reduce((F,k)=>F+(k.quantity||1),0),j=new Set(t.map(F=>F.printer_id).filter(Boolean)).size;return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"grid grid-cols-3 gap-2 max-[640px]:grid-cols-1",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodFilament")}),n.jsx("p",{className:"text-2xl font-bold text-white leading-none",children:yh(C)})]}),n.jsxs("p",{className:"text-xs text-bambu-gray",children:[j," ",i("nav.printers").toLowerCase()]})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodCost")}),n.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,P.toFixed(2)]})]}),n.jsxs("p",{className:"text-xs text-bambu-gray",children:[T," ",i("common.prints")]})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.avgPerPrint")}),n.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[T>0?(C/T).toFixed(0):0,"g"]})]}),n.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,T>0?(P/T).toFixed(2):"0.00"," avg"]})]})]}),N.length>0?n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.usageOverTime")}),n.jsx(au,{width:"100%",height:250,children:n.jsxs(w5,{data:N,children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[n.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),n.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:F=>`${F}g`}),n.jsx(ru,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:F=>[`${Number(F??0).toFixed(0)}g`,"Filament"]}),n.jsx(qA,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):n.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:i("stats.noPrintDataInRange")}),n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.byMaterial")}),n.jsx(ST,{value:s,onChange:o})]}),S.length>0?n.jsxs("div",{className:"flex items-center gap-4",children:[n.jsx(au,{width:160,height:160,children:n.jsxs($K,{children:[n.jsx(iI,{data:S,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:S.map((F,k)=>n.jsx(Oy,{fill:pN[k%pN.length]},`cell-${k}`))}),n.jsx(ru,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:F=>[s==="weight"?yh(Number(F??0)):s==="time"?`${Number(F??0)}h`:`${F??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),n.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:S.map((F,k)=>{const M=S.reduce((I,B)=>I+B.value,0),q=M>0?(F.value/M*100).toFixed(0):0;return n.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:pN[k%pN.length]}}),n.jsx("span",{className:"text-white truncate flex-1",children:F.name}),n.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?yh(F.value):s==="time"?`${F.value}h`:F.value," · ",q,"%"]})]},F.name)})})]}):n.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noFilamentData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.filamentSuccess")}),b.length>0?n.jsx("div",{className:"space-y-1.5",children:b.map(F=>n.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.jsx("span",{className:"text-white truncate w-20 flex-shrink-0",children:F.name}),n.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-secondary rounded-full",children:n.jsx("div",{className:`h-full rounded-full transition-all ${F.rate>=90?"bg-status-ok":F.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${F.rate}%`}})}),n.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${F.rate>=90?"text-status-ok":F.rate>=70?"text-status-warning":"text-status-error"}`,children:[F.rate,"%"]}),n.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",F.total,")"]})]},F.name))}):n.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noArchiveData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.colorDistribution")}),n.jsx(ST,{value:l,onChange:c,exclude:["time"]})]}),x.length>0?(()=>{const F=x.reduce((k,M)=>k+M.value,0);return n.jsxs("div",{children:[n.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[n.jsx(au,{width:"100%",height:"100%",children:n.jsxs($K,{children:[n.jsx(iI,{data:x,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:x.map((k,M)=>n.jsx(Oy,{fill:k.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${M}`))}),n.jsx(ru,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:k=>[l==="weight"?yh(Number(k??0)):`${k??0}`,i(l==="weight"?"stats.filamentByWeight":"stats.filamentByPrints")]})]})}),n.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[n.jsx("span",{className:"text-lg font-bold text-white",children:l==="weight"?yh(F):F}),n.jsxs("span",{className:"text-[10px] text-bambu-gray",children:[x.length," ",x.length===1?"color":"colors"]})]})]}),n.jsx("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1 mt-2",children:x.slice(0,8).map(k=>{const M=F>0?(k.value/F*100).toFixed(0):0;return n.jsxs("div",{className:"flex items-center gap-1.5 text-xs min-w-0",children:[n.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20",style:{backgroundColor:k.hex}}),n.jsxs("span",{className:"text-bambu-gray truncate",children:[M,"%"]})]},k.hex)})}),x.length>8&&n.jsxs("p",{className:"text-[10px] text-bambu-gray mt-1 text-center",children:["+",x.length-8," more"]})]})})():n.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noColorData")})]})]})]})}function srt({id:t,title:e,component:a,isHidden:r,size:i,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:f}=Yce({id:t}),g={transform:Wy.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:n.jsxs("div",{ref:u,style:{...g,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{...c,...d,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:n.jsx(Mh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),n.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{onClick:l,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?n.jsx(EO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):n.jsx(MT,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),n.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:n.jsx(db,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),n.jsx("div",{className:"p-4",children:typeof a=="function"?a(i):a})]})}function ort({widgets:t,storageKey:e,columns:a=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const F={};return t.forEach(k=>{F[k.id]=k.defaultSize||4}),F},[c,d]=y.useState(()=>{const F=localStorage.getItem(e);if(F)try{const k=JSON.parse(F);if(!k.sizes)k.sizes=l();else{const M=l();for(const q in M)q in k.sizes||(k.sizes[q]=M[q])}return k}catch{}return{order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()}}),[u,m]=y.useState(!1),[p,f]=y.useState(!1);y.useEffect(()=>{if(!r)return;const F=window.matchMedia(`(max-width: ${r}px)`),k=q=>{f(q.matches)};k(F);const M=q=>k(q);return F.addEventListener?F.addEventListener("change",M):F.addListener(M),()=>{F.removeEventListener?F.removeEventListener("change",M):F.removeListener(M)}},[r]);const g=r&&p?1:a;y.useEffect(()=>{const F=()=>m(k=>!k);return window.addEventListener("toggle-hidden-panel",F),()=>window.removeEventListener("toggle-hidden-panel",F)},[]),y.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),y.useEffect(()=>{const k=t.map(M=>M.id).filter(M=>!c.order.includes(M));k.length>0&&d(M=>({...M,order:[...M.order,...k]}))},[t,c.order]);const w=Tce(yT(cj,{activationConstraint:{distance:8}}),yT(lj,{coordinateGetter:Xce})),b=F=>{const{active:k,over:M}=F;M&&k.id!==M.id&&d(q=>{const I=q.order.indexOf(k.id),B=q.order.indexOf(M.id);return{...q,order:mj(q.order,I,B)}})},x=F=>{d(k=>({...k,hidden:k.hidden.includes(F)?k.hidden.filter(M=>M!==F):[...k.hidden,F]}))},S=F=>{d(k=>{const M=k.sizes[F]||4,q=M===1?2:M===2?4:1;return{...k,sizes:{...k.sizes,[F]:q}}})},N=()=>{const F={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()};d(F),s?.()},C=c.order.map(F=>t.find(k=>k.id===F)).filter(Boolean),P=C.filter(F=>!c.hidden.includes(F.id)),T=C.filter(F=>c.hidden.includes(F.id)),j=o?.({hiddenCount:T.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:N});return n.jsxs("div",{className:"space-y-4",children:[j,!i&&!o&&n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsxs(Me,{variant:"secondary",size:"sm",onClick:N,children:[n.jsx(vs,{className:"w-4 h-4"}),"Reset Layout"]}),T.length>0&&n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[n.jsx(Ml,{className:"w-4 h-4"}),T.length," Hidden"]})]}),u&&T.length>0&&n.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),n.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(F=>n.jsxs("button",{onClick:()=>x(F.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:[n.jsx(Ml,{className:"w-3 h-3"}),F.title]},F.id))})]}),n.jsx(Vce,{sensors:w,collisionDetection:Ece,onDragEnd:b,children:n.jsx(Kce,{items:P.map(F=>F.id),strategy:bU,children:n.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${g}, minmax(0, 1fr))`},children:P.map(F=>{const k=c.sizes[F.id]||2,M=Math.min(k,g);return n.jsx(srt,{id:F.id,title:F.title,component:F.component,isHidden:c.hidden.includes(F.id),size:k,columnSpan:M,onToggleVisibility:()=>x(F.id),onToggleSize:()=>S(F.id)},F.id)})})})}),P.length===0&&n.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[n.jsx("p",{children:"All widgets are hidden."}),n.jsx(Me,{className:"mt-4",onClick:N,children:"Reset Layout"})]})]})}function lrt(t){const e=new Date,a=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate(),s=l=>l.toISOString().split("T")[0],o=s(e);switch(t){case"today":return{dateFrom:o,dateTo:o};case"this-week":{const l=e.getUTCDay(),c=new Date(Date.UTC(a,r,i-(l===0?6:l-1)));return{dateFrom:s(c),dateTo:o}}case"this-month":return{dateFrom:s(new Date(Date.UTC(a,r,1))),dateTo:o};case"last-7":return{dateFrom:s(new Date(Date.UTC(a,r,i-6))),dateTo:o};case"last-30":return{dateFrom:s(new Date(Date.UTC(a,r,i-29))),dateTo:o};case"last-90":return{dateFrom:s(new Date(Date.UTC(a,r,i-89))),dateTo:o};case"this-year":return{dateFrom:s(new Date(Date.UTC(a,0,1))),dateTo:o};case"all-time":return{dateFrom:void 0,dateTo:void 0};case"custom":return{}}}const crt=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],drt=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],nO=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],f3=[{key:"<30m",max:1800},{key:"30m-1h",max:3600},{key:"1-2h",max:7200},{key:"2-4h",max:14400},{key:"4-8h",max:28800},{key:"8-12h",max:43200},{key:"12-24h",max:86400},{key:"24h+",max:1/0}],hN={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function urt({stats:t,currency:e}){const{t:a}=vt(),r=t?.energy_data_warming_up===!0,i=r?a("stats.energyWarmingUpTooltip"):void 0,s=[{icon:Hn,color:"text-bambu-green",label:a("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:Za,color:"text-blue-400",label:a("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Hn,color:"text-orange-400",label:a("stats.filamentUsed"),value:yh(t?.total_filament_grams||0)},{icon:rC,color:"text-green-400",label:a("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:Nc,color:"text-yellow-400",label:a("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`,warning:r,tooltip:i},{icon:rC,color:"text-yellow-500",label:a("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`,warning:r,tooltip:i}];return n.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:s.map(o=>n.jsxs("div",{className:"flex items-start gap-3",title:o.tooltip,children:[n.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${o.color}`,children:n.jsx(o.icon,{className:"w-5 h-5"})}),n.jsxs("div",{children:[n.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[o.label,o.warning&&n.jsx(ba,{className:"w-3 h-3 text-yellow-400","aria-label":o.tooltip})]}),n.jsx("p",{className:"text-xl font-bold text-white",children:o.value})]})]},o.label))})}function mrt({stats:t,printerMap:e,size:a=1}){const{t:r}=vt(),i=(t?.successful_prints||0)+(t?.failed_prints||0),s=i?Math.round((t?.successful_prints||0)/i*100):0,o=a===1?112:a===2?128:144,l=o/2-8,c=l*2*Math.PI;return n.jsxs("div",{className:"flex items-center gap-6",children:[n.jsxs("div",{className:"relative flex-shrink-0",style:{width:o,height:o},children:[n.jsxs("svg",{className:"w-full h-full -rotate-90",children:[n.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),n.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${s/100*c} ${c}`})]}),n.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:n.jsxs("span",{className:`font-bold text-white ${a>=2?"text-2xl":"text-xl"}`,children:[s,"%"]})})]}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fn,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),n.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),n.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Mn,{className:"w-4 h-4 text-status-error flex-shrink-0"}),n.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),n.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Xfe,{className:"w-4 h-4 text-bambu-gray flex-shrink-0"}),n.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.cancelled")}),n.jsx("span",{className:"text-sm text-white font-medium",children:t?.cancelled_prints||0})]})]}),a>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&n.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),n.jsx("div",{className:`grid gap-x-6 gap-y-1 ${a===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([d,u])=>n.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[n.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(d)||`${r("common.printer")} ${d}`}),n.jsx("span",{className:"text-white font-medium",children:u})]},d))})]})]})]})}function prt({stats:t,printerMap:e,size:a=1}){const{t:r}=vt(),i=t?.average_time_accuracy;if(i==null)return n.jsx("div",{className:"flex items-center justify-center h-full",children:n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(w=>w>=95&&w<=105?"#00ae42":w>105?"#3b82f6":"#f97316")(i),d=i-100,u=a===1?112:a===2?128:144,m=u/2-8,p=m*2*Math.PI,f=a===1?3:a===2?6:999,g=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,f):[];return n.jsxs("div",{className:"flex items-center gap-6",children:[n.jsxs("div",{className:"relative flex-shrink-0",style:{width:u,height:u},children:[n.jsxs("svg",{className:"w-full h-full -rotate-90",children:[n.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),n.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),n.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[n.jsxs("span",{className:`font-bold text-white ${a>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),n.jsxs("span",{className:`text-xs ${d>=0?"text-blue-400":"text-orange-400"}`,children:[d>=0?"+":"",d.toFixed(0),"%"]})]})]}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[n.jsx(rJ,{className:"w-3 h-3 flex-shrink-0"}),n.jsx("span",{children:r("stats.perfectEstimate")})]}),g.length>0&&n.jsx("div",{className:`mt-2 ${a===4?"grid grid-cols-3 gap-x-6 gap-y-1":a===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:g.map(([w,b])=>n.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[n.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(w)||`${r("common.printer")} ${w}`}),n.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},w))})]})]})}function hrt({printDates:t,dateFrom:e,dateTo:a}){const{days:r,hourlyCounts:i,maxCount:s}=y.useMemo(()=>{const u=new Date(e+"T00:00:00"),m=new Date(a+"T00:00:00"),p=[],f=x=>`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,g=new Date(u);for(;g<=m;)p.push({key:f(g),label:g.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),g.setDate(g.getDate()+1);const w={};let b=0;return t.forEach(x=>{const S=Qa(x);if(!S)return;const C=`${`${S.getFullYear()}-${String(S.getMonth()+1).padStart(2,"0")}-${String(S.getDate()).padStart(2,"0")}`}-${S.getHours()}`;w[C]=(w[C]||0)+1,w[C]>b&&(b=w[C])}),{days:p,hourlyCounts:w,maxCount:Math.max(1,b)}},[t,e,a]),o=u=>{if(u===0)return"bg-bambu-dark";const m=u/s;return m<=.25?"bg-bambu-green/30":m<=.5?"bg-bambu-green/50":m<=.75?"bg-bambu-green/75":"bg-bambu-green"},l=20,c=2,d=80;return n.jsxs("div",{className:"w-full overflow-x-auto",children:[n.jsxs("div",{className:"inline-flex flex-col",style:{gap:c},children:[n.jsx("div",{className:"flex",style:{gap:c,marginLeft:d+4},children:nO.map((u,m)=>n.jsx("div",{className:"text-bambu-gray text-[10px] text-center",style:{width:l,visibility:m%2===0?"visible":"hidden"},children:u},m))}),r.map(u=>n.jsxs("div",{className:"flex items-center",style:{gap:c},children:[n.jsx("div",{className:"text-bambu-gray text-[10px] flex-shrink-0 truncate",style:{width:d},children:u.label}),Array.from({length:24},(m,p)=>{const f=i[`${u.key}-${p}`]||0;return n.jsx("div",{className:`rounded-sm ${o(f)}`,style:{width:l,height:l},title:`${u.label} ${nO[p]}: ${f} print${f!==1?"s":""}`},p)})]},u.key))]}),n.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray text-xs",children:[n.jsx("span",{children:"Less"}),n.jsxs("div",{className:"flex",style:{gap:c},children:[n.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:l,height:l}})]}),n.jsx("span",{children:"More"})]})]})}function frt({printDates:t,size:e=2,dateFrom:a,dateTo:r}){const i=y.useMemo(()=>a&&r?Math.max((new Date(r).getTime()-new Date(a).getTime())/864e5,0)+1:a?Math.max((Date.now()-new Date(a).getTime())/864e5,0)+1:1/0,[a,r]);if(i<=7&&a&&r)return n.jsx(hrt,{printDates:t,dateFrom:a,dateTo:r});const o=i===1/0?e===1?3:e===2?6:12:Math.max(1,Math.ceil(i/30));return n.jsx(nrt,{printDates:t,months:o})}function grt({stats:t,archives:e,printerMap:a}){const{t:r}=vt(),[i,s]=y.useState("weight"),[o,l]=y.useState("weight"),c=y.useMemo(()=>{const x=new Map;return t?.prints_by_printer&&Object.entries(t.prints_by_printer).forEach(([S,N])=>{const C=x.get(S)||{prints:0,weight:0,time:0};C.prints=N,x.set(S,C)}),e.forEach(S=>{if(!S.printer_id)return;const N=String(S.printer_id),C=x.get(N)||{prints:0,weight:0,time:0};C.weight+=S.filament_used_grams||0,C.time+=S.actual_time_seconds||S.print_time_seconds||0,t?.prints_by_printer||C.prints++,x.set(N,C)}),Array.from(x.entries()).map(([S,N])=>({name:a.get(S)||`${r("common.printer")} ${S}`,value:i==="prints"?N.prints:i==="weight"?Math.round(N.weight):Math.round(N.time/3600*10)/10})).sort((S,N)=>N.value-S.value)},[t,e,a,i,r]),d=y.useMemo(()=>{const x=Array.from({length:24},(S,N)=>({hour:N,label:nO[N],total:0,failures:0}));return e.forEach(S=>{if(!S.started_at)return;const N=Qa(S.started_at);if(!N)return;const C=N.getHours();x[C].total++,S.status==="failed"&&x[C].failures++}),x},[e]),u=y.useMemo(()=>{const x=f3.map(S=>({name:S.key,count:0}));return e.forEach(S=>{const N=S.actual_time_seconds||S.print_time_seconds;if(!(!N||N<=0)){for(let C=0;C{const x=[0,0,0,0,0,0,0],S=new Set;e.forEach(C=>{const P=Qa(C.created_at)||new Date(C.created_at);let T=P.getDay()-1;T<0&&(T=6),o==="prints"?x[T]++:o==="weight"?x[T]+=C.filament_used_grams||0:x[T]+=(C.actual_time_seconds||C.print_time_seconds||0)/3600;const j=new Date(P);j.setDate(P.getDate()-(P.getDay()+6)%7),S.add(`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}-${String(j.getDate()).padStart(2,"0")}`)});const N=Math.max(S.size,1);return drt.map((C,P)=>({name:C,avg:Math.round(x[P]/N*10)/10}))},[e,o]),p=x=>({unit:x==="weight"?"g":x==="time"?"h":"",color:x==="weight"?"#00ae42":x==="time"?"#3b82f6":"#f59e0b"}),f=p(i),g=r(i==="weight"?"stats.filamentByWeight":i==="time"?"stats.hours":"common.prints"),w=p(o),b=r(o==="weight"?"stats.avgWeight":o==="time"?"stats.avgTime":"stats.avgPrints");return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printsByPrinter")}),n.jsx(ST,{value:i,onChange:s})]}),c.length>0?n.jsx(au,{width:"100%",height:Math.max(140,c.length*40),children:n.jsxs(Q1,{data:c,layout:"vertical",margin:{left:10},children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),n.jsx(Fm,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),n.jsx(ru,{contentStyle:hN,formatter:x=>[i==="weight"?yh(Number(x??0)):`${x??0}${f.unit}`,g]}),n.jsx($x,{dataKey:"value",fill:f.color,radius:[0,4,4,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noPrinterData")})]}),n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printDuration")}),e.length>0?n.jsx(au,{width:"100%",height:160,children:n.jsxs(Q1,{data:u,children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),n.jsx(ru,{contentStyle:hN}),n.jsx($x,{dataKey:"count",name:r("common.prints"),fill:"#00ae42",radius:[4,4,0,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printHabits")}),n.jsx(ST,{value:o,onChange:l})]}),e.length>0?n.jsx(au,{width:"100%",height:160,children:n.jsxs(Q1,{data:m,children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:11},unit:w.unit}),n.jsx(ru,{contentStyle:hN,formatter:x=>[`${x??0}${w.unit}`,b]}),n.jsx($x,{dataKey:"avg",fill:w.color,radius:[4,4,0,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printTimeOfDay")}),e.length>0?n.jsx(au,{width:"100%",height:160,children:n.jsxs(Q1,{data:d,children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),n.jsx(ru,{contentStyle:hN}),n.jsx($x,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),n.jsx($x,{dataKey:"failures",name:r("stats.failed"),fill:"#ef4444",radius:[2,2,0,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]})]})]})}function brt({archives:t,currency:e,dateFrom:a,dateTo:r}){const{t:i}=vt();return!t||t.length===0?n.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):n.jsx(irt,{archives:t,currency:e,dateFrom:a,dateTo:r})}function xrt({size:t=1,dateFrom:e,dateTo:a,createdById:r}){const{t:i}=vt(),s=!!(e||a),{data:o,isLoading:l}=Qe({queryKey:["failureAnalysis",e,a,r??"all"],queryFn:()=>ne.getFailureAnalysis({...s?{dateFrom:e,dateTo:a}:{days:30},createdById:r})});if(l)return n.jsx("div",{className:"flex justify-center py-4",children:n.jsx(pt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!o||o.total_prints===0)return n.jsx("p",{className:"text-bambu-gray text-center py-4",children:i(s?"stats.noPrintDataInRange":"stats.noPrintDataLast30Days")});const c=t===1?5:t===2?8:999,d=Object.entries(o.failures_by_reason).sort(([,p],[,f])=>f-p),u=d.slice(0,c),m=d.length>c;return n.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[n.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[n.jsx("div",{className:"flex items-center gap-4",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ba,{className:`w-5 h-5 ${o.failure_rate>20?"text-status-error":o.failure_rate>10?"text-status-warning":"text-status-ok"}`}),n.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[o.failure_rate.toFixed(1),"%"]})]})}),n.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:i("stats.failedPrintsCount",{failed:o.failed_prints,total:o.total_prints})}),o.trend&&o.trend.length>=2&&n.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:n.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.jsx(US,{className:`w-4 h-4 ${o.trend[o.trend.length-1].failure_rate0&&n.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[n.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?i("stats.failureReasons"):i("stats.topFailureReasons")}),n.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:u.map(([p,f])=>n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:p||i("common.unknown")}),n.jsx("span",{className:"text-bambu-gray ml-2",children:f})]},p))}),m&&n.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("common.more",{count:d.length-c})})]})]})}function yrt({archives:t,currency:e}){const{t:a}=vt(),r=y.useMemo(()=>{const i=[];if(t.length===0)return i;const s=g=>{let w=null,b=0;return t.forEach(x=>{const S=g(x);S&&S>b&&(b=S,w=x)}),{archive:w,value:b}},o=s(g=>g.status==="completed"?g.actual_time_seconds:null);o.archive&&i.push({icon:Za,iconColor:"text-blue-400",label:a("stats.longestPrint"),value:hs(o.value),detail:o.archive.print_name||null});const l=s(g=>g.filament_used_grams);l.archive&&i.push({icon:Hn,iconColor:"text-orange-400",label:a("stats.heaviestPrint"),value:yh(l.value),detail:l.archive.print_name||null});const c=s(g=>g.cost);c.archive&&i.push({icon:rC,iconColor:"text-green-400",label:a("stats.mostExpensivePrint"),value:`${e}${c.value.toFixed(2)}`,detail:c.archive.print_name||null});const d=new Map;t.forEach(g=>{const w=Qa(g.created_at)||new Date(g.created_at),b=`${w.getFullYear()}-${String(w.getMonth()+1).padStart(2,"0")}-${String(w.getDate()).padStart(2,"0")}`;d.set(b,(d.get(b)||0)+1)});let u="",m=0;d.forEach((g,w)=>{g>m&&(m=g,u=w)}),m>1&&i.push({icon:vr,iconColor:"text-purple-400",label:a("stats.busiestDay"),value:`${m} ${a("common.prints")}`,detail:(()=>{const[g,w,b]=u.split("-").map(Number);return new Date(g,w-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(g=>g.status==="completed"||g.status==="failed").sort((g,w)=>new Date(w.completed_at||w.created_at).getTime()-new Date(g.completed_at||g.created_at).getTime());let f=0;for(const g of p)if(g.status==="completed")f++;else break;return f>0&&i.push({icon:Nc,iconColor:"text-yellow-400",label:a("stats.successStreak"),value:`${f}`,detail:f===1?a("stats.streakPrint"):a("stats.streakPrints",{count:f})}),i},[t,e,a]);return r.length===0?n.jsx("p",{className:"text-bambu-gray text-center py-4",children:a("stats.noArchiveData")}):n.jsx("div",{className:"space-y-3",children:r.map((i,s)=>n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:`p-1.5 rounded-lg bg-bambu-dark ${i.iconColor}`,children:n.jsx(i.icon,{className:"w-4 h-4"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"text-sm font-bold text-white",children:i.value}),i.detail&&n.jsx("span",{className:"text-xs text-bambu-gray truncate",children:i.detail})]})]})]},s))})}function vrt(){const{t}=vt(),{showToast:e}=ra(),{hasPermission:a,authEnabled:r}=un(),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(0),[u,m]=y.useState(0),[p,f]=y.useState(!1),[g,w]=y.useState(null),[b,x]=y.useState(!1),S=r&&a("stats:filter_by_user"),[N,C]=y.useState(()=>{try{const J=localStorage.getItem("bambusy-stats-timeframe");if(J){const A=JSON.parse(J);if(A.preset)return A}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[P,T]=y.useState(!1);y.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(N))},[N]);const j=y.useMemo(()=>N.preset==="custom"?{dateFrom:N.dateFrom,dateTo:N.dateTo}:lrt(N.preset),[N]);y.useEffect(()=>{const J=()=>{try{const E=localStorage.getItem("bambusy-dashboard-layout-v2");if(E){const z=JSON.parse(E);m(z.hidden?.length||0)}}catch{m(0)}};J(),window.addEventListener("storage",J);const A=setInterval(J,2e3);return()=>{window.removeEventListener("storage",J),clearInterval(A)}},[c]);const F=g!==null?g:void 0,{data:k,isLoading:M,isFetching:q,refetch:I}=Qe({queryKey:["archiveStats",j.dateFrom,j.dateTo,F??"all"],queryFn:()=>ne.getArchiveStats({dateFrom:j.dateFrom,dateTo:j.dateTo,createdById:F})}),{data:B}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),{data:R,isFetching:X,refetch:ee}=Qe({queryKey:["archivesSlim",j.dateFrom,j.dateTo,F??"all"],queryFn:()=>ne.getArchivesSlim(j.dateFrom,j.dateTo,F)}),{data:Q}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),{data:le}=Qe({queryKey:["users"],queryFn:ne.getUsers,enabled:S}),de=y.useMemo(()=>g===null?t("stats.allUsers","All Users"):g===-1?t("stats.noUser","No User (System)"):le?.find(J=>J.id===g)?.username??"?",[g,le,t]),ue=async J=>{l(!1),s(!0);try{const{blob:A,filename:E}=await ne.exportStats({format:J,days:90,createdById:F}),z=URL.createObjectURL(A),W=document.createElement("a");W.href=z,W.download=E,W.click(),URL.revokeObjectURL(z),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},Z=async()=>{f(!0);try{const J=await ne.recalculateCosts();await Promise.all([I(),ee()]),e(t("stats.recalculatedCosts",{count:J.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},oe=(q||X)&&!M,fe=Go(Q?.currency||"USD"),me=new Map(B?.map(J=>[String(J.id),J.name])||[]),be=y.useMemo(()=>R?.map(J=>J.created_at)||[],[R]);if(M)return n.jsx("div",{className:"p-4 md:p-8",children:n.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const H=[{id:"quick-stats",title:t("stats.quickStats"),component:n.jsx(urt,{stats:k,currency:fe}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:J=>n.jsx(mrt,{stats:k,printerMap:me,size:J}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:J=>n.jsx(prt,{stats:k,printerMap:me,size:J}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:J=>n.jsx(xrt,{size:J,dateFrom:j.dateFrom,dateTo:j.dateTo,createdById:F}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:J=>n.jsx(frt,{printDates:be,size:J,dateFrom:j.dateFrom,dateTo:j.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:n.jsx(yrt,{archives:R||[],currency:fe}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:n.jsx(grt,{stats:k,archives:R||[],printerMap:me}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:n.jsx(brt,{archives:R||[],currency:fe,dateFrom:j.dateFrom,dateTo:j.dateTo}),defaultSize:4}];return n.jsxs("div",{className:"p-4 md:p-8",children:[n.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[n.jsx(WZ,{className:"w-7 h-7 text-bambu-green"}),t("stats.title")]}),oe&&n.jsx(pt,{className:"w-5 h-5 text-bambu-green animate-spin"})]}),n.jsx("p",{className:"text-bambu-gray mt-1",children:t("stats.subtitle")})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&n.jsxs(Me,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[n.jsx(Ml,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),n.jsxs(Me,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(J=>J+1),e(t("stats.layoutReset"))},disabled:!a("settings:update"),title:a("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[n.jsx(vs,{className:"w-4 h-4"}),t("stats.resetLayout")]}),n.jsxs(Me,{variant:"secondary",onClick:Z,disabled:p||!a("archives:update_all"),title:a("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(pge,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),n.jsxs("div",{className:"relative",children:[n.jsxs(Me,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(sC,{className:"w-4 h-4"}),t("stats.exportStats")]}),o&&n.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:[n.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:()=>ue("csv"),children:[n.jsx(Bs,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),n.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:()=>ue("xlsx"),children:[n.jsx(sC,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),S&&le&&le.length>0&&n.jsxs("div",{className:"relative",children:[n.jsxs(Me,{variant:"secondary",onClick:()=>x(!b),children:[n.jsx(Sm,{className:"w-4 h-4"}),de,n.jsx(Da,{className:"w-3 h-3"})]}),b&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),n.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 p-2 max-h-64 overflow-y-auto",children:[n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===null?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(null),x(!1)},children:t("stats.allUsers","All Users")}),n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===-1?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(-1),x(!1)},children:t("stats.noUser","No User (System)")}),n.jsx("div",{className:"border-t border-bambu-dark-tertiary my-1"}),le.map(J=>n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===J.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(J.id),x(!1)},children:J.username},J.id))]})]})]}),n.jsxs("div",{className:"relative",children:[n.jsxs(Me,{variant:"secondary",onClick:()=>T(!P),children:[n.jsx(vr,{className:"w-4 h-4"}),t(`stats.timeframe.${N.preset}`),n.jsx(Da,{className:"w-3 h-3"})]}),P&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>T(!1)}),n.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2",children:[crt.map(J=>n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${N.preset===J?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{C({preset:J,dateFrom:void 0,dateTo:void 0}),T(!1)},children:t(`stats.timeframe.${J}`)},J)),n.jsx("div",{className:"border-t border-bambu-dark-tertiary my-2"}),n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${N.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>C(J=>({...J,preset:"custom"})),children:t("stats.timeframe.custom")}),N.preset==="custom"&&n.jsxs("div",{className:"mt-2 px-1 pb-1 space-y-2",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.from")}),n.jsx("input",{type:"date",value:N.dateFrom||"",max:N.dateTo||new Date().toISOString().split("T")[0],onChange:J=>C(A=>({...A,dateFrom:J.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.to")}),n.jsx("input",{type:"date",value:N.dateTo||"",min:N.dateFrom,max:new Date().toISOString().split("T")[0],onChange:J=>C(A=>({...A,dateTo:J.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),n.jsx(Me,{variant:"primary",onClick:()=>T(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),n.jsx(ort,{widgets:H,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function fN(t){return t.length<8?"tooShort":/[A-Z]/.test(t)?/[a-z]/.test(t)?/\d/.test(t)?/[^A-Za-z0-9]/.test(t)?null:"needsSpecial":"needsDigit":"needsLowercase":"needsUppercase"}function wrt(){const{t}=vt(),e=ta(),{showToast:a}=ra(),r=y.useRef(null),[i,s]=y.useState(null),{data:o,isLoading:l}=Qe({queryKey:["slicer-bundles"],queryFn:ne.listSlicerBundles}),c=lt({mutationFn:m=>ne.importSlicerBundle(m),onSuccess:m=>{e.invalidateQueries({queryKey:["slicer-bundles"]}),a(t("settings.slicerBundles.uploadSuccess",{defaultValue:"Imported {{name}}",name:m.printer_preset_name}),"success"),r.current&&(r.current.value="")},onError:m=>{a(t("settings.slicerBundles.uploadError",{defaultValue:"Bundle upload failed: {{message}}",message:m.message}),"error"),r.current&&(r.current.value="")}}),d=lt({mutationFn:m=>ne.deleteSlicerBundle(m),onSuccess:()=>{e.invalidateQueries({queryKey:["slicer-bundles"]}),s(null),a(t("settings.slicerBundles.deleteSuccess",{defaultValue:"Bundle removed"}),"success")},onError:m=>{a(t("settings.slicerBundles.deleteError",{defaultValue:"Bundle delete failed: {{message}}",message:m.message}),"error"),s(null)}}),u=m=>{const p=m.target.files?.[0];p&&c.mutate(p)};return n.jsxs(Tt,{children:[n.jsx(fa,{children:n.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[n.jsx(Hn,{className:"w-4 h-4 text-bambu-green"}),t("settings.slicerBundles.title",{defaultValue:"Slicer Bundles"})]})}),n.jsxs(Mt,{className:"space-y-3",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.slicerBundles.description",{defaultValue:'Import a Printer Preset Bundle (.bbscfg) exported from BambuStudio (File → Export → Export Preset Bundle → "Printer preset bundle"). Once imported, slice requests can pick presets from the bundle by name without re-uploading the JSON profile triplet.'})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{ref:r,type:"file",accept:".bbscfg,.zip,application/zip",onChange:u,className:"hidden",disabled:c.isPending}),n.jsx(Me,{variant:"primary",onClick:()=>r.current?.click(),disabled:c.isPending,children:c.isPending?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),t("settings.slicerBundles.uploading",{defaultValue:"Uploading…"})]}):n.jsxs(n.Fragment,{children:[n.jsx(Sr,{className:"w-4 h-4"}),t("settings.slicerBundles.uploadButton",{defaultValue:"Upload bundle"})]})})]}),l?n.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),t("settings.slicerBundles.loading",{defaultValue:"Loading bundles…"})]}):o&&o.length>0?n.jsx("ul",{className:"divide-y divide-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg",children:o.map(m=>n.jsxs("li",{className:"flex items-center justify-between px-3 py-2 hover:bg-bambu-dark-tertiary/30",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-sm text-white truncate",children:m.printer_preset_name}),n.jsxs("p",{className:"text-xs text-bambu-gray mt-0.5",children:[t("settings.slicerBundles.summary",{defaultValue:"{{processCount}} process · {{filamentCount}} filament presets",processCount:m.process.length,filamentCount:m.filament.length}),m.version&&` · v${m.version}`]})]}),n.jsx("button",{type:"button",onClick:()=>s(m),disabled:d.isPending,className:"ml-3 p-1.5 text-bambu-gray hover:text-red-400 disabled:opacity-40","aria-label":t("settings.slicerBundles.delete",{defaultValue:"Delete"}),children:n.jsx(ea,{className:"w-4 h-4"})})]},m.id))}):n.jsx("p",{className:"text-sm text-bambu-gray italic",children:t("settings.slicerBundles.empty",{defaultValue:"No bundles imported yet."})})]}),i&&n.jsx(ya,{title:t("settings.slicerBundles.confirmDeleteTitle",{defaultValue:"Remove this bundle?"}),message:t("settings.slicerBundles.confirmDeleteMessage",{defaultValue:'Slice requests that reference "{{name}}" will fail until the bundle is re-imported.',name:i.printer_preset_name}),confirmText:t("common.delete",{defaultValue:"Delete"}),variant:"danger",isLoading:d.isPending,onConfirm:()=>d.mutate(i.id),onCancel:()=>s(null)})]})}const yX=90,vX=365;function g3(t){return t?new Date(t).toLocaleString():"—"}function Srt(t){return new Date(t).getTime(){if(u.preventDefault(),!!r.trim()){c(!0);try{const m=await ne.createLongLivedCameraToken({name:r.trim(),expires_in_days:s});t(m),i(""),o(yX),a(e("cameraTokens.toast.created","Token created"))}catch(m){a(m instanceof Error?m.message:e("cameraTokens.toast.createFailed","Failed to create token"),"error")}finally{c(!1)}}};return n.jsxs("form",{onSubmit:d,className:"bg-bambu-dark-secondary rounded-lg p-4 mb-6 border border-bambu-dark-tertiary",children:[n.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:e("cameraTokens.create.title","Create new token")}),n.jsxs("div",{className:"grid gap-3 md:grid-cols-[1fr_140px_auto]",children:[n.jsx("input",{type:"text",maxLength:100,required:!0,value:r,onChange:u=>i(u.target.value),placeholder:e("cameraTokens.create.namePlaceholder","e.g. Home Assistant"),className:"px-3 py-2 bg-bambu-dark rounded-md text-white border border-bambu-dark-tertiary focus:border-bambu-green focus:outline-none","aria-label":e("cameraTokens.create.nameLabel","Token name")}),n.jsx("input",{type:"number",min:1,max:vX,required:!0,value:s,onChange:u=>{const m=Number(u.target.value);o(Math.min(Math.max(m,1),vX))},className:"px-3 py-2 bg-bambu-dark rounded-md text-white border border-bambu-dark-tertiary focus:border-bambu-green focus:outline-none","aria-label":e("cameraTokens.create.daysLabel","Days until expiry")}),n.jsxs("button",{type:"submit",disabled:l||!r.trim(),className:"flex items-center gap-2 px-4 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90 disabled:opacity-50 disabled:cursor-not-allowed",children:[n.jsx(en,{className:"w-4 h-4"}),e("cameraTokens.create.submit","Create")]})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("cameraTokens.create.hint","Maximum lifetime is 365 days. The token value is shown only once on creation — copy it now.")})]})}function _rt({token:t,onConfirm:e,onCancel:a}){const{t:r}=vt();return n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full border border-red-500/40",children:[n.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[n.jsx(ba,{className:"w-6 h-6 text-red-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:r("cameraTokens.confirmRevoke.title","Revoke this token?")}),n.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("cameraTokens.confirmRevoke.body",'Any device using "{{name}}" will lose access immediately. This cannot be undone.',{name:t.name})})]})]}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:a,className:"px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80",children:r("cameraTokens.confirmRevoke.cancel","Cancel")}),n.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600",children:r("cameraTokens.confirmRevoke.confirm","Revoke")})]})]})})}function Nrt({token:t,onClose:e}){const{t:a}=vt(),{showToast:r}=ra(),i=t.token??"",s=async()=>{if(i)try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(i);else{const o=document.createElement("textarea");o.value=i,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o);try{o.select(),document.execCommand("copy")}finally{document.body.removeChild(o)}}r(a("cameraTokens.toast.copied","Copied to clipboard"))}catch{r(a("cameraTokens.toast.copyFailed","Copy failed — select and copy manually"),"error")}};return n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4",children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-2xl w-full border border-bambu-green/40",children:[n.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[n.jsx(ba,{className:"w-6 h-6 text-yellow-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("cameraTokens.created.title","Token created — copy it now")}),n.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("cameraTokens.created.warning","This is the only time this token will be visible. After you close this dialog you can never view it again.")})]})]}),n.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[n.jsx("code",{className:"flex-1 px-3 py-2 bg-bambu-dark rounded-md text-bambu-green text-xs break-all font-mono select-all",children:i}),n.jsxs("button",{type:"button",onClick:s,className:"flex items-center gap-2 px-3 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90",children:[n.jsx(xi,{className:"w-4 h-4"}),a("cameraTokens.created.copy","Copy")]})]}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80",children:a("cameraTokens.created.dismiss","I've saved it")})})]})})}function Crt({token:t,showOwner:e,ownerLabel:a,onRevoke:r}){const{t:i}=vt(),s=Srt(t.expires_at);return n.jsxs("tr",{className:"border-b border-bambu-dark-tertiary last:border-b-0",children:[n.jsx("td",{className:"py-3 px-3 text-white",children:t.name}),e&&n.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:a}),n.jsxs("td",{className:"py-3 px-3 text-bambu-gray font-mono text-xs",children:[t.lookup_prefix,"…"]}),n.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:g3(t.created_at)}),n.jsxs("td",{className:`py-3 px-3 ${s?"text-red-400":"text-bambu-gray"}`,children:[g3(t.expires_at),s&&n.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs bg-red-500/20 text-red-300 rounded",children:i("cameraTokens.list.expired","Expired")})]}),n.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:g3(t.last_used_at)}),n.jsx("td",{className:"py-3 px-3 text-right",children:n.jsxs("button",{type:"button",onClick:()=>r(t.id),className:"inline-flex items-center gap-1 px-2 py-1 text-sm text-red-400 hover:text-red-300",title:i("cameraTokens.list.revoke","Revoke"),children:[n.jsx(ea,{className:"w-4 h-4"}),i("cameraTokens.list.revoke","Revoke")]})})]})}function wX({tokens:t,showOwner:e,userIdToName:a,onRevoke:r,emptyMessage:i}){const{t:s}=vt();return t.length===0?n.jsx("p",{className:"text-sm text-bambu-gray italic",children:i}):n.jsx("div",{className:"overflow-x-auto",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{className:"text-bambu-gray text-left border-b border-bambu-dark-tertiary",children:n.jsxs("tr",{children:[n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.name","Name")}),e&&n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.owner","Owner")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.prefix","Prefix")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.created","Created")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.expires","Expires")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.lastUsed","Last used")}),n.jsx("th",{className:"py-2 px-3"})]})}),n.jsx("tbody",{children:t.map(o=>n.jsx(Crt,{token:o,showOwner:e,ownerLabel:a?.get(o.user_id)??`#${o.user_id}`,onRevoke:r},o.id))})]})})}function Prt(){const{t}=vt(),{user:e,isAdmin:a}=un(),{showToast:r}=ra(),[i,s]=y.useState([]),[o,l]=y.useState([]),[c,d]=y.useState(new Map),[u,m]=y.useState(!0),[p,f]=y.useState(null),[g,w]=y.useState(null),b=async()=>{m(!0);try{const C=await ne.listMyLongLivedCameraTokens();if(s(C),a){const P=await ne.listAllLongLivedCameraTokens();l(P);try{const T=await ne.getUsers();d(new Map(T.map(j=>[j.id,j.username])))}catch{d(new Map)}}}catch(C){r(C instanceof Error?C.message:t("cameraTokens.toast.loadFailed","Failed to load tokens"),"error")}finally{m(!1)}};y.useEffect(()=>{b()},[a]);const x=async C=>{const P=[...i,...o].find(T=>T.id===C);P&&w(P)},S=async()=>{if(!g)return;const C=g.id;w(null);try{await ne.revokeLongLivedCameraToken(C),r(t("cameraTokens.toast.revoked","Token revoked")),await b()}catch(P){r(P instanceof Error?P.message:t("cameraTokens.toast.revokeFailed","Failed to revoke token"),"error")}},N=y.useMemo(()=>o.filter(C=>C.user_id!==e?.id),[o,e?.id]);return n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("cameraTokens.description","Long-lived tokens for embedding the camera stream into Home Assistant, Frigate, kiosks, or any other tool that needs a stable URL. Each token is camera-stream-only and can be revoked at any time.")}),n.jsx(krt,{onCreated:C=>{f(C),b()}}),n.jsxs("div",{className:"mb-6",children:[n.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:t("cameraTokens.list.myTitle","My tokens")}),u?n.jsx("p",{className:"text-sm text-bambu-gray",children:t("cameraTokens.loading","Loading…")}):n.jsx(wX,{tokens:i,onRevoke:x,emptyMessage:t("cameraTokens.list.empty","No tokens yet.")})]}),a&&n.jsxs("div",{children:[n.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:t("cameraTokens.list.allTitle","All users (admin view)")}),n.jsx(wX,{tokens:N,showOwner:!0,userIdToName:c,onRevoke:x,emptyMessage:t("cameraTokens.list.empty","No tokens yet.")})]}),p&&n.jsx(Nrt,{token:p,onClose:()=>f(null)}),g&&n.jsx(_rt,{token:g,onConfirm:()=>{S()},onCancel:()=>w(null)})]})}function Trt({plug:t,onEdit:e}){const{t:a}=vt(),r=ta(),{showToast:i}=ra(),[s,o]=y.useState(!1),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),{data:f,isLoading:g}=Qe({queryKey:["smart-plug-status",t.id],queryFn:()=>ne.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:w}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),b=w?.find(M=>M.id===t.printer_id),x=lt({mutationFn:M=>ne.controlSmartPlug(t.id,M),onMutate:async M=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const q=r.getQueryData(["smart-plug-status",t.id]),I=M==="on"?"ON":M==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],B=>({...B,state:I})),{previousStatus:q}},onError:(M,q,I)=>{I?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],I.previousStatus),i(a("smartPlugs.failedToTurn",{action:q,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),S=lt({mutationFn:M=>ne.updateSmartPlug(t.id,M),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=lt({mutationFn:()=>ne.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),C=f?.state==="ON",P=t.plug_type==="mqtt"&&f?.energy?.power!==null&&f?.energy?.power!==void 0,T=(f?.reachable??!1)||P,j=x.isPending,k=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const M=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${M}/`:`http://${M}/`})();return n.jsxs(n.Fragment,{children:[n.jsx(Tt,{className:"relative",children:n.jsxs(Mt,{className:"p-4",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[n.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?T?"bg-teal-500/20":"bg-red-500/20":T?C?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?n.jsx(FO,{className:`w-5 h-5 ${T?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?n.jsx(ES,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?n.jsx(ro,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):n.jsx(xc,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),n.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.plug_type==="rest"?t.rest_on_url??t.rest_off_url??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.plug_type==="rest"?t.rest_on_url||t.rest_off_url:t.ip_address})]})]}),n.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[g?n.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?n.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[n.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&&n.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?n.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[n.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),n.jsx("span",{className:T?C?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?f?.state||"?":a("smartPlugs.offline")})]}):t.plug_type==="rest"?n.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[n.jsx("span",{className:"px-1 py-0.5 bg-purple-500/20 text-purple-400 text-[10px] font-medium rounded",children:"REST"}),n.jsx("span",{className:T?C?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?f?.state||"?":a("smartPlugs.offline")})]}):T?n.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[n.jsx(Dh,{className:"w-4 h-4 text-status-ok"}),n.jsx("span",{className:C?"text-status-ok":"text-bambu-gray",children:f?.state||a("smartPlugs.unknown")})]}):n.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[n.jsx(pu,{className:"w-4 h-4"}),n.jsx("span",{children:a("smartPlugs.offline")})]}),k&&n.jsxs("a",{href:k,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:a("smartPlugs.openPlugAdminPage"),children:[n.jsx(En,{className:"w-3 h-3"}),a("smartPlugs.admin")]})]})]}),b&&n.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[n.jsxs("span",{className:"text-xs text-bambu-gray",children:[a("smartPlugs.linkedTo")," "]}),n.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&n.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&n.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:[n.jsx(Ml,{className:"w-3 h-3"}),a("smartPlugs.monitorOnly")]}),t.power_alert_enabled&&n.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:[n.jsx(Th,{className:"w-3 h-3"}),a("smartPlugs.alerts")]}),t.schedule_enabled&&n.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:[n.jsx(vr,{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?a("smartPlugs.scheduleOn",{time:t.schedule_on_time}):a("smartPlugs.scheduleOff",{time:t.schedule_off_time})]})]}),t.plug_type!=="mqtt"&&n.jsxs("div",{className:"flex gap-2 mb-3",children:[n.jsxs(Me,{size:"sm",variant:C?"primary":"secondary",disabled:!T||j,onClick:()=>c(!0),className:"flex-1",children:[j?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Su,{className:"w-4 h-4"}),a("smartPlugs.on")]}),n.jsxs(Me,{size:"sm",variant:C?"secondary":"primary",disabled:!T||j,onClick:()=>u(!0),className:"flex-1",children:[j?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(IS,{className:"w-4 h-4"}),a("smartPlugs.off")]})]}),t.plug_type==="mqtt"&&f?.energy&&n.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[f.energy.power!==null&&f.energy.power!==void 0&&n.jsxs("div",{className:"flex-1 text-center",children:[n.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(f.energy.power),"W"]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.power")})]}),f.energy.today!==null&&f.energy.today!==void 0&&n.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-lg font-semibold text-white",children:f.energy.today.toFixed(3)}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.kwhToday")})]})]}),n.jsxs("button",{onClick:()=>p(!m),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(mu,{className:"w-4 h-4"}),t.plug_type==="mqtt"?a("smartPlugs.settings"):a("smartPlugs.automationSettings")]}),n.jsx("span",{children:m?"-":"+"})]}),m&&n.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(DS,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.showInSwitchbar")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.quickAccessSidebar")})]})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:M=>S.mutate({show_in_switchbar:M.target.checked}),className:"sr-only peer"}),n.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"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.enabled")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.enableAutomation")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.enabled,onChange:M=>S.mutate({enabled:M.target.checked}),className:"sr-only peer"}),n.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"})]})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOn")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOnDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:M=>S.mutate({auto_on:M.target.checked}),className:"sr-only peer"}),n.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"})]})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOff")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOffDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:M=>S.mutate({auto_off:M.target.checked}),className:"sr-only peer"}),n.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&&n.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOffPersistent")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOffPersistentDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_off_persistent,onChange:M=>S.mutate({auto_off_persistent:M.target.checked}),className:"sr-only peer"}),n.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&&n.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white mb-2",children:a("smartPlugs.turnOffDelayMode")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[n.jsx(Za,{className:"w-4 h-4"}),a("smartPlugs.time")]}),n.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[n.jsx(zS,{className:"w-4 h-4"}),a("smartPlugs.temp")]})]})]}),t.off_delay_mode==="time"?n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("smartPlugs.delayMinutes")}),n.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:M=>S.mutate({off_delay_minutes:parseInt(M.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"})]}):n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("smartPlugs.tempThreshold")}),n.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:M=>S.mutate({off_temp_threshold:parseInt(M.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"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("smartPlugs.tempThresholdDescription")})]})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOffAfterDrying")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOffAfterDryingDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_off_after_drying,onChange:M=>S.mutate({auto_off_after_drying:M.target.checked}),className:"sr-only peer"}),n.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_after_drying&&n.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary",children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("smartPlugs.delayAfterDryingMinutes")}),n.jsx("input",{type:"number",min:"0",max:"120",value:t.off_delay_after_drying_minutes,onChange:M=>S.mutate({off_delay_after_drying_minutes:parseInt(M.target.value)||10}),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"})]})]}),n.jsxs("div",{className:"flex gap-2 pt-2",children:[n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[n.jsx(fc,{className:"w-4 h-4"}),a("smartPlugs.edit")]}),n.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:n.jsx(ea,{className:"w-4 h-4"})})]})]})]})}),s&&n.jsx(ya,{title:a("smartPlugs.deleteSmartPlug"),message:a("smartPlugs.deleteConfirm",{name:t.name}),confirmText:a("smartPlugs.delete"),variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&n.jsx(ya,{title:a("smartPlugs.turnOnSmartPlug"),message:a("smartPlugs.turnOnConfirm",{name:t.name}),confirmText:a("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{x.mutate("on"),c(!1)},onCancel:()=>c(!1)}),d&&n.jsx(ya,{title:a("smartPlugs.turnOffSmartPlug"),message:a("smartPlugs.turnOffConfirm",{name:t.name}),confirmText:a("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{x.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function Art({plug:t,onClose:e}){const{t:a}=vt(),r=ta(),i=!!t,[s,o]=y.useState(t?.plug_type||"tasmota"),[l,c]=y.useState(t?.name||""),[d,u]=y.useState(t?.ip_address||""),[m,p]=y.useState(t?.username||""),[f,g]=y.useState(t?.password||""),[w,b]=y.useState(t?.ha_entity_id||""),[x,S]=y.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,C]=y.useState(t?.mqtt_power_path||""),[P,T]=y.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[j,F]=y.useState(t?.mqtt_energy_topic||""),[k,M]=y.useState(t?.mqtt_energy_path||""),[q,I]=y.useState((t?.mqtt_energy_multiplier??1).toString()),[B,R]=y.useState(t?.mqtt_state_topic||""),[X,ee]=y.useState(t?.mqtt_state_path||""),[Q,le]=y.useState(t?.mqtt_state_on_value||""),[de,ue]=y.useState(t?.rest_on_url||""),[Z,oe]=y.useState(t?.rest_on_body||""),[fe,me]=y.useState(t?.rest_off_url||""),[be,H]=y.useState(t?.rest_off_body||""),[J,A]=y.useState(t?.rest_method||"POST"),[E,z]=y.useState(t?.rest_headers||""),[W,O]=y.useState(t?.rest_status_url||""),[re,U]=y.useState(t?.rest_status_path||""),[V,K]=y.useState(t?.rest_status_on_value||""),[Y,ie]=y.useState(t?.rest_power_url||""),[se,pe]=y.useState(t?.rest_power_path||""),[ce,he]=y.useState((t?.rest_power_multiplier??1).toString()),[$,L]=y.useState(t?.rest_energy_url||""),[ae,ge]=y.useState(t?.rest_energy_path||""),[xe,Se]=y.useState((t?.rest_energy_multiplier??1).toString()),[Te,ve]=y.useState(t?.ha_power_entity||""),[we,ze]=y.useState(t?.ha_energy_today_entity||""),[De,Le]=y.useState(t?.ha_energy_total_entity||""),[Re,We]=y.useState(""),[Be,ot]=y.useState(""),[Ee,it]=y.useState(!1),Ne=y.useRef(null),[Ze,Ye]=y.useState(""),[Ae,Ie]=y.useState(!1),et=y.useRef(null),[Ke,Pe]=y.useState(""),[at,rt]=y.useState(!1),At=y.useRef(null),[Bt,gt]=y.useState(""),[Qt,Xt]=y.useState(!1),ia=y.useRef(null),[da,ut]=y.useState(t?.printer_id||null),[_t,Ct]=y.useState(null),[dt,Nt]=y.useState(null),[Oe,je]=y.useState(t?.power_alert_enabled||!1),[Ve,Je]=y.useState(t?.power_alert_high?.toString()||""),[Fe,bt]=y.useState(t?.power_alert_low?.toString()||""),[Ce,$e]=y.useState(t?.schedule_enabled||!1),[nt,st]=y.useState(t?.schedule_on_time||""),[tt,wt]=y.useState(t?.schedule_off_time||""),[kt,Ue]=y.useState(t?.show_in_switchbar||!1),[qe,Dt]=y.useState(t?.show_on_printer_card??!0),[It,Ft]=y.useState(!1),[Xe,Ge]=y.useState({scanned:0,total:0}),[Gt,ca]=y.useState([]),ma=y.useRef(null),{data:Jt}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),{data:pa}=Qe({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:Pa}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),tn=!!(Pa?.ha_enabled&&Pa?.ha_url&&Pa?.ha_token);y.useEffect(()=>{const Ot=setTimeout(()=>{ot(Re)},300);return()=>clearTimeout(Ot)},[Re]),y.useEffect(()=>{const Ot=Ua=>{Ne.current&&!Ne.current.contains(Ua.target)&&it(!1),et.current&&!et.current.contains(Ua.target)&&Ie(!1),At.current&&!At.current.contains(Ua.target)&&rt(!1),ia.current&&!ia.current.contains(Ua.target)&&Xt(!1)};return document.addEventListener("mousedown",Ot),()=>document.removeEventListener("mousedown",Ot)},[]);const{data:In,isLoading:$a,error:Br}=Qe({queryKey:["ha-entities",Be],queryFn:()=>ne.getHAEntities(Be||void 0),enabled:s==="homeassistant"&&tn,retry:!1,staleTime:0}),{data:Ra}=Qe({queryKey:["ha-sensor-entities"],queryFn:ne.getHASensorEntities,enabled:s==="homeassistant"&&tn,retry:!1,staleTime:0});y.useEffect(()=>{const Ot=Ua=>{Ua.key==="Escape"&&e()};return window.addEventListener("keydown",Ot),()=>{window.removeEventListener("keydown",Ot),ma.current&&clearInterval(ma.current)}},[e]);const Vn=async()=>{Ft(!0),ca([]),Ge({scanned:0,total:0}),Nt(null);try{await ne.startTasmotaScan();const Ot=async()=>{try{const Ua=await ne.getTasmotaScanStatus();Ge({scanned:Ua.scanned,total:Ua.total});const ln=await ne.getDiscoveredTasmotaDevices();ca(ln),Ua.running||(Ft(!1),ma.current&&(clearInterval(ma.current),ma.current=null))}catch(Ua){console.error("Polling error:",Ua)}};await Ot(),ma.current=setInterval(Ot,500)}catch(Ot){Ft(!1);const Ua=Ot instanceof Error?Ot.message:typeof Ot=="string"?Ot:JSON.stringify(Ot);Nt(Ua||a("smartPlugs.failedToStartScan"))}},br=async()=>{try{await ne.stopTasmotaScan()}catch{}Ft(!1),ma.current&&(clearInterval(ma.current),ma.current=null)},xn=Ot=>{u(Ot.ip_address),c(Ot.name),Ct(null)},xr=lt({mutationFn:()=>ne.testSmartPlugConnection(d,m||null,f||null),onSuccess:Ot=>{Ct(Ot),Nt(null),!l&&Ot.device_name&&c(Ot.device_name)},onError:Ot=>{Ct(null),Nt(Ot.message)}}),ci=lt({mutationFn:Ot=>ne.createSmartPlug(Ot),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Ot=>{Nt(Ot.message)}}),ts=lt({mutationFn:Ot=>ne.updateSmartPlug(t.id,Ot),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Ot=>{Nt(Ot.message)}}),Pu=Jt?.filter(Ot=>s==="tasmota"?!pa?.some(ln=>ln.printer_id===Ot.id&&ln.id!==t?.id&&ln.plug_type==="tasmota"):!0),Sd=Ot=>{if(Ot.preventDefault(),Nt(null),!l.trim()){Nt(a("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Nt("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!w){Nt(a("smartPlugs.entityRequired"));return}if(s==="mqtt"){const ln=x.trim(),Ht=j.trim(),Lc=B.trim();if(!ln&&!Ht&&!Lc){Nt(a("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!de.trim()&&!fe.trim()){Nt(a("smartPlugs.restUrlRequired"));return}const Ua={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?d.trim():null,ha_entity_id:s==="homeassistant"?w:null,ha_power_entity:s==="homeassistant"&&Te||null,ha_energy_today_entity:s==="homeassistant"&&we||null,ha_energy_total_entity:s==="homeassistant"&&De||null,mqtt_power_topic:s==="mqtt"&&x.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(P)||1,mqtt_energy_topic:s==="mqtt"&&j.trim()||null,mqtt_energy_path:s==="mqtt"&&k.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(q)||1,mqtt_state_topic:s==="mqtt"&&B.trim()||null,mqtt_state_path:s==="mqtt"&&X.trim()||null,mqtt_state_on_value:s==="mqtt"&&Q.trim()||null,rest_on_url:s==="rest"&&de.trim()||null,rest_on_body:s==="rest"&&Z.trim()||null,rest_off_url:s==="rest"&&fe.trim()||null,rest_off_body:s==="rest"&&be.trim()||null,rest_method:s==="rest"?J:null,rest_headers:s==="rest"&&E.trim()||null,rest_status_url:s==="rest"&&W.trim()||null,rest_status_path:s==="rest"&&re.trim()||null,rest_status_on_value:s==="rest"&&V.trim()||null,rest_power_url:s==="rest"&&Y.trim()||null,rest_power_path:s==="rest"&&se.trim()||null,rest_power_multiplier:s==="rest"&&parseFloat(ce)||1,rest_energy_url:s==="rest"&&$.trim()||null,rest_energy_path:s==="rest"&&ae.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(xe)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:da,power_alert_enabled:Oe,power_alert_high:Ve?parseFloat(Ve):null,power_alert_low:Fe?parseFloat(Fe):null,schedule_enabled:Ce,schedule_on_time:nt||null,schedule_off_time:tt||null,show_in_switchbar:kt,show_on_printer_card:qe};i?ts.mutate(Ua):ci.mutate(Ua)},Il=ci.isPending||ts.isPending;return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:n.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:Ot=>Ot.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a(i?"smartPlugs.editTitle":"smartPlugs.addTitle")}),n.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:n.jsx($t,{className:"w-5 h-5"})})]}),n.jsxs("form",{onSubmit:Sd,className:"p-6 space-y-4 overflow-y-auto",children:[dt&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:dt}),!i&&n.jsxs("div",{className:"flex gap-2 mb-2",children:[n.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(xc,{className:"w-4 h-4"}),"Tasmota"]}),n.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(ES,{className:"w-4 h-4"}),"HA"]}),n.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(FO,{className:"w-4 h-4"}),"MQTT"]}),n.jsxs("button",{type:"button",onClick:()=>{o("rest"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="rest"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(ro,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&n.jsxs("div",{className:"space-y-3",children:[It?n.jsxs(Me,{type:"button",variant:"secondary",onClick:br,className:"w-full",children:[n.jsx($t,{className:"w-4 h-4"}),a("smartPlugs.stopScanning")]}):n.jsxs(Me,{type:"button",variant:"primary",onClick:Vn,className:"w-full",children:[n.jsx(gn,{className:"w-4 h-4"}),a("smartPlugs.discoverTasmota")]}),It&&Xe.total>0&&n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[n.jsx("span",{children:a("smartPlugs.addSmartPlug.scanningNetwork")}),n.jsxs("span",{children:[Xe.scanned," / ",Xe.total]})]}),n.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:n.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Xe.scanned/Xe.total*100}%`}})})]}),Gt.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.foundDevices",{count:Gt.length})}),n.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Gt.map(Ot=>n.jsxs("button",{type:"button",onClick:()=>xn(Ot),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:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(xc,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:Ot.name}),n.jsx("p",{className:"text-xs text-bambu-gray",children:Ot.ip_address})]})]}),Ot.state&&n.jsxs("span",{className:`flex items-center gap-1 text-xs ${Ot.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[n.jsx(Su,{className:"w-3 h-3"}),Ot.state]})]},Ot.ip_address))})]}),!It&&Gt.length===0&&Xe.total>0&&n.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:a("smartPlugs.noDevicesFound")})]}),s==="homeassistant"&&n.jsxs("div",{className:"space-y-3",children:[!tn&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[a("smartPlugs.haNotConfigured")," ",n.jsx("span",{className:"font-medium",children:a("smartPlugs.haSettingsPath")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:a("smartPlugs.selectEntity")}),n.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:n.jsx("option",{children:a("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),tn&&n.jsxs(n.Fragment,{children:[$a&&n.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[n.jsx(pt,{className:"w-5 h-5 animate-spin mr-2"}),a("smartPlugs.loadingEntities")]}),Br&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:a("smartPlugs.failedToLoadEntities",{error:Br.message})}),(()=>{const Ot=pa?.filter(Ht=>Ht.ha_entity_id&&Ht.id!==t?.id).map(Ht=>Ht.ha_entity_id)||[],Ua=(In||[]).filter(Ht=>!Ot.includes(Ht.entity_id)),ln=In?.find(Ht=>Ht.entity_id===w);return n.jsxs("div",{ref:Ne,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.selectEntity")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:Ee?Re:ln?`${ln.friendly_name} (${ln.entity_id})`:"",onChange:Ht=>{We(Ht.target.value),Ee||it(!0)},onFocus:()=>{it(!0),We("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),w&&!Ee&&n.jsx("button",{type:"button",onClick:()=>{b(""),We("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),$a&&n.jsx(pt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),Ee&&n.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:[$a&&n.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),a("smartPlugs.loading")]}),!$a&&Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Be?a("smartPlugs.noEntitiesMatching",{search:Be}):a("smartPlugs.noEntitiesAvailable")}),!$a&&Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{b(Ht.entity_id),it(!1),We(""),l||c(Ht.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Ht.entity_id===w?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[n.jsx("span",{children:Ht.entity_id}),n.jsx("span",{className:Ht.state==="on"?"text-bambu-green":"",children:Ht.state})]})]},Ht.entity_id))]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Be?a("smartPlugs.searchingEntities",{count:Ua.length}):a("smartPlugs.showingEntities",{count:Ua.length})})]})})(),w&&Ra&&Ra.length>0&&n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white font-medium mb-1",children:a("smartPlugs.energyMonitoringOptional")}),n.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:a("smartPlugs.energyMonitoringHint")})]}),(()=>{const Ot=Ra.filter(Ht=>Ht.unit_of_measurement==="W"||Ht.unit_of_measurement==="kW"||Ht.unit_of_measurement==="mW"),Ua=Ze?Ot.filter(Ht=>Ht.entity_id.toLowerCase().includes(Ze.toLowerCase())||Ht.friendly_name.toLowerCase().includes(Ze.toLowerCase())):Ot,ln=Ra.find(Ht=>Ht.entity_id===Te);return n.jsxs("div",{ref:et,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.powerSensorW")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:Ae?Ze:ln?`${ln.friendly_name} (${ln.state} ${ln.unit_of_measurement})`:"",onChange:Ht=>{Ye(Ht.target.value),Ae||Ie(!0)},onFocus:()=>{Ie(!0),Ye("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Te&&!Ae&&n.jsx("button",{type:"button",onClick:()=>{ve(""),Ye("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Ae&&n.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:[n.jsx("button",{type:"button",onClick:()=>{ve(""),Ie(!1),Ye("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:a("smartPlugs.none")}),Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{ve(Ht.entity_id),Ie(!1),Ye("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ht.entity_id===Te?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ht.entity_id," • ",Ht.state," ",Ht.unit_of_measurement]})]},Ht.entity_id)),Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:a("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const Ot=Ra.filter(Ht=>Ht.unit_of_measurement==="kWh"||Ht.unit_of_measurement==="Wh"||Ht.unit_of_measurement==="MWh"),Ua=Ke?Ot.filter(Ht=>Ht.entity_id.toLowerCase().includes(Ke.toLowerCase())||Ht.friendly_name.toLowerCase().includes(Ke.toLowerCase())):Ot,ln=Ra.find(Ht=>Ht.entity_id===we);return n.jsxs("div",{ref:At,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.energyTodayKwh")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:at?Ke:ln?`${ln.friendly_name} (${ln.state} ${ln.unit_of_measurement})`:"",onChange:Ht=>{Pe(Ht.target.value),at||rt(!0)},onFocus:()=>{rt(!0),Pe("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),we&&!at&&n.jsx("button",{type:"button",onClick:()=>{ze(""),Pe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),at&&n.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:[n.jsx("button",{type:"button",onClick:()=>{ze(""),rt(!1),Pe("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:a("smartPlugs.none")}),Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{ze(Ht.entity_id),rt(!1),Pe("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ht.entity_id===we?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ht.entity_id," • ",Ht.state," ",Ht.unit_of_measurement]})]},Ht.entity_id)),Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:a("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const Ot=Ra.filter(Ht=>Ht.unit_of_measurement==="kWh"||Ht.unit_of_measurement==="Wh"||Ht.unit_of_measurement==="MWh"),Ua=Bt?Ot.filter(Ht=>Ht.entity_id.toLowerCase().includes(Bt.toLowerCase())||Ht.friendly_name.toLowerCase().includes(Bt.toLowerCase())):Ot,ln=Ra.find(Ht=>Ht.entity_id===De);return n.jsxs("div",{ref:ia,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.totalEnergyKwh")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:Qt?Bt:ln?`${ln.friendly_name} (${ln.state} ${ln.unit_of_measurement})`:"",onChange:Ht=>{gt(Ht.target.value),Qt||Xt(!0)},onFocus:()=>{Xt(!0),gt("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),De&&!Qt&&n.jsx("button",{type:"button",onClick:()=>{Le(""),gt("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Qt&&n.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:[n.jsx("button",{type:"button",onClick:()=>{Le(""),Xt(!1),gt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:a("smartPlugs.none")}),Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{Le(Ht.entity_id),Xt(!1),gt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ht.entity_id===De?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ht.entity_id," • ",Ht.state," ",Ht.unit_of_measurement]})]},Ht.entity_id)),Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:a("smartPlugs.noMatchingSensors")})]})]})})()]})]})]}),s==="mqtt"&&n.jsxs("div",{className:"space-y-3",children:[!Pa?.mqtt_broker&&n.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[a("smartPlugs.mqttNotConfigured")," ",n.jsx("span",{className:"font-medium",children:a("smartPlugs.mqttSettingsPath")})," ",a("smartPlugs.mqttNotConfiguredSuffix")]}),Pa?.mqtt_broker&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[n.jsx("p",{className:"font-medium mb-1",children:a("smartPlugs.monitorOnly")}),n.jsx("p",{className:"text-xs opacity-80",children:a("smartPlugs.mqttMonitorOnlyDescription")})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-white font-medium text-sm",children:a("smartPlugs.powerMonitoring")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.topic")}),n.jsx("input",{type:"text",value:x,onChange:Ot=>S(Ot.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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.jsonPath")}),n.jsx("input",{type:"text",value:N,onChange:Ot=>C(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.multiplier")}),n.jsx("input",{type:"text",value:P,onChange:Ot=>T(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:a("smartPlugs.mqttPowerHint")})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.energyMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.topic")}),n.jsx("input",{type:"text",value:j,onChange:Ot=>F(Ot.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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.jsonPath")}),n.jsx("input",{type:"text",value:k,onChange:Ot=>M(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.multiplier")}),n.jsx("input",{type:"text",value:q,onChange:Ot=>I(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:a("smartPlugs.mqttEnergyHint")})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.stateMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.topic")}),n.jsx("input",{type:"text",value:B,onChange:Ot=>R(Ot.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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.jsonPath")}),n.jsx("input",{type:"text",value:X,onChange:Ot=>ee(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.onValue")}),n.jsx("input",{type:"text",value:Q,onChange:Ot=>le(Ot.target.value),placeholder:a("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:a("smartPlugs.mqttStateHint")})]})]})]}),s==="rest"&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-white font-medium text-sm",children:a("smartPlugs.restControl")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restMethod")}),n.jsxs("select",{value:J,onChange:Ot=>A(Ot.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:"GET",children:"GET"}),n.jsx("option",{value:"POST",children:"POST"}),n.jsx("option",{value:"PUT",children:"PUT"}),n.jsx("option",{value:"PATCH",children:"PATCH"})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restOnUrl")}),n.jsx("input",{type:"text",value:de,onChange:Ot=>{ue(Ot.target.value),Ct(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",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"})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restOnBody")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:Z,onChange:Ot=>oe(Ot.target.value),placeholder:a("smartPlugs.restBodyHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restOffUrl")}),n.jsx("input",{type:"text",value:fe,onChange:Ot=>{me(Ot.target.value),Ct(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",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"})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restOffBody")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:be,onChange:Ot=>H(Ot.target.value),placeholder:a("smartPlugs.restBodyHint"),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"})]})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.restHeaders")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("div",{children:n.jsx("textarea",{value:E,onChange:Ot=>z(Ot.target.value),placeholder:a("smartPlugs.restHeadersHint"),rows:2,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 font-mono text-sm"})})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.stateMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restStatusUrl")}),n.jsx("input",{type:"text",value:W,onChange:Ot=>O(Ot.target.value),placeholder:a("smartPlugs.restStatusHint"),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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restStatusPath")}),n.jsx("input",{type:"text",value:re,onChange:Ot=>U(Ot.target.value),placeholder:a("smartPlugs.restPathHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restStatusOnValue")}),n.jsx("input",{type:"text",value:V,onChange:Ot=>K(Ot.target.value),placeholder:"ON",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"})]})]})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.energyMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restPowerUrl")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:Y,onChange:Ot=>ie(Ot.target.value),placeholder:a("smartPlugs.restPowerUrlHint"),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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restPowerPath")}),n.jsx("input",{type:"text",value:se,onChange:Ot=>pe(Ot.target.value),placeholder:a("smartPlugs.restPathHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restPowerMultiplier")}),n.jsx("input",{type:"text",value:ce,onChange:Ot=>he(Ot.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"})]})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restEnergyUrl")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:$,onChange:Ot=>L(Ot.target.value),placeholder:a("smartPlugs.restEnergyUrlHint"),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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restEnergyPath")}),n.jsx("input",{type:"text",value:ae,onChange:Ot=>ge(Ot.target.value),placeholder:a("smartPlugs.restPathHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restEnergyMultiplier")}),n.jsx("input",{type:"text",value:xe,onChange:Ot=>Se(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.restEnergyHint")})]}),(de.trim()||fe.trim())&&n.jsx("div",{className:"flex gap-2",children:n.jsxs(Me,{type:"button",variant:"secondary",onClick:async()=>{Ct(null);try{const Ot=de.trim()||fe.trim(),Ua=await ne.testRESTConnection(Ot,J,E.trim()||null);Ct({success:Ua.success}),Ua.success||Nt(Ua.error||a("smartPlugs.addSmartPlug.connectionFailed"))}catch{Ct({success:!1}),Nt(a("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[n.jsx(Dh,{className:"w-4 h-4"}),a("smartPlugs.testConnection")]})}),_t&&n.jsxs("div",{className:`flex items-center gap-2 text-sm ${_t.success?"text-green-400":"text-red-400"}`,children:[_t.success?n.jsx(fn,{className:"w-4 h-4"}):n.jsx(pu,{className:"w-4 h-4"}),_t.success?a("smartPlugs.connectionSuccess"):a("smartPlugs.addSmartPlug.connectionFailed")]})]}),s==="tasmota"&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.ipAddress")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{type:"text",value:d,onChange:Ot=>{u(Ot.target.value),Ct(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"}),n.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>xr.mutate(),disabled:!d.trim()||xr.isPending,children:[xr.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Dh,{className:"w-4 h-4"}),a("smartPlugs.test")]})]})]}),s==="tasmota"&&_t&&n.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${_t.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:_t.success?n.jsxs(n.Fragment,{children:[n.jsx(fn,{className:"w-5 h-5"}),n.jsxs("div",{children:[n.jsx("p",{className:"font-medium",children:a("smartPlugs.connectedResult")}),n.jsxs("p",{className:"text-sm opacity-80",children:[_t.device_name&&a("smartPlugs.deviceLabel",{name:_t.device_name}),a("smartPlugs.stateLabel",{state:_t.state})]})]})]}):n.jsxs(n.Fragment,{children:[n.jsx(pu,{className:"w-5 h-5"}),n.jsx("span",{children:a("smartPlugs.addSmartPlug.connectionFailed")})]})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.nameLabel")}),n.jsx("input",{type:"text",value:l,onChange:Ot=>c(Ot.target.value),placeholder:a("smartPlugs.addSmartPlug.placeholders.plugName"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s==="tasmota"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.username")}),n.jsx("input",{type:"text",value:m,onChange:Ot=>p(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.password")}),n.jsx("input",{type:"password",value:f,onChange:Ot=>g(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:a("smartPlugs.authHint")})]}),s!=="mqtt"&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.linkToPrinter")}),n.jsxs("select",{value:da??"",onChange:Ot=>ut(Ot.target.value?Number(Ot.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:[n.jsx("option",{value:"",children:a("smartPlugs.noPrinter")}),Pu?.map(Ot=>n.jsx("option",{value:Ot.id,children:Ot.name},Ot.id))]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("smartPlugs.linkingDescription")})]}),n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Th,{className:"w-4 h-4 text-bambu-green"}),n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.powerAlerts")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:Oe,onChange:Ot=>je(Ot.target.checked),className:"sr-only peer"}),n.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"})]})]}),Oe&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.alertAbove")}),n.jsx("input",{type:"number",value:Ve,onChange:Ot=>Je(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.alertBelow")}),n.jsx("input",{type:"number",value:Fe,onChange:Ot=>bt(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.alertDescription")})]})]}),s!=="mqtt"&&n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Za,{className:"w-4 h-4 text-bambu-green"}),n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.dailySchedule")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:Ce,onChange:Ot=>$e(Ot.target.checked),className:"sr-only peer"}),n.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"})]})]}),Ce&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.turnOnAt")}),n.jsx("input",{type:"time",value:nt,onChange:Ot=>st(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.turnOffAt")}),n.jsx("input",{type:"time",value:tt,onChange:Ot=>wt(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.scheduleDescription")})]})]}),n.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(DS,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.showInSwitchbar")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.quickAccessSidebar")})]})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:kt,onChange:Ot=>Ue(Ot.target.checked),className:"sr-only peer"}),n.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&n.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ml,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.showOnPrinterCard")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.displayOnPrinterCard")})]})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:qe,onChange:Ot=>Dt(Ot.target.checked),className:"sr-only peer"}),n.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"})]})]})}),n.jsxs("div",{className:"flex gap-3 pt-2",children:[n.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("smartPlugs.cancel")}),n.jsxs(Me,{type:"submit",disabled:Il,className:"flex-1",children:[Il?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(fs,{className:"w-4 h-4"}),a(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function ja({checked:t,onChange:e,disabled:a}){const r=i=>{i.preventDefault(),i.stopPropagation(),a||e(!t)};return n.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:a,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 ${a?"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:n.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"}`})})}function jrt({provider:t,onEdit:e}){const{t:a}=vt(),r=ta(),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(null),{data:u}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=lt({mutationFn:b=>ne.updateNotificationProvider(t.id,b),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=lt({mutationFn:()=>ne.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),g=lt({mutationFn:()=>ne.testNotificationProvider(t.id),onSuccess:b=>{d(b),r.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{d({success:!1,message:b.message})}}),w=b=>b||"";return n.jsxs(n.Fragment,{children:[n.jsx(Tt,{className:"relative",children:n.jsxs(Mt,{className:"p-3",children:[n.jsxs("div",{className:`flex items-start justify-between ${t.enabled?"mb-3":"mb-0"}`,children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:n.jsx(Th,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),n.jsxs("div",{children:[n.jsx("h3",{className:"font-medium text-white",children:t.name}),n.jsx("p",{className:"text-sm text-bambu-gray",children:a(`notifications.providerTypes.${t.provider_type}`,t.provider_type)})]})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&n.jsx("span",{className:"text-xs text-status-ok hidden sm:inline",children:a("notifications.lastSuccess",{date:zg(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Qa(t.last_error_at)?.getTime()||0)>(Qa(t.last_success)?.getTime()||0))&&n.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:a("notifications.error")}),n.jsx(ja,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]})]}),t.enabled&&n.jsxs(n.Fragment,{children:[m&&n.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[n.jsxs("span",{className:"text-xs text-bambu-gray",children:[a("notifications.printer")," "]}),n.jsx("span",{className:"text-sm text-white",children:m.name})]}),!m&&!t.printer_id&&n.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:n.jsx("span",{className:"text-xs text-bambu-gray",children:a("notifications.allPrinters")})}),n.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&n.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:a("notifications.start")}),t.on_plate_not_empty&&n.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:a("notifications.plateCheck")}),t.on_print_complete&&n.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:a("notifications.complete")}),t.on_print_failed&&n.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:a("notifications.failed")}),t.on_print_stopped&&n.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:a("notifications.stopped")}),t.on_print_progress&&n.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:a("notifications.progress")}),t.on_printer_offline&&n.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:a("notifications.offline")}),t.on_printer_error&&n.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:a("notifications.error")}),t.on_filament_low&&n.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:a("notifications.lowFilament")}),t.on_maintenance_due&&n.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:a("notifications.maintenance")}),t.on_ams_humidity_high&&n.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:a("notifications.amsHumidity")}),t.on_ams_temperature_high&&n.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:a("notifications.amsTemp")}),t.on_ams_ht_humidity_high&&n.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:a("notifications.amsHtHumidity")}),t.on_ams_ht_temperature_high&&n.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:a("notifications.amsHtTemp")}),t.on_bed_cooled&&n.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:a("notifications.bedCooled")}),t.on_first_layer_complete&&n.jsx("span",{className:"px-2 py-0.5 bg-emerald-600/20 text-emerald-300 text-xs rounded",children:a("notifications.firstLayer")}),t.on_print_missing_spool_assignment&&n.jsx("span",{className:"px-2 py-0.5 bg-amber-500/20 text-amber-300 text-xs rounded",children:a("notifications.missingSpoolAssignmentLabel")}),t.on_stock_reorder_alert&&n.jsx("span",{className:"px-2 py-0.5 bg-lime-500/20 text-lime-400 text-xs rounded",children:a("notifications.stockReorderAlert")}),t.on_stock_break_alert&&n.jsx("span",{className:"px-2 py-0.5 bg-red-600/20 text-red-300 text-xs rounded",children:a("notifications.stockBreakAlert")}),t.quiet_hours_enabled&&n.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[n.jsx(cC,{className:"w-3 h-3"}),a("notifications.quiet")]}),t.daily_digest_enabled&&n.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[n.jsx(vr,{className:"w-3 h-3"}),a("notifications.digest",{time:t.daily_digest_time})]})]}),n.jsx("div",{className:"mb-3",children:n.jsxs(Me,{size:"sm",variant:"secondary",disabled:g.isPending,onClick:()=>{d(null),g.mutate()},className:"w-full",children:[g.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(OS,{className:"w-4 h-4"}),a("notifications.sendTestNotification")]})}),c&&n.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${c.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[c.success?n.jsx(fn,{className:"w-4 h-4"}):n.jsx(Mn,{className:"w-4 h-4"}),n.jsx("span",{children:c.message})]})]}),n.jsxs("button",{onClick:()=>l(!o),className:`w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors ${t.enabled?"border-t border-bambu-dark-tertiary":"mt-2 border-t border-bambu-dark-tertiary"}`,children:[n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(mu,{className:"w-4 h-4"}),a("notifications.eventSettings")]}),o?n.jsx(al,{className:"w-4 h-4"}):n.jsx(Da,{className:"w-4 h-4"})]}),o&&n.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.enabled")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.sendFromProvider")})]}),n.jsx(ja,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.printEvents")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printStarted")}),n.jsx(ja,{checked:t.on_print_start,onChange:b=>p.mutate({on_print_start:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.plateNotEmpty")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.plateNotEmptyDescription")})]}),n.jsx(ja,{checked:t.on_plate_not_empty??!0,onChange:b=>p.mutate({on_plate_not_empty:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printCompleted")}),n.jsx(ja,{checked:t.on_print_complete,onChange:b=>p.mutate({on_print_complete:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.bedCooledLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.bedCooledDescription")})]}),n.jsx(ja,{checked:t.on_bed_cooled??!1,onChange:b=>p.mutate({on_bed_cooled:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.firstLayerCompleteLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.firstLayerCompleteDescription")})]}),n.jsx(ja,{checked:t.on_first_layer_complete??!1,onChange:b=>p.mutate({on_first_layer_complete:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.missingSpoolAssignmentLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.missingSpoolAssignmentDescription")})]}),n.jsx(ja,{checked:t.on_print_missing_spool_assignment??!1,onChange:b=>p.mutate({on_print_missing_spool_assignment:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printFailed")}),n.jsx(ja,{checked:t.on_print_failed,onChange:b=>p.mutate({on_print_failed:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printStopped")}),n.jsx(ja,{checked:t.on_print_stopped,onChange:b=>p.mutate({on_print_stopped:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.progressMilestones")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.progressMilestonesDescription")})]}),n.jsx(ja,{checked:t.on_print_progress,onChange:b=>p.mutate({on_print_progress:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.printerStatus")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printerOffline")}),n.jsx(ja,{checked:t.on_printer_offline,onChange:b=>p.mutate({on_printer_offline:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printerError")}),n.jsx(ja,{checked:t.on_printer_error,onChange:b=>p.mutate({on_printer_error:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.lowFilamentLabel")}),n.jsx(ja,{checked:t.on_filament_low,onChange:b=>p.mutate({on_filament_low:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.maintenanceDue")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.maintenanceDueDescription")})]}),n.jsx(ja,{checked:t.on_maintenance_due??!1,onChange:b=>p.mutate({on_maintenance_due:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.amsAlarms")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsHumidityHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsHumidityHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_humidity_high??!1,onChange:b=>p.mutate({on_ams_humidity_high:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsTemperatureHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsTemperatureHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_temperature_high??!1,onChange:b=>p.mutate({on_ams_temperature_high:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.amsHtAlarms")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsHtHumidityHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsHtHumidityHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>p.mutate({on_ams_ht_humidity_high:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsHtTemperatureHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsHtTemperatureHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>p.mutate({on_ams_ht_temperature_high:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.inventoryAlerts")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.stockReorderAlert")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.stockReorderAlertDescription")})]}),n.jsx(ja,{checked:t.on_stock_reorder_alert??!1,onChange:b=>p.mutate({on_stock_reorder_alert:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.stockBreakAlert")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.stockBreakAlertDescription")})]}),n.jsx(ja,{checked:t.on_stock_break_alert??!1,onChange:b=>p.mutate({on_stock_break_alert:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.printQueue")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobAdded")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobAddedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_added??!1,onChange:b=>p.mutate({on_queue_job_added:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobAssigned")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobAssignedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_assigned??!1,onChange:b=>p.mutate({on_queue_job_assigned:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobStarted")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobStartedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_started??!1,onChange:b=>p.mutate({on_queue_job_started:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobWaiting")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobWaitingDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_waiting??!0,onChange:b=>p.mutate({on_queue_job_waiting:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobSkipped")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobSkippedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_skipped??!0,onChange:b=>p.mutate({on_queue_job_skipped:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobFailed")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobFailedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_failed??!0,onChange:b=>p.mutate({on_queue_job_failed:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.queueComplete")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.queueCompleteDescription")})]}),n.jsx(ja,{checked:t.on_queue_completed??!1,onChange:b=>p.mutate({on_queue_completed:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(cC,{className:"w-4 h-4 text-purple-400"}),n.jsx("p",{className:"text-sm text-white",children:a("notifications.quietHours")})]}),n.jsx(ja,{checked:t.quiet_hours_enabled,onChange:b=>p.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&n.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.noNotificationsDuring")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Za,{className:"w-4 h-4 text-bambu-gray"}),n.jsxs("span",{className:"text-sm text-white",children:[w(t.quiet_hours_start)||"22:00"," - ",w(t.quiet_hours_end)||"07:00"]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.editProviderToChangeQuietHours")})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(vr,{className:"w-4 h-4 text-emerald-400"}),n.jsx("p",{className:"text-sm text-white",children:a("notifications.dailyDigest")})]}),n.jsx(ja,{checked:t.daily_digest_enabled,onChange:b=>p.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&n.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.batchNotifications")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Za,{className:"w-4 h-4 text-bambu-gray"}),n.jsx("span",{className:"text-sm text-white",children:a("notifications.sendAt",{time:w(t.daily_digest_time)||"08:00"})})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.editProviderToChangeDigestTime")})]})]}),n.jsxs("div",{className:"flex gap-2 pt-2",children:[n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[n.jsx(fc,{className:"w-4 h-4"}),a("notifications.edit")]}),n.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:n.jsx(ea,{className:"w-4 h-4"})})]})]})]})}),i&&n.jsx(ya,{title:a("notifications.deleteProvider"),message:a("notifications.deleteConfirm",{name:t.name}),confirmText:a("notifications.delete"),variant:"danger",onConfirm:()=>{f.mutate(),s(!1)},onCancel:()=>s(!1)})]})}const Mrt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function Ert({provider:t,onClose:e}){const{t:a}=vt(),r=ta(),i=!!t,[s,o]=y.useState(t?.name||""),[l,c]=y.useState(t?.provider_type||"email"),[d,u]=y.useState(t?.printer_id||null),[m,p]=y.useState(t?.quiet_hours_enabled||!1),[f,g]=y.useState(t?.quiet_hours_start||"22:00"),[w,b]=y.useState(t?.quiet_hours_end||"07:00"),[x,S]=y.useState(t?.daily_digest_enabled||!1),[N,C]=y.useState(t?.daily_digest_time||"08:00"),[P,T]=y.useState(t?.on_print_start??!1),[j,F]=y.useState(t?.on_print_complete??!0),[k,M]=y.useState(t?.on_print_failed??!0),[q,I]=y.useState(t?.on_print_stopped??!0),[B,R]=y.useState(t?.on_print_progress??!1),[X,ee]=y.useState(t?.on_printer_offline??!1),[Q,le]=y.useState(t?.on_printer_error??!1),[de,ue]=y.useState(t?.on_filament_low??!1),[Z,oe]=y.useState(t?.on_maintenance_due??!1),[fe,me]=y.useState(t?.on_stock_reorder_alert??!1),[be,H]=y.useState(t?.on_stock_break_alert??!1),[J,A]=y.useState(t?.on_bed_cooled??!1),[E,z]=y.useState(t?.on_first_layer_complete??!1),[W,O]=y.useState(t?.config?Object.fromEntries(Object.entries(t.config).filter(([Te])=>Te!=="event_priorities").map(([Te,ve])=>[Te,String(ve)])):{}),re=(()=>{const Te=t?.config?.event_priorities;if(!Te||typeof Te!="object")return{};const ve={};for(const[we,ze]of Object.entries(Te)){const De=Number(ze);Number.isInteger(De)&&De>=1&&De<=5&&(ve[we]=De)}return ve})(),[U,V]=y.useState(re),[K,Y]=y.useState(null),[ie,se]=y.useState(null),{data:pe}=Qe({queryKey:["printers"],queryFn:ne.getPrinters});y.useEffect(()=>{const Te=ve=>{ve.key==="Escape"&&e()};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[e]);const ce=lt({mutationFn:()=>ne.testNotificationConfig({provider_type:l,config:W}),onSuccess:Te=>{Y(Te),se(null)},onError:Te=>{Y({success:!1,message:Te.message})}}),he=lt({mutationFn:Te=>ne.createNotificationProvider(Te),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:Te=>{se(Te.message)}}),$=lt({mutationFn:Te=>ne.updateNotificationProvider(t.id,Te),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:Te=>{se(Te.message)}}),L=Te=>{if(Te.preventDefault(),se(null),!s.trim()){se(a("notifications.nameRequired"));return}const ve=xe(l);for(const De of ve)if(!W[De.key]?.trim()){se(a("notifications.fieldRequired",{field:De.label}));return}const we=l==="ntfy"&&Object.keys(U).length>0?{...W,event_priorities:U}:W,ze={name:s.trim(),provider_type:l,config:we,printer_id:d,quiet_hours_enabled:m,quiet_hours_start:m?f:null,quiet_hours_end:m?w:null,daily_digest_enabled:x,daily_digest_time:x?N:null,on_print_start:P,on_print_complete:j,on_print_failed:k,on_print_stopped:q,on_print_progress:B,on_printer_offline:X,on_printer_error:Q,on_filament_low:de,on_maintenance_due:Z,on_stock_reorder_alert:fe,on_stock_break_alert:be,on_bed_cooled:J,on_first_layer_complete:E};i?$.mutate(ze):he.mutate(ze)},ae=he.isPending||$.isPending,ge=Te=>{switch(Te){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:ve=>ve.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:ve=>ve.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},xe=Te=>ge(Te).filter(ve=>ve.required),Se=ge(l);return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:n.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:Te=>Te.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a(i?"notifications.editTitle":"notifications.addTitle")}),n.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:n.jsx($t,{className:"w-5 h-5"})})]}),n.jsxs("form",{onSubmit:L,className:"p-6 space-y-4",children:[ie&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:ie}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("notifications.nameLabel")}),n.jsx("input",{type:"text",value:s,onChange:Te=>o(Te.target.value),placeholder:a("notifications.namePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("notifications.providerTypeLabel")}),n.jsx("select",{value:l,onChange:Te=>{c(Te.target.value),O({}),Y(null)},disabled:i,className:"w-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:Mrt.map(Te=>n.jsx("option",{value:Te,children:a(`notifications.providerTypes.${Te}`,Te)},Te))}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a(`notifications.providerDescriptions.${l}`,"")})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:a("notifications.configuration")}),Se.filter(Te=>!("showIf"in Te)||Te.showIf?.(W)!==!1).map(Te=>n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[Te.label," ",Te.required&&"*"]}),Te.type==="select"&&"options"in Te&&Te.options?n.jsx("select",{value:W[Te.key]||Te.options[0]?.value||"",onChange:ve=>{O({...W,[Te.key]:ve.target.value}),Y(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:Te.options.map(ve=>n.jsx("option",{value:ve.value,children:ve.label},ve.value))}):n.jsx("input",{type:Te.type,value:W[Te.key]||"",onChange:ve=>{O({...W,[Te.key]:ve.target.value}),Y(null)},placeholder:Te.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"})]},Te.key))]}),n.jsx("div",{className:"flex gap-2",children:n.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>{Y(null),ce.mutate()},disabled:ce.isPending||xe(l).length>0&&!W[xe(l)[0]?.key],className:"flex-1",children:[ce.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(OS,{className:"w-4 h-4"}),a("notifications.testConfiguration")]})}),K&&n.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${K.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:K.success?n.jsxs(n.Fragment,{children:[n.jsx(fn,{className:"w-5 h-5"}),n.jsx("span",{children:K.message})]}):n.jsxs(n.Fragment,{children:[n.jsx(Mn,{className:"w-5 h-5"}),n.jsx("span",{children:K.message})]})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("notifications.printerFilter")}),n.jsxs("select",{value:d??"",onChange:Te=>u(Te.target.value?Number(Te.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:[n.jsx("option",{value:"",children:a("notifications.allPrinters")}),pe?.map(Te=>n.jsx("option",{value:Te.id,children:Te.name},Te.id))]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("notifications.onlyFromPrinter")})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-sm text-white",children:a("notifications.quietHoursDnd")}),n.jsx(ja,{checked:m,onChange:p})]}),m&&n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("notifications.quietStart")}),n.jsx("input",{type:"time",value:f,onChange:Te=>g(Te.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("notifications.quietEnd")}),n.jsx("input",{type:"time",value:w,onChange:Te=>b(Te.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"})]})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-sm text-white",children:a("notifications.dailyDigestLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.batchNotifications")})]}),n.jsx(ja,{checked:x,onChange:S})]}),x&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("notifications.sendDigestAt")}),n.jsx("input",{type:"time",value:N,onChange:Te=>C(Te.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"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("notifications.digestCollected")})]})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:a("notifications.notificationEvents")}),n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:a("notifications.printEvents")}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.start")}),n.jsx(ja,{checked:P,onChange:T})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.complete")}),n.jsx(ja,{checked:j,onChange:F})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.failed")}),n.jsx(ja,{checked:k,onChange:M})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.stopped")}),n.jsx(ja,{checked:q,onChange:I})]}),n.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.progress")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.progressPercent")})]}),n.jsx(ja,{checked:B,onChange:R})]}),n.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.bedCooled")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.bedCooledAfterPrint")})]}),n.jsx(ja,{checked:J,onChange:A})]}),n.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.firstLayerCompleteLabel")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.firstLayerCompleteDescription")})]}),n.jsx(ja,{checked:E,onChange:z})]})]})]}),n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:a("notifications.printerStatus")}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.offline")}),n.jsx(ja,{checked:X,onChange:ee})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.error")}),n.jsx(ja,{checked:Q,onChange:le})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.lowFilament")}),n.jsx(ja,{checked:de,onChange:ue})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.maintenance")}),n.jsx(ja,{checked:Z,onChange:oe})]})]})]}),n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:a("notifications.inventoryAlerts")}),n.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.stockReorderAlert")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.stockReorderAlertDescription")})]}),n.jsx(ja,{checked:fe,onChange:me})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.stockBreakAlert")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.stockBreakAlertDescription")})]}),n.jsx(ja,{checked:be,onChange:H})]})]})]}),l==="ntfy"&&(()=>{const Te=[];return P&&Te.push({key:"on_print_start",label:a("notifications.start")}),j&&Te.push({key:"on_print_complete",label:a("notifications.complete")}),k&&Te.push({key:"on_print_failed",label:a("notifications.failed")}),q&&Te.push({key:"on_print_stopped",label:a("notifications.stopped")}),B&&Te.push({key:"on_print_progress",label:a("notifications.progress")}),J&&Te.push({key:"on_bed_cooled",label:a("notifications.bedCooled")}),E&&Te.push({key:"on_first_layer_complete",label:a("notifications.firstLayerCompleteLabel")}),X&&Te.push({key:"on_printer_offline",label:a("notifications.offline")}),Q&&Te.push({key:"on_printer_error",label:a("notifications.error")}),de&&Te.push({key:"on_filament_low",label:a("notifications.lowFilament")}),Z&&Te.push({key:"on_maintenance_due",label:a("notifications.maintenance")}),fe&&Te.push({key:"on_stock_reorder_alert",label:a("notifications.stockReorderAlert")}),be&&Te.push({key:"on_stock_break_alert",label:a("notifications.stockBreakAlert")}),Te.length===0?null:n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-1",children:a("notifications.eventPriority.sectionTitle")}),n.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:a("notifications.eventPriority.helpNtfy")}),n.jsx("div",{className:"space-y-2",children:Te.map(ve=>n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"text-sm text-white",children:ve.label}),n.jsxs("select",{value:U[ve.key]??3,onChange:we=>{const ze=Number(we.target.value);V(De=>({...De,[ve.key]:ze}))},className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:1,children:a("notifications.eventPriority.min")}),n.jsx("option",{value:2,children:a("notifications.eventPriority.low")}),n.jsx("option",{value:3,children:a("notifications.eventPriority.default")}),n.jsx("option",{value:4,children:a("notifications.eventPriority.high")}),n.jsx("option",{value:5,children:a("notifications.eventPriority.urgent")})]})]},ve.key))})]})})()]}),n.jsxs("div",{className:"flex gap-3 pt-2",children:[n.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("notifications.cancel")}),n.jsxs(Me,{type:"submit",disabled:ae,className:"flex-1",children:[ae?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(fs,{className:"w-4 h-4"}),a(i?"notifications.save":"notifications.add")]})]})]})]})})}function Drt({template:t,onClose:e}){const{t:a}=vt(),r=ta(),i=y.useRef(null),[s,o]=y.useState(t.title_template),[l,c]=y.useState(t.body_template),[d,u]=y.useState(null),[m,p]=y.useState(!0),{data:f}=Qe({queryKey:["template-variables"],queryFn:ne.getTemplateVariables}),g=f?.find(T=>T.event_type===t.event_type),{data:w,isLoading:b}=Qe({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>ne.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});y.useEffect(()=>{const T=j=>{j.key==="Escape"&&e()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[e]);const x=lt({mutationFn:T=>ne.updateNotificationTemplate(t.id,T),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:T=>{u(T.message)}}),S=lt({mutationFn:()=>ne.resetNotificationTemplate(t.id),onSuccess:T=>{o(T.title_template),c(T.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:T=>{u(T.message)}}),N=T=>{if(T.preventDefault(),u(null),!s.trim()){u(a("notifications.titleRequired"));return}if(!l.trim()){u(a("notifications.bodyRequired"));return}x.mutate({title_template:s,body_template:l})},C=T=>{const j=i.current;if(!j)return;const F=j.selectionStart,k=j.selectionEnd,M=l,q=M.substring(0,F),I=M.substring(k),B=q+`{${T}}`+I;c(B),setTimeout(()=>{j.focus();const R=F+T.length+2;j.setSelectionRange(R,R)},0)},P=s!==t.title_template||l!==t.body_template;return n.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("notifications.editTemplate",{name:t.name})}),n.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:n.jsx($t,{className:"w-5 h-5 text-bambu-gray"})})]}),n.jsxs("form",{onSubmit:N,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[d&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:d}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("notifications.titleLabel")}),n.jsx("input",{type:"text",value:s,onChange:T=>o(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:a("notifications.titlePlaceholder")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("notifications.bodyLabel")}),n.jsx("textarea",{ref:i,value:l,onChange:T=>c(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:a("notifications.bodyPlaceholder")})]}),g&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:a("notifications.availableVariables")}),n.jsx("div",{className:"flex flex-wrap gap-2",children:g.variables.map(T=>n.jsxs("button",{type:"button",onClick:()=>C(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:[n.jsx(en,{className:"w-3 h-3"}),T]},T))}),n.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:a("notifications.clickToInsert")})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[n.jsx(Ml,{className:"w-4 h-4"}),a("notifications.livePreview")]}),n.jsx("button",{type:"button",onClick:()=>p(!m),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:a(m?"notifications.hide":"notifications.show")})]}),m&&n.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?n.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),a("notifications.loadingPreview")]}):w?n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-xs text-bambu-gray",children:a("notifications.titlePreview")}),n.jsx("div",{className:"text-white font-medium",children:w.title})]}),n.jsxs("div",{children:[n.jsx("span",{className:"text-xs text-bambu-gray",children:a("notifications.bodyPreview")}),n.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:w.body})]})]}):n.jsx("div",{className:"text-bambu-gray text-sm",children:a("notifications.enterTemplateContent")})})]})]}),n.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[n.jsxs(Me,{type:"button",variant:"ghost",onClick:()=>S.mutate(),disabled:S.isPending,className:"text-orange-400 hover:text-orange-300",children:[S.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):n.jsx(vs,{className:"w-4 h-4 mr-2"}),a("notifications.resetToDefault")]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:a("notifications.cancel")}),n.jsxs(Me,{onClick:N,disabled:x.isPending||!P,children:[x.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):n.jsx(fs,{className:"w-4 h-4 mr-2"}),a("notifications.save")]})]})]})]})})}const Frt={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 Lrt({onClose:t}){const{t:e}=vt(),a=ta(),{showToast:r}=ra(),[i,s]=y.useState(7),[o,l]=y.useState(null),[c,d]=y.useState(!1),{data:u}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:g,isRefetching:w}=Qe({queryKey:["notification-logs",i,c],queryFn:()=>ne.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=Qe({queryKey:["notification-log-stats",i],queryFn:()=>ne.getNotificationLogStats(i)}),x=lt({mutationFn:()=>ne.clearNotificationLogs(30),onSuccess:N=>{r(N.message,"success"),a.invalidateQueries({queryKey:["notification-logs"]}),a.invalidateQueries({queryKey:["notification-log-stats"]})},onError:N=>{r(`Failed to clear logs: ${N.message}`,"error")}}),S=N=>{const C=Qa(N);if(!C)return"";const T=new Date().getTime()-C.getTime();return T<6e4?e("notifications.justNow"):T<36e5?`${Math.floor(T/6e4)}m ago`:T<864e5?`${Math.floor(T/36e5)}h ago`:C.toLocaleDateString()+" "+xJ(C,m)};return n.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:n.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:[n.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(Wh,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:e("notifications.notificationLog")})]}),n.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&n.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:n.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[n.jsxs("span",{className:"text-bambu-gray",children:[e("notifications.statsSummary",{days:i})," ",n.jsx("span",{className:"text-white font-medium",children:b.total})," ",e("notifications.statsNotifications")]}),n.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[n.jsx(fn,{className:"w-4 h-4"}),e("notifications.statsSent",{count:b.success_count})]}),b.failure_count>0&&n.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[n.jsx(Mn,{className:"w-4 h-4"}),e("notifications.statsFailed",{count:b.failure_count})]})]})}),n.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[n.jsxs("select",{value:i,onChange:N=>s(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:[n.jsx("option",{value:1,children:e("notifications.last24Hours")}),n.jsx("option",{value:7,children:e("notifications.last7Days")}),n.jsx("option",{value:30,children:e("notifications.last30Days")}),n.jsx("option",{value:90,children:e("notifications.last90Days")})]}),n.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:c,onChange:N=>d(N.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),e("notifications.showFailedOnly")]}),n.jsx("div",{className:"flex-1"}),n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>g(),disabled:w,children:[w?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),e("notifications.refresh")]}),n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>x.mutate(),disabled:x.isPending,className:"text-red-400 hover:text-red-300",children:[x.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(ea,{className:"w-4 h-4"}),e("notifications.clearOld")]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?n.jsx("div",{className:"flex justify-center py-12",children:n.jsx(pt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?n.jsx("div",{className:"space-y-2",children:p.map(N=>n.jsx(Rrt,{log:N,isExpanded:o===N.id,onToggle:()=>l(o===N.id?null:N.id),formatDate:S,formatFullDate:C=>Ug(C,m)},N.id))}):n.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[n.jsx(Wh,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),n.jsx("p",{className:"text-sm",children:e(c?"notifications.noFailedNotifications":"notifications.noNotificationsLogged")})]})})]})})}function Rrt({log:t,isExpanded:e,onToggle:a,formatDate:r,formatFullDate:i}){const{t:s}=vt();return n.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:[n.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:a,children:[t.success?n.jsx(fn,{className:"w-4 h-4 text-bambu-green shrink-0"}):n.jsx(Mn,{className:"w-4 h-4 text-red-400 shrink-0"}),n.jsx("span",{className:`text-xs font-medium ${Frt[t.event_type]||"text-bambu-gray"}`,children:s(`notifications.eventTypes.${t.event_type}`,t.event_type)}),n.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||s("notifications.unknownProvider")}),t.printer_name&&n.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),n.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?n.jsx(al,{className:"w-4 h-4 text-bambu-gray shrink-0"}):n.jsx(Da,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&n.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logTitle")}),n.jsx("p",{className:"text-sm text-white",children:t.title})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logMessage")}),n.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&n.jsxs("div",{children:[n.jsx("p",{className:"text-xs text-red-400 mb-1",children:s("notifications.logError")}),n.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),n.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[n.jsx("span",{children:s("notifications.logProvider",{type:t.provider_type})}),n.jsx("span",{children:s("notifications.logTime",{time:i(t.created_at)})})]})]})]})}const Irt=300,I0=2;function Jce({onSuccess:t}){const{t:e}=vt(),a=ta(),[r,i]=y.useState(""),[s,o]=y.useState(""),[l,c]=y.useState(null),[d,u]=y.useState(null);y.useEffect(()=>{const N=r.trim();if(N.lengtho(N),Irt);return()=>clearTimeout(C)},[r]),y.useEffect(()=>{c(null),u(null)},[s]);const m=Qe({queryKey:["ldap-search",s],queryFn:()=>ne.searchLDAPDirectory(s),enabled:s.length>=I0,staleTime:3e4}),p=lt({mutationFn:N=>ne.provisionLDAPUser(N),onSuccess:N=>{a.invalidateQueries({queryKey:["users"]}),t(N)},onError:N=>{u(N.message||e("users.modal.ldapErrorProvision"))}}),f=y.useMemo(()=>m.data?.find(N=>N.dn===l)??null,[m.data,l]),g=r.trim().length>0&&r.trim().length=I0,b=!!m.data&&m.data.length>0,x=!w&&!!m.data&&m.data.length===0&&s.length>=I0,S=()=>{!f||f.already_provisioned||(u(null),p.mutate(f.username))};return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:e("users.modal.ldapSearchLabel")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2"}),n.jsx("input",{type:"text",value:r,onChange:N=>i(N.target.value),className:"w-full pl-9 pr-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("users.modal.ldapSearchPlaceholder"),autoComplete:"off"})]}),g&&n.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:e("users.modal.ldapMinChars")})]}),n.jsxs("div",{className:"min-h-[8rem] max-h-64 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[w&&n.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}),n.jsx("span",{children:e("users.modal.ldapSearching")})]}),x&&n.jsx("div",{className:"flex items-center justify-center py-8 text-bambu-gray text-sm",children:e("users.modal.ldapNoResults")}),m.isError&&n.jsx("div",{className:"px-3 py-4 text-sm text-red-400",children:m.error instanceof Error?m.error.message:e("users.modal.ldapSearchError")}),!w&&b&&n.jsx("ul",{className:"divide-y divide-bambu-dark-tertiary",children:m.data.map(N=>n.jsx(Ort,{result:N,selected:l===N.dn,onSelect:()=>c(N.dn)},N.dn))}),!w&&!m.data&&!m.isError&&n.jsx("div",{className:"flex items-center justify-center py-8 text-bambu-gray text-sm",children:e("users.modal.ldapTypeToSearch")})]}),f&&n.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-1",children:[n.jsxs("p",{className:"text-sm text-white",children:[n.jsxs("span",{className:"text-bambu-gray",children:[e("users.modal.ldapSelectedLabel"),": "]}),n.jsx("span",{className:"font-medium",children:f.username}),f.display_name&&n.jsxs("span",{className:"text-bambu-gray",children:[" — ",f.display_name]})]}),f.email&&n.jsx("p",{className:"text-xs text-bambu-gray",children:f.email}),n.jsx("p",{className:"text-xs text-bambu-gray break-all",children:f.dn})]}),d&&n.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-lg p-3",children:n.jsx("p",{className:"text-sm text-red-400",children:d})}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Me,{onClick:S,disabled:!f||f.already_provisioned||p.isPending,children:p.isPending?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),e("users.modal.ldapProvisioning")]}):n.jsxs(n.Fragment,{children:[n.jsx(en,{className:"w-4 h-4"}),e("users.modal.ldapProvision")]})})})]})}function Ort({result:t,selected:e,onSelect:a}){const{t:r}=vt(),i=t.already_provisioned;return n.jsx("li",{children:n.jsxs("button",{type:"button",onClick:a,disabled:i,className:`w-full text-left px-3 py-2 flex items-center gap-3 transition-colors ${i?"opacity-50 cursor-not-allowed":e?"bg-bambu-green/10":"hover:bg-bambu-dark-tertiary"}`,children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("p",{className:"text-sm text-white truncate",children:[n.jsx("span",{className:"font-medium",children:t.username}),t.display_name&&n.jsxs("span",{className:"text-bambu-gray",children:[" — ",t.display_name]})]}),t.email&&n.jsx("p",{className:"text-xs text-bambu-gray truncate",children:t.email})]}),i&&n.jsxs("span",{className:"flex items-center gap-1 text-xs text-bambu-gray whitespace-nowrap",children:[n.jsx(no,{className:"w-3.5 h-3.5"}),r("users.modal.ldapAlreadyProvisioned")]})]})})}function zrt({formData:t,setFormData:e,groups:a,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o,ldapEnabled:l=!1,onLdapProvisioned:c}){const{t:d}=vt(),[u,m]=y.useState("local");y.useEffect(()=>{const f=g=>{g.key==="Escape"&&r()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r]);const p=f=>{e({...t,group_ids:t.group_ids.includes(f)?t.group_ids.filter(g=>g!==f):[...t.group_ids,f]})};return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:n.jsxs(Tt,{className:"w-full max-w-md",onClick:f=>f.stopPropagation(),children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Sm,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:d("users.modal.createUser")})]}),n.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:d("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),n.jsx(Me,{variant:"ghost",size:"sm",onClick:r,children:n.jsx($t,{className:"w-5 h-5"})})]})}),n.jsxs(Mt,{children:[l&&n.jsxs("div",{className:"mb-4 flex items-center gap-1 p-1 bg-bambu-dark-secondary rounded-lg",role:"tablist","aria-label":d("users.modal.tabsAriaLabel"),children:[n.jsx("button",{type:"button",role:"tab","aria-selected":u==="local",onClick:()=>m("local"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${u==="local"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:d("users.modal.localTab")}),n.jsx("button",{type:"button",role:"tab","aria-selected":u==="ldap",onClick:()=>m("ldap"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${u==="ldap"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:d("users.modal.ldapTab")})]}),u==="ldap"&&l?n.jsx(Jce,{onSuccess:f=>{c?.(f)}}):n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[d("users.form.username")," ",n.jsx("span",{className:"text-red-400",children:"*"})]}),n.jsx("input",{type:"text",value:t.username,onChange:f=>e({...t,username:f.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:d("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[d("users.form.email")||"Email"," ",n.jsx("span",{className:"text-red-400",children:"*"})]}),n.jsx("input",{type:"email",value:t.email,onChange:f=>e({...t,email:f.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:d("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),n.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:n.jsx("p",{className:"text-sm text-bambu-gray",children:d("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:d("users.form.groups")}),n.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.map(f=>n.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.group_ids.includes(f.id),onChange:()=>p(f.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),n.jsx("span",{className:"text-sm text-white",children:f.name}),f.is_system&&n.jsxs("span",{className:"text-xs text-yellow-400",children:["(",d("users.system"),")"]})]},f.id)),a.length===0&&n.jsx("p",{className:"text-sm text-bambu-gray",children:d("users.noGroupsAvailable")})]})]})]}),n.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[n.jsx(Me,{variant:"secondary",onClick:r,children:d("users.modal.cancel")}),u==="local"&&n.jsx(Me,{onClick:i,disabled:o,children:s?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),d("users.modal.creating")]}):n.jsxs(n.Fragment,{children:[n.jsx(en,{className:"w-4 h-4"}),d("users.modal.createUser")]})})]})]})]})})}function Urt(){const{t}=vt(),e=ta(),{showToast:a}=ra(),[r,i]=y.useState(!1),[s,o]=y.useState(""),[l,c]=y.useState("auto"),[d,u]=y.useState(!1),[m,p]=y.useState(!0),[f,g]=y.useState("all"),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!1),{data:j,isLoading:F}=Qe({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings}),{data:k,isLoading:M,refetch:q}=Qe({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,refetchInterval:3e4}),{data:I}=Qe({queryKey:["printers"],queryFn:ne.getPrinters});y.useEffect(()=>{j&&(i(j.spoolman_enabled==="true"),o(j.spoolman_url||""),c(j.spoolman_sync_mode||"auto"),u(j.spoolman_disable_weight_sync==="true"),p(j.spoolman_report_partial_usage!=="false"),b(!0))},[j]),y.useEffect(()=>{if(!w||!j)return;if(j.spoolman_enabled==="true"!==r||(j.spoolman_url||"")!==s||(j.spoolman_sync_mode||"auto")!==l||j.spoolman_disable_weight_sync==="true"!==d||j.spoolman_report_partial_usage!=="false"!==m){const be=setTimeout(()=>{B.mutate()},500);return()=>clearTimeout(be)}},[r,s,l,d,m,w]);const B=lt({mutationFn:()=>ne.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:d?"true":"false",spoolman_report_partial_usage:m?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),e.invalidateQueries({queryKey:["settings"]}),e.invalidateQueries({queryKey:["spoolman-inventory-filaments"]}),a(t("settings.toast.settingsSaved"))},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),R=lt({mutationFn:ne.connectSpoolman,onSuccess:()=>{q()},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),X=lt({mutationFn:ne.disconnectSpoolman,onSuccess:()=>{q()},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),ee=lt({mutationFn:ne.syncAllPrintersAms,onSuccess:me=>{a(t("settings.spoolmanAmsSyncSuccess",{synced:me.synced_count,skipped:0}),"success")},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),Q=lt({mutationFn:me=>ne.syncPrinterAms(me),onSuccess:me=>{a(t("settings.spoolmanAmsSyncSuccess",{synced:me.synced_count,skipped:0}),"success")},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),le=()=>{f==="all"?ee.mutate():Q.mutate(f)},de=lt({mutationFn:ne.syncWeightsFromAms,onSuccess:me=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),a(t("settings.amsSyncSuccess",{synced:me.synced,skipped:me.skipped}),"success"),C(!1)},onError:()=>{a(t("settings.amsSyncError"),"error"),C(!1)}}),ue=lt({mutationFn:ne.syncSpoolmanAmsWeights,onSuccess:me=>{e.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),a(t("settings.spoolmanAmsSyncSuccess",{synced:me.synced,skipped:me.skipped}),"success"),T(!1)},onError:me=>{me instanceof Hi&&me.status===503?a(t("settings.spoolmanAmsSyncErrorUnreachable"),"error"):me instanceof Hi&&me.status===400?a(t("settings.spoolmanAmsSyncErrorNotConfigured"),"error"):a(t("settings.spoolmanAmsSyncError"),"error"),T(!1)}}),Z=ee.isPending||Q.isPending,oe=f==="all"?ee.data:Q.data,fe=f==="all"?ee.isSuccess:Q.isSuccess;return F?n.jsxs(Tt,{id:"card-spoolman",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(hc,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),n.jsx(Mt,{children:n.jsx("div",{className:"flex justify-center py-8",children:n.jsx(pt,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):n.jsxs(Tt,{id:"card-spoolman",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(hc,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),B.isPending&&n.jsx(pt,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx(Hn,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),n.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),n.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&n.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[n.jsx(_n,{className:"w-3 h-3 text-bambu-green"}),n.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),n.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx(En,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),n.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),n.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&n.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[n.jsx(_n,{className:"w-3 h-3 text-bambu-green"}),n.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Ei,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),n.jsx("div",{className:"text-xs text-bambu-gray",children:n.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[n.jsx("li",{children:t("settings.builtInFeatureRfid")}),n.jsx("li",{children:t("settings.builtInFeatureUsage")}),n.jsx("li",{children:t("settings.builtInFeatureCatalog")}),n.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>C(!0),disabled:de.isPending,children:[de.isPending?n.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Ei,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{className:"text-xs text-blue-300",children:[n.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),n.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[n.jsx("li",{children:t("settings.syncInfoRfidOnly")}),n.jsx("li",{children:t("settings.syncInfoAutoCreate")}),n.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),n.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),n.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),n.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:me=>o(me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),n.jsxs("select",{value:l,onChange:me=>c(me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),n.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),n.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:d,onChange:me=>u(me.target.checked),className:"sr-only peer"}),n.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"})]})]}),d&&n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),n.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:m,onChange:me=>p(me.target.checked),className:"sr-only peer"}),n.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"})]})]}),n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),M?n.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin"}):k?.connected?n.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[n.jsx(_n,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):n.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[n.jsx($t,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),n.jsx("div",{className:"flex gap-2",children:k?.connected?n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,children:[X.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Lxe,{className:"w-4 h-4"}),t("settings.disconnect")]}):n.jsxs(Me,{size:"sm",onClick:()=>R.mutate(),disabled:R.isPending||!s,children:[R.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Eh,{className:"w-4 h-4"}),t("settings.connect")]})})]}),(R.isError||X.isError)&&n.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:(R.error||X.error).message}),k?.connected&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"relative flex-1",children:[n.jsxs("select",{value:f,onChange:me=>g(me.target.value==="all"?"all":Number(me.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:[n.jsx("option",{value:"all",children:t("settings.allPrinters")}),I?.map(me=>n.jsx("option",{value:me.id,children:me.name},me.id))]}),n.jsx(Da,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:le,disabled:Z,children:[Z?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),k?.connected&&n.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:t("settings.spoolmanAmsSyncButton")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.spoolmanAmsSyncMessage")})]}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>T(!0),disabled:ue.isPending,children:[ue.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),ue.isPending?t("settings.spoolmanAmsSyncing"):t("settings.spoolmanAmsSyncButton")]})]})}),fe&&oe&&n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx("div",{className:`p-2 rounded text-sm ${oe.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:oe.success?`Synced ${oe.synced_count} spool${oe.synced_count!==1?"s":""} successfully`:`Synced ${oe.synced_count} spool${oe.synced_count!==1?"s":""} with ${oe.errors.length} error${oe.errors.length!==1?"s":""}`}),oe.skipped_count>0&&n.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[n.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(ba,{className:"w-3.5 h-3.5"}),n.jsxs("span",{className:"font-medium",children:[oe.skipped_count," spool",oe.skipped_count!==1?"s":""," skipped"]})]}),oe.skipped_count>5&&n.jsx("button",{onClick:()=>S(!x),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:x?"Show less":"Show all"})]}),n.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(x?oe.skipped:oe.skipped.slice(0,5)).map((me,be)=>n.jsxs("li",{className:"flex items-center gap-2",children:[me.color&&n.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${me.color}`}}),n.jsx("span",{children:me.location}),n.jsxs("span",{className:"text-amber-300/60",children:["- ",me.reason]})]},be)),!x&&oe.skipped_count>5&&n.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",oe.skipped_count-5," more"]})]})]}),oe.errors.length>0&&n.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[n.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),n.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:oe.errors.map((me,be)=>n.jsx("li",{children:me},be))})]})]})]})]})]}),N&&n.jsx(ya,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:de.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>de.mutate(),onCancel:()=>C(!1)}),P&&n.jsx(ya,{title:t("settings.spoolmanAmsSyncTitle"),message:t("settings.spoolmanAmsSyncMessage"),confirmText:t("settings.spoolmanAmsSyncButton"),variant:"warning",isLoading:ue.isPending,loadingText:t("settings.spoolmanAmsSyncing"),onConfirm:()=>ue.mutate(),onCancel:()=>T(!1)})]})}function Brt(){const{t}=vt(),{showToast:e}=ra(),[a,r]=y.useState([]),[i,s]=y.useState(!0),[o,l]=y.useState(""),c=y.useRef(null),[d,u]=y.useState(!1),[m,p]=y.useState(null),[f,g]=y.useState(""),[w,b]=y.useState(""),[x,S]=y.useState(!1),[N,C]=y.useState(new Set),[P,T]=y.useState(!1),[j,F]=y.useState(null),[k,M]=y.useState(!1),q=y.useCallback(async()=>{try{const me=await ne.getSpoolCatalog();r(me)}catch(me){console.error("SpoolCatalogSettings.loadCatalog failed:",me),e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);y.useEffect(()=>{q()},[q]);const I=a.filter(me=>me.name.toLowerCase().includes(o.toLowerCase())),B=async()=>{if(!f.trim()||!w){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const me=await ne.addCatalogEntry({name:f.trim(),weight:parseInt(w)});r(be=>[...be,me].sort((H,J)=>H.name.localeCompare(J.name))),u(!1),g(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch(me){console.error("SpoolCatalogSettings.handleAdd failed:",me),e(t("settings.catalog.addFailed"),"error")}finally{S(!1)}},R=me=>{p(me.id),g(me.name),b(me.weight.toString())},X=()=>{p(null),g(""),b("")},ee=async me=>{if(!f.trim()||!w){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const be=await ne.updateCatalogEntry(me,{name:f.trim(),weight:parseInt(w)});r(H=>H.map(J=>J.id===me?be:J).sort((J,A)=>J.name.localeCompare(A.name))),p(null),g(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch(be){console.error("SpoolCatalogSettings.handleUpdate failed:",be),e(t("settings.catalog.updateFailed"),"error")}finally{S(!1)}},Q=async()=>{if(j)try{await ne.deleteCatalogEntry(j.id),r(me=>me.filter(be=>be.id!==j.id)),e(t("settings.catalog.entryDeleted"),"success")}catch(me){console.error("SpoolCatalogSettings.handleDelete failed:",me),e(t("settings.catalog.deleteFailed"),"error")}finally{F(null)}},le=async()=>{M(!1),s(!0);try{await ne.resetSpoolCatalog(),await q(),e(t("settings.catalog.resetSuccess"),"success")}catch(me){console.error("SpoolCatalogSettings.handleReset failed:",me),e(t("settings.catalog.resetFailed"),"error"),s(!1)}},de=me=>{C(be=>{const H=new Set(be);return H.has(me)?H.delete(me):H.add(me),H})},ue=()=>{N.size===I.length?C(new Set):C(new Set(I.map(me=>me.id)))},Z=async()=>{if(T(!1),N.size!==0)try{const me=await ne.bulkDeleteCatalogEntries([...N]);r(be=>be.filter(H=>!N.has(H.id))),C(new Set),e(t("settings.catalog.bulkDeleted",{count:me.deleted}),"success")}catch(me){console.error("SpoolCatalogSettings.handleBulkDelete failed:",me),e(t("settings.catalog.bulkDeleteFailed"),"error")}},oe=()=>{const me=a.map(({name:A,weight:E})=>({name:A,weight:E})),be=new Blob([JSON.stringify(me,null,2)],{type:"application/json"}),H=URL.createObjectURL(be),J=document.createElement("a");J.href=H,J.download="spool-catalog.json",document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(H),e(t("settings.catalog.exported",{count:a.length}),"success")},fe=async me=>{const be=me.target.files?.[0];if(be){try{const H=await be.text(),J=JSON.parse(H);if(!Array.isArray(J))throw new Error("Invalid format");let A=0,E=0;for(const z of J){if(!z.name||typeof z.weight!="number"){E++;continue}if(a.some(O=>O.name.toLowerCase()===z.name.toLowerCase())){E++;continue}try{const O=await ne.addCatalogEntry({name:z.name,weight:z.weight});r(re=>[...re,O].sort((U,V)=>U.name.localeCompare(V.name))),A++}catch(O){console.error("SpoolCatalogSettings import item failed:",O),E++}}e(t("settings.catalog.imported",{added:A,skipped:E}),"success")}catch(H){console.error("SpoolCatalogSettings.handleImport failed:",H),e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return n.jsxs(Tt,{id:"card-spool-catalog",children:[n.jsxs(fa,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(hc,{className:"w-5 h-5 text-bambu-gray"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),n.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",a.length,")"]})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsxs("button",{onClick:oe,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[n.jsx(Bn,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),n.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[n.jsx(Sr,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),n.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:fe}),n.jsxs("button",{onClick:()=>M(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[n.jsx(vs,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),n.jsxs("button",{onClick:()=>u(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[n.jsx(en,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),N.size>0&&n.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[n.jsx("span",{className:"text-sm text-red-400",children:t("settings.catalog.selectedCount",{count:N.size})}),n.jsxs("button",{onClick:()=>T(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[n.jsx(ea,{className:"w-4 h-4"}),t("settings.catalog.deleteSelected")]}),n.jsx("button",{onClick:()=>C(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),n.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:me=>l(me.target.value)})]}),d&&n.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),n.jsxs("div",{className:"flex gap-2 items-center",children:[n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:f,onChange:me=>g(me.target.value)})}),n.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:w,onChange:me=>b(me.target.value)}),n.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),n.jsxs("button",{onClick:B,disabled:x,className:"px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center gap-1 shrink-0",children:[x?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(_n,{className:"w-4 h-4"}),t("common.add")]}),n.jsx("button",{onClick:()=>{u(!1),g(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:n.jsx($t,{className:"w-4 h-4"})})]})]}),i?n.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[n.jsx(pt,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):n.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:n.jsxs("tr",{children:[n.jsx("th",{className:"px-2 py-2 w-10",children:n.jsx("input",{type:"checkbox",checked:I.length>0&&N.size===I.length,onChange:ue,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),n.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),n.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),n.jsx("th",{className:"px-4 py-2 w-24"})]})}),n.jsx("tbody",{children:I.length===0?n.jsx("tr",{children:n.jsx("td",{colSpan:5,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):I.map(me=>n.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${N.has(me.id)?"bg-bambu-dark":""}`,children:m===me.id?n.jsxs(n.Fragment,{children:[n.jsx("td",{className:"px-2 py-2",children:n.jsx("input",{type:"checkbox",checked:N.has(me.id),onChange:()=>de(me.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("td",{className:"px-4 py-2",children:n.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:f,onChange:be=>g(be.target.value)})}),n.jsx("td",{className:"px-4 py-2",children:n.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:w,onChange:be=>b(be.target.value)})}),n.jsx("td",{className:"px-4 py-2 text-center",children:n.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),n.jsx("td",{className:"px-4 py-2",children:n.jsxs("div",{className:"flex justify-end gap-1",children:[n.jsx("button",{onClick:()=>ee(me.id),disabled:x,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:x?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(_n,{className:"w-4 h-4"})}),n.jsx("button",{onClick:X,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:n.jsx($t,{className:"w-4 h-4"})})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx("td",{className:"px-2 py-2",children:n.jsx("input",{type:"checkbox",checked:N.has(me.id),onChange:()=>de(me.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("td",{className:"px-4 py-2 text-white",children:me.name}),n.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[me.weight,"g"]}),n.jsx("td",{className:"px-4 py-2 text-center",children:me.is_default?n.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):n.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),n.jsx("td",{className:"px-4 py-2",children:n.jsxs("div",{className:"flex justify-end gap-1",children:[n.jsx("button",{onClick:()=>R(me),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:n.jsx(yi,{className:"w-4 h-4"})}),n.jsx("button",{onClick:()=>F(me),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:n.jsx(ea,{className:"w-4 h-4"})})]})})]})},me.id))})]})})]}),j&&n.jsx(ya,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:j.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:Q,onCancel:()=>F(null)}),P&&n.jsx(ya,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:N.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:Z,onCancel:()=>T(!1)}),k&&n.jsx(ya,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:le,onCancel:()=>M(!1)})]})}const qrt=2166136261,Hrt=16777619;function $rt(...t){let e=qrt;const a=new TextEncoder,r=a.encode("__|");for(const i of t)typeof i=="string"?e=SX(e,a.encode(i+"|")):i==null&&(e=SX(e,r));return e>>>0}function SX(t,e){for(const a of e)t^=a,t=Math.imul(t,Hrt)>>>0;return t}function Vrt(t){const e=()=>{t|=0,t=t+1831565813|0;let r=Math.imul(t^t>>>15,1|t);return r=r+Math.imul(r^r>>>7,61|r)^r,(r^r>>>14)>>>0},a=(r,i)=>{if(!Number.isFinite(r)||!Number.isFinite(i))throw new RangeError("from and to must be finite numbers");if(r>i)throw new RangeError("from must be less than or equal to to");return r===i?r:r+e()/4294967295*(i-r)};return{next:()=>e()/4294967295,floatBetween:(r,i)=>a(r,i),intBetween:(r,i)=>{if(!Number.isInteger(r)||!Number.isInteger(i))throw new RangeError("from and to must be integers");return Math.round(a(r,i))}}}const kX={table:{dotCount:5,dotScale:1},preview:{dotCount:8,dotScale:1.5},card:{dotCount:40,dotScale:2},bar:{dotCount:20,dotScale:2},groupheader:{dotCount:80,dotScale:2}},rO=[{value:"",labelKey:"inventory.colorEffect.none"},{value:"sparkle",labelKey:"inventory.colorEffect.sparkle"},{value:"wood",labelKey:"inventory.colorEffect.wood"},{value:"marble",labelKey:"inventory.colorEffect.marble"},{value:"glow",labelKey:"inventory.colorEffect.glow"},{value:"matte",labelKey:"inventory.colorEffect.matte"},{value:"silk",labelKey:"inventory.colorEffect.silk"},{value:"galaxy",labelKey:"inventory.colorEffect.galaxy"},{value:"rainbow",labelKey:"inventory.colorEffect.rainbow"},{value:"metal",labelKey:"inventory.colorEffect.metal"},{value:"translucent",labelKey:"inventory.colorEffect.translucent"},{value:"gradient",labelKey:"inventory.colorEffect.gradient"},{value:"dual-color",labelKey:"inventory.colorEffect.dualColor"},{value:"tri-color",labelKey:"inventory.colorEffect.triColor"},{value:"multicolor",labelKey:"inventory.colorEffect.multicolor"}],Grt="repeating-conic-gradient(#979797 0% 25%, #f5f5f5 0% 50%)",Wrt="12px 12px",Krt={sparkle:(t=0,e="table")=>{const a=Vrt(t),r=kX[e]??kX.table,i=[];for(let s=0;s"repeating-linear-gradient(90deg, rgba(0,0,0,0.18) 0 1px, transparent 1px 6px, rgba(0,0,0,0.08) 6px 7px, transparent 7px 12px)",marble:()=>"repeating-linear-gradient(135deg, rgba(255,255,255,0.18) 0 2px, transparent 2px 8px), repeating-linear-gradient(45deg, rgba(0,0,0,0.10) 0 1px, transparent 1px 7px)",glow:()=>"radial-gradient(circle at 50% 50%, rgba(255,255,255,0.35) 0%, rgba(255,255,255,0) 70%)",matte:()=>"linear-gradient(180deg, rgba(0,0,0,0.10) 0%, rgba(0,0,0,0) 50%, rgba(0,0,0,0.10) 100%)",silk:()=>"linear-gradient(110deg, rgba(255,255,255,0) 30%, rgba(255,255,255,0.30) 50%, rgba(255,255,255,0) 70%)",galaxy:()=>"linear-gradient(110deg, rgba(255,255,255,0) 25%, rgba(255,255,255,0.40) 50%, rgba(255,255,255,0) 75%)",metal:()=>"repeating-linear-gradient(90deg, rgba(255,255,255,0.10) 0 1px, transparent 1px 3px), linear-gradient(180deg, rgba(255,255,255,0.18) 0%, rgba(0,0,0,0.18) 100%)"};function ede(t){const e=t.trim().replace(/^#/,"");return e.length!==6&&e.length!==8||!/^[0-9a-fA-F]+$/.test(e)?null:`#${e}`}function tde(t){return t?t.split(",").map(e=>ede(e)).filter(e=>!!e):[]}function Qrt(t,e,a,r){const i=t?ede(t):null;if(e.length===0)return`linear-gradient(${i??"#808080"}, ${i??"#808080"})`;const s=e.length===1?[e[0],e[0]]:e,o=(a??"").toLowerCase(),l=(r??"").toLowerCase();if(o==="multicolor"||l==="multicolor"){const c=s.length;return`conic-gradient(from 0deg, ${s.map((u,m)=>{const p=(m/c*360).toFixed(3),f=((m+1)/c*360).toFixed(3);return`${u} ${p}deg ${f}deg`}).join(", ")})`}if(l==="dual-color"||l==="tri-color"){const c=s.length;return`linear-gradient(to right, ${s.map((u,m)=>{const p=(m/c*100).toFixed(3),f=((m+1)/c*100).toFixed(3);return`${u} ${p}% ${f}%`}).join(", ")})`}return`linear-gradient(135deg, ${s.join(", ")})`}function Yrt(t,e,a){const r=Krt[t];return r?r(a,e):null}function pj(t){const e=tde(t.extraColors),a=Qrt(t.rgba,e,t.subtype,t.effectType),r=$rt(t.rgba,t.extraColors,t.subtype,t.effectType),i=typeof t.effectType=="string"?Yrt(t.effectType,t.effectSize,r):null,s=[];return i&&(Array.isArray(i)?i:[i]).forEach(l=>{s.push({image:l,size:"cover"})}),s.push({image:a,size:"cover"}),s.push({image:Grt,size:Wrt}),{backgroundImage:s.map(o=>o.image).join(", "),backgroundSize:s.map(o=>o.size).join(", ")}}function xU({rgba:t,extraColors:e,effectType:a,subtype:r,className:i="w-5 h-5",shape:s="circle",style:o,title:l,effectSize:c}){const d=y.useMemo(()=>tde(e),[e]),u=y.useMemo(()=>pj({effectSize:c,rgba:t,extraColors:e,effectType:a,subtype:r}),[c,t,e,a,r]),m=u.backgroundImage,p=u.backgroundSize,f=s==="circle"||s==="pill"?"rounded-full":"rounded",g=l??(d.length>0?d.join(", "):t?`#${t.substring(0,6)}`:void 0);return n.jsx("span",{"data-testid":"filament-swatch",className:`${i} ${f} border border-black/20 inline-block flex-shrink-0`,style:{backgroundImage:m,backgroundSize:p,...o},title:g})}function Xrt(){const{t}=vt(),{showToast:e}=ra(),[a,r]=y.useState([]),[i,s]=y.useState(!0),[o,l]=y.useState(""),[c,d]=y.useState(""),u=y.useRef(null),[m,p]=y.useState(!1),[f,g]=y.useState(null),[w,b]=y.useState(""),[x,S]=y.useState(""),[N,C]=y.useState("#FFFFFF"),[P,T]=y.useState(""),[j,F]=y.useState(""),[k,M]=y.useState(""),[q,I]=y.useState(!1),[B,R]=y.useState(new Set),[X,ee]=y.useState(!1),[Q,le]=y.useState(!1),[de,ue]=y.useState(null),[Z,oe]=y.useState(null),[fe,me]=y.useState(!1),be=y.useCallback(async()=>{try{const ce=await ne.getColorCatalog();r(ce)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);y.useEffect(()=>{be()},[be]);const H=[...new Set(a.map(ce=>ce.manufacturer))].sort(),J=a.filter(ce=>{const he=o===""||ce.manufacturer.toLowerCase().includes(o.toLowerCase())||ce.color_name.toLowerCase().includes(o.toLowerCase())||(ce.material?.toLowerCase().includes(o.toLowerCase())??!1),$=c===""||ce.manufacturer===c;return he&&$}),A=()=>{b(""),S(""),C("#FFFFFF"),T(""),F(""),M("")},E=async()=>{if(!w.trim()||!x.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}I(!0);try{const ce=await ne.addColorEntry({manufacturer:w.trim(),color_name:x.trim(),hex_color:N,material:P.trim()||null,extra_colors:j.trim()||null,effect_type:k.trim()||null});r(he=>[...he,ce].sort(($,L)=>$.manufacturer.localeCompare(L.manufacturer)||($.material||"").localeCompare(L.material||"")||$.color_name.localeCompare(L.color_name))),p(!1),A(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{I(!1)}},z=ce=>{g(ce.id),b(ce.manufacturer),S(ce.color_name),C(ce.hex_color),T(ce.material||""),F(ce.extra_colors||""),M(ce.effect_type||"")},W=()=>{g(null),A()},O=async ce=>{if(!w.trim()||!x.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}I(!0);try{const he=await ne.updateColorEntry(ce,{manufacturer:w.trim(),color_name:x.trim(),hex_color:N,material:P.trim()||null,extra_colors:j.trim()||null,effect_type:k.trim()||null});r($=>$.map(L=>L.id===ce?he:L).sort((L,ae)=>L.manufacturer.localeCompare(ae.manufacturer)||(L.material||"").localeCompare(ae.material||"")||L.color_name.localeCompare(ae.color_name))),g(null),A(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{I(!1)}},re=async()=>{if(Z)try{await ne.deleteColorEntry(Z.id),r(ce=>ce.filter(he=>he.id!==Z.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{oe(null)}},U=async()=>{me(!1),s(!0);try{await ne.resetColorCatalog(),await be(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},V=async()=>{le(!0),ue(null);try{const ce={},he=Jm();he&&(ce.Authorization=`Bearer ${he}`);const $=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:ce});if(!$.ok)throw new Error("Failed to start sync");const L=$.body?.getReader();if(!L)throw new Error("No response body");const ae=new TextDecoder;let ge="";for(;;){const{done:xe,value:Se}=await L.read();if(xe)break;ge+=ae.decode(Se,{stream:!0});const Te=ge.split(` +`),confirmText:t("queue.filamentShort.printAnyway"),variant:"warning",onConfirm:()=>{O.mutate({id:z.itemId,skipFilamentCheck:!0})},onCancel:()=>W(null)}),S&&n.jsx(ya,{title:S.type==="cancel"?t("queue.confirm.cancelTitle"):S.type==="stop"?t("queue.confirm.stopTitle"):t("queue.confirm.removeTitle"),message:S.type==="cancel"?t("queue.confirm.cancelMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):S.type==="stop"?t("queue.confirm.stopMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisPrint")}):t("queue.confirm.removeMessage",{name:S.item.archive_name||S.item.library_file_name||t("queue.confirm.thisItem")}),confirmText:S.type==="cancel"?t("queue.confirm.cancelButton"):S.type==="stop"?t("queue.confirm.stopButton"):t("common.remove"),variant:"danger",onConfirm:()=>{S.type==="cancel"?J.mutate(S.item.id):S.type==="stop"?E.mutate(S.item.id):A.mutate(S.item.id),N(null)},onCancel:()=>N(null)}),p&&n.jsx(ya,{title:t("queue.confirm.clearHistoryTitle"),message:t("queue.confirm.clearHistoryMessage",{count:xe.length}),confirmText:t("queue.clearHistory"),variant:"danger",onConfirm:()=>{U.mutate(),f(!1)},onCancel:()=>f(!1)}),T&&n.jsx(trt,{selectedCount:C.length,printers:be?.map(we=>({id:we.id,name:we.name}))||[],onSave:we=>{Object.keys(we).length>0&&V.mutate({item_ids:C,...we})},onClose:()=>j(!1),isSaving:V.isPending,canControlPrinter:r("printers:control"),t})]})}function nrt({printDates:t,months:e=3}){const a=y.useRef(null),[r,i]=y.useState(0);y.useEffect(()=>{const S=a.current;if(!S)return;const N=new ResizeObserver(C=>{const P=C[0]?.contentRect.width||0;i(P)});return N.observe(S),()=>N.disconnect()},[]);const{weeks:s,monthLabels:o,printCounts:l}=y.useMemo(()=>{const S={};t.forEach(q=>{const I=xE(q);I&&(S[I]=(S[I]||0)+1)});const N=new Date,C=new Date(N);C.setMonth(C.getMonth()-e),C.setDate(C.getDate()-C.getDay());const P=[],T=[];let j=[],F=-1;const k=new Date(C);let M=0;for(;k<=N;)k.getDay()===0&&j.length>0&&(P.push(j),j=[],M++),k.getMonth()!==F&&(T.push({month:k.toLocaleDateString("en-US",{month:"short"}),weekIndex:M}),F=k.getMonth()),j.push(new Date(k)),k.setDate(k.getDate()+1);return j.length>0&&P.push(j),{weeks:P,monthLabels:T,printCounts:S}},[t,e]),c=Math.max(1,...Object.values(l)),d=S=>{if(S===0)return"bg-bambu-dark";const N=S/c;return N<=.25?"bg-bambu-green/30":N<=.5?"bg-bambu-green/50":N<=.75?"bg-bambu-green/75":"bg-bambu-green"},u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=s.length,p=32,f=2,g=r-p-16,w=m>0?Math.floor((g-(m-1)*f)/m):12,b=Math.max(8,Math.min(20,w)),x=b<=10?10:12;return n.jsx("div",{ref:a,className:"w-full flex justify-center",children:r>0&&n.jsxs("div",{children:[n.jsx("div",{className:"flex mb-1",style:{marginLeft:p+4},children:o.map(({month:S,weekIndex:N},C)=>n.jsx("div",{className:"text-bambu-gray",style:{fontSize:x,marginLeft:C===0?0:`${(N-(o[C-1]?.weekIndex||0))*(b+f)-24}px`},children:S},C))}),n.jsxs("div",{className:"flex",style:{gap:f},children:[n.jsx("div",{className:"flex flex-col",style:{gap:f,marginRight:4,width:p},children:u.map((S,N)=>n.jsx("div",{className:"text-bambu-gray flex items-center",style:{width:p,height:b,fontSize:x,visibility:N%2===1?"visible":"hidden"},children:S},S))}),s.map((S,N)=>n.jsx("div",{className:"flex flex-col",style:{gap:f},children:[0,1,2,3,4,5,6].map(C=>{const P=S.find(k=>k.getDay()===C);if(!P)return n.jsx("div",{style:{width:b,height:b}},C);const T=xE(P),j=l[T]||0,F=T===xE(new Date);return n.jsx("div",{className:`rounded-sm ${d(j)} ${F?"ring-1 ring-white":""}`,style:{width:b,height:b},title:`${P.toLocaleDateString()}: ${j} print${j!==1?"s":""}`},C)})},N))]}),n.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray",style:{fontSize:x},children:[n.jsx("span",{children:"Less"}),n.jsxs("div",{className:"flex",style:{gap:f},children:[n.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:b,height:b}}),n.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:b,height:b}})]}),n.jsx("span",{children:"More"})]})]})})}const bX=["weight","prints","time"];function ST({value:t,onChange:e,exclude:a}){const{t:r}=vt(),i={weight:r("stats.filamentByWeight"),prints:r("stats.filamentByPrints"),time:r("stats.filamentByTime")},s=a?bX.filter(o=>!a.includes(o)):bX;return n.jsx("div",{className:"flex gap-0.5 bg-bambu-dark rounded-lg p-0.5",children:s.map(o=>n.jsx("button",{onClick:()=>e(o),className:`px-2 py-0.5 text-xs rounded-md transition-colors ${t===o?"bg-bambu-green text-white":"text-bambu-gray hover:text-white"}`,children:i[o]},o))})}function yh(t){if(t>=1e6){const e=t/1e6;return`${e%1===0?e.toFixed(0):e.toFixed(1)}t`}if(t>=1e3){const e=t/1e3;return`${e%1===0?e.toFixed(0):e.toFixed(1)}kg`}return`${Math.round(t)}g`}const pN=["#00ae42","#3b82f6","#f59e0b","#ef4444","#8b5cf6","#ec4899","#14b8a6","#f97316"],rrt=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],xX=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"];function irt({archives:t,currency:e="$",dateFrom:a,dateTo:r}){const{t:i}=vt(),[s,o]=y.useState("weight"),[l,c]=y.useState("weight"),d=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{const M=Qa(k.completed_at||k.created_at)||new Date,q=`${M.getFullYear()}-${String(M.getMonth()+1).padStart(2,"0")}-${String(M.getDate()).padStart(2,"0")}`,I=F.get(q)||{date:q,filament:0,cost:0,prints:0};I.filament+=k.filament_used_grams||0,I.cost+=k.cost||0,I.prints+=k.quantity||1,F.set(q,I)}),Array.from(F.values()).sort((k,M)=>k.date.localeCompare(M.date)).map(k=>({...k,dateLabel:new Date(k.date).toLocaleDateString("en-US",{month:"short",day:"numeric"})}))},[t]),u=y.useMemo(()=>{if(a&&r)return Math.max((new Date(r).getTime()-new Date(a).getTime())/864e5,0)+1;if(a)return Math.max((Date.now()-new Date(a).getTime())/864e5,0)+1;if(t.length<2)return 0;const F=t.map(k=>new Date(k.completed_at||k.created_at).getTime());return(Math.max(...F)-Math.min(...F))/864e5},[t,a,r]),m=y.useMemo(()=>{if(u>7)return[];const F=new Map,k=u>1;return t.forEach(M=>{const q=Qa(M.completed_at||M.created_at)||new Date,I=q.getHours(),B=`${q.getFullYear()}-${String(q.getMonth()+1).padStart(2,"0")}-${String(q.getDate()).padStart(2,"0")}T${String(I).padStart(2,"0")}`,R=F.get(B)||{date:B,filament:0,cost:0,prints:0};R.filament+=M.filament_used_grams||0,R.cost+=M.cost||0,R.prints+=M.quantity||1,F.set(B,R)}),Array.from(F.values()).sort((M,q)=>M.date.localeCompare(q.date)).map(M=>{const[q,I]=M.date.split("T"),B=new Date(q),R=parseInt(I,10),X=k?`${rrt[B.getDay()]} ${xX[R]}`:xX[R];return{...M,dateLabel:X}})},[t,u]),p=y.useMemo(()=>{if(d.length<=60)return d;const F=new Map;return d.forEach(k=>{const M=new Date(k.date),q=new Date(M);q.setDate(M.getDate()-M.getDay());const I=`${q.getFullYear()}-${String(q.getMonth()+1).padStart(2,"0")}-${String(q.getDate()).padStart(2,"0")}`,B=F.get(I)||{week:I,filament:0,cost:0,prints:0};B.filament+=k.filament,B.cost+=k.cost,B.prints+=k.prints,F.set(I,B)}),Array.from(F.values()).sort((k,M)=>k.week.localeCompare(M.week)).map(k=>({date:k.week,dateLabel:`Week of ${new Date(k.week).toLocaleDateString("en-US",{month:"short",day:"numeric"})}`,...k}))},[d]),f=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{const q=(k.filament_type||"Unknown").split(", ");q.forEach(I=>{const B=(k.filament_used_grams||0)/q.length;F.set(I,(F.get(I)||0)+B)})}),Array.from(F.entries()).map(([k,M])=>({name:k,value:Math.round(M)})).sort((k,M)=>M.value-k.value)},[t]),g=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{(k.filament_type||"Unknown").split(", ").forEach(I=>{F.set(I,(F.get(I)||0)+1)})}),Array.from(F.entries()).map(([k,M])=>({name:k,value:M})).sort((k,M)=>M.value-k.value)},[t]),w=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{const q=(k.filament_type||"Unknown").split(", "),I=(k.actual_time_seconds||k.print_time_seconds||0)/q.length;q.forEach(B=>{F.set(B,(F.get(B)||0)+I)})}),Array.from(F.entries()).map(([k,M])=>({name:k,value:Math.round(M/3600*10)/10})).sort((k,M)=>M.value-k.value)},[t]),b=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(k.status!=="completed"&&k.status!=="failed")return;(k.filament_type||"Unknown").split(", ").forEach(q=>{const I=F.get(q)||{completed:0,failed:0};k.status==="completed"?I.completed++:I.failed++,F.set(q,I)})}),Array.from(F.entries()).filter(([,k])=>k.completed+k.failed>=2).map(([k,M])=>{const q=M.completed+M.failed,I=Math.round(M.completed/q*100);return{name:k,rate:I,total:q}}).sort((k,M)=>M.rate-k.rate)},[t]),x=y.useMemo(()=>{const F=new Map;return t.forEach(k=>{if(!k.filament_color)return;const M=k.filament_color.split(",").map(I=>I.trim()),q=(k.filament_used_grams||0)/M.length;M.forEach(I=>{const B=F.get(I)||{count:0,weight:0};B.count++,B.weight+=q,F.set(I,B)})}),Array.from(F.entries()).map(([k,M])=>({hex:k,value:l==="prints"?M.count:Math.round(M.weight)})).sort((k,M)=>M.value-k.value)},[t,l]),S=s==="weight"?f:s==="prints"?g:w,N=u<=7&&m.length>0?m:p,C=t.reduce((F,k)=>F+(k.filament_used_grams||0),0),P=t.reduce((F,k)=>F+(k.cost||0),0),T=t.reduce((F,k)=>F+(k.quantity||1),0),j=new Set(t.map(F=>F.printer_id).filter(Boolean)).size;return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"grid grid-cols-3 gap-2 max-[640px]:grid-cols-1",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodFilament")}),n.jsx("p",{className:"text-2xl font-bold text-white leading-none",children:yh(C)})]}),n.jsxs("p",{className:"text-xs text-bambu-gray",children:[j," ",i("nav.printers").toLowerCase()]})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.periodCost")}),n.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[e,P.toFixed(2)]})]}),n.jsxs("p",{className:"text-xs text-bambu-gray",children:[T," ",i("common.prints")]})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between gap-2",children:[n.jsx("p",{className:"text-sm text-bambu-gray leading-none",children:i("stats.avgPerPrint")}),n.jsxs("p",{className:"text-2xl font-bold text-white leading-none",children:[T>0?(C/T).toFixed(0):0,"g"]})]}),n.jsxs("p",{className:"text-xs text-bambu-gray",children:[e,T>0?(P/T).toFixed(2):"0.00"," avg"]})]})]}),N.length>0?n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.usageOverTime")}),n.jsx(au,{width:"100%",height:250,children:n.jsxs(w5,{data:N,children:[n.jsx("defs",{children:n.jsxs("linearGradient",{id:"colorFilament",x1:"0",y1:"0",x2:"0",y2:"1",children:[n.jsx("stop",{offset:"5%",stopColor:"#00ae42",stopOpacity:.3}),n.jsx("stop",{offset:"95%",stopColor:"#00ae42",stopOpacity:0})]})}),n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"dateLabel",stroke:"#9ca3af",tick:{fontSize:12},interval:"preserveStartEnd"}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:12},tickFormatter:F=>`${F}g`}),n.jsx(ru,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},labelStyle:{color:"#fff"},formatter:F=>[`${Number(F??0).toFixed(0)}g`,"Filament"]}),n.jsx(qA,{type:"monotone",dataKey:"filament",stroke:"#00ae42",strokeWidth:2,fillOpacity:1,fill:"url(#colorFilament)"})]})})]}):n.jsx("div",{className:"bg-bambu-dark rounded-lg p-8 text-center text-bambu-gray",children:i("stats.noPrintDataInRange")}),n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.byMaterial")}),n.jsx(ST,{value:s,onChange:o})]}),S.length>0?n.jsxs("div",{className:"flex items-center gap-4",children:[n.jsx(au,{width:160,height:160,children:n.jsxs($K,{children:[n.jsx(iI,{data:S,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",children:S.map((F,k)=>n.jsx(Oy,{fill:pN[k%pN.length]},`cell-${k}`))}),n.jsx(ru,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:F=>[s==="weight"?yh(Number(F??0)):s==="time"?`${Number(F??0)}h`:`${F??0}`,s==="weight"?"Usage":s==="time"?"Time":"Prints"]})]})}),n.jsx("div",{className:"flex-1 space-y-2 overflow-hidden",children:S.map((F,k)=>{const M=S.reduce((I,B)=>I+B.value,0),q=M>0?(F.value/M*100).toFixed(0):0;return n.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.jsx("div",{className:"w-3 h-3 rounded-sm flex-shrink-0",style:{backgroundColor:pN[k%pN.length]}}),n.jsx("span",{className:"text-white truncate flex-1",children:F.name}),n.jsxs("span",{className:"text-bambu-gray flex-shrink-0",children:[s==="weight"?yh(F.value):s==="time"?`${F.value}h`:F.value," · ",q,"%"]})]},F.name)})})]}):n.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noFilamentData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-4",children:i("stats.filamentSuccess")}),b.length>0?n.jsx("div",{className:"space-y-1.5",children:b.map(F=>n.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.jsx("span",{className:"text-white truncate w-20 flex-shrink-0",children:F.name}),n.jsx("div",{className:"flex-1 h-1.5 bg-bambu-dark-secondary rounded-full",children:n.jsx("div",{className:`h-full rounded-full transition-all ${F.rate>=90?"bg-status-ok":F.rate>=70?"bg-status-warning":"bg-status-error"}`,style:{width:`${F.rate}%`}})}),n.jsxs("span",{className:`font-medium flex-shrink-0 tabular-nums ${F.rate>=90?"text-status-ok":F.rate>=70?"text-status-warning":"text-status-error"}`,children:[F.rate,"%"]}),n.jsxs("span",{className:"text-bambu-gray flex-shrink-0 text-xs",children:["(",F.total,")"]})]},F.name))}):n.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noArchiveData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:i("stats.colorDistribution")}),n.jsx(ST,{value:l,onChange:c,exclude:["time"]})]}),x.length>0?(()=>{const F=x.reduce((k,M)=>k+M.value,0);return n.jsxs("div",{children:[n.jsxs("div",{className:"relative mx-auto",style:{width:160,height:160},children:[n.jsx(au,{width:"100%",height:"100%",children:n.jsxs($K,{children:[n.jsx(iI,{data:x,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,paddingAngle:2,dataKey:"value",children:x.map((k,M)=>n.jsx(Oy,{fill:k.hex,stroke:"#1a1a1a",strokeWidth:1},`color-${M}`))}),n.jsx(ru,{contentStyle:{backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"},formatter:k=>[l==="weight"?yh(Number(k??0)):`${k??0}`,i(l==="weight"?"stats.filamentByWeight":"stats.filamentByPrints")]})]})}),n.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[n.jsx("span",{className:"text-lg font-bold text-white",children:l==="weight"?yh(F):F}),n.jsxs("span",{className:"text-[10px] text-bambu-gray",children:[x.length," ",x.length===1?"color":"colors"]})]})]}),n.jsx("div",{className:"grid grid-cols-2 gap-x-3 gap-y-1 mt-2",children:x.slice(0,8).map(k=>{const M=F>0?(k.value/F*100).toFixed(0):0;return n.jsxs("div",{className:"flex items-center gap-1.5 text-xs min-w-0",children:[n.jsx("div",{className:"w-2.5 h-2.5 rounded-full flex-shrink-0 border border-black/20",style:{backgroundColor:k.hex}}),n.jsxs("span",{className:"text-bambu-gray truncate",children:[M,"%"]})]},k.hex)})}),x.length>8&&n.jsxs("p",{className:"text-[10px] text-bambu-gray mt-1 text-center",children:["+",x.length-8," more"]})]})})():n.jsx("div",{className:"h-[160px] flex items-center justify-center text-bambu-gray",children:i("stats.noColorData")})]})]})]})}function srt({id:t,title:e,component:a,isHidden:r,size:i,columnSpan:s,onToggleVisibility:o,onToggleSize:l}){const{attributes:c,listeners:d,setNodeRef:u,transform:m,transition:p,isDragging:f}=Yce({id:t}),g={transform:Wy.Transform.toString(m),transition:p,opacity:f?.5:1};return r?null:n.jsxs("div",{ref:u,style:{...g,gridColumn:`span ${s}`},className:`bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary overflow-hidden ${f?"ring-2 ring-bambu-green shadow-lg":""}`,children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/30",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{...c,...d,className:"cursor-grab active:cursor-grabbing p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Drag to reorder",children:n.jsx(Mh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray"})}),n.jsx("h3",{className:"text-sm font-medium text-white",children:e})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("button",{onClick:l,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?n.jsx(EO,{className:"w-4 h-4 text-bambu-gray hover:text-white"}):n.jsx(MT,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),n.jsx("button",{onClick:o,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",title:"Hide widget",children:n.jsx(db,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]})]}),n.jsx("div",{className:"p-4",children:typeof a=="function"?a(i):a})]})}function ort({widgets:t,storageKey:e,columns:a=4,stackBelow:r,hideControls:i=!1,onResetLayout:s,renderControls:o}){const l=()=>{const F={};return t.forEach(k=>{F[k.id]=k.defaultSize||4}),F},[c,d]=y.useState(()=>{const F=localStorage.getItem(e);if(F)try{const k=JSON.parse(F);if(!k.sizes)k.sizes=l();else{const M=l();for(const q in M)q in k.sizes||(k.sizes[q]=M[q])}return k}catch{}return{order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()}}),[u,m]=y.useState(!1),[p,f]=y.useState(!1);y.useEffect(()=>{if(!r)return;const F=window.matchMedia(`(max-width: ${r}px)`),k=q=>{f(q.matches)};k(F);const M=q=>k(q);return F.addEventListener?F.addEventListener("change",M):F.addListener(M),()=>{F.removeEventListener?F.removeEventListener("change",M):F.removeListener(M)}},[r]);const g=r&&p?1:a;y.useEffect(()=>{const F=()=>m(k=>!k);return window.addEventListener("toggle-hidden-panel",F),()=>window.removeEventListener("toggle-hidden-panel",F)},[]),y.useEffect(()=>{localStorage.setItem(e,JSON.stringify(c))},[c,e]),y.useEffect(()=>{const k=t.map(M=>M.id).filter(M=>!c.order.includes(M));k.length>0&&d(M=>({...M,order:[...M.order,...k]}))},[t,c.order]);const w=Tce(yT(cj,{activationConstraint:{distance:8}}),yT(lj,{coordinateGetter:Xce})),b=F=>{const{active:k,over:M}=F;M&&k.id!==M.id&&d(q=>{const I=q.order.indexOf(k.id),B=q.order.indexOf(M.id);return{...q,order:mj(q.order,I,B)}})},x=F=>{d(k=>({...k,hidden:k.hidden.includes(F)?k.hidden.filter(M=>M!==F):[...k.hidden,F]}))},S=F=>{d(k=>{const M=k.sizes[F]||4,q=M===1?2:M===2?4:1;return{...k,sizes:{...k.sizes,[F]:q}}})},N=()=>{const F={order:t.map(k=>k.id),hidden:t.filter(k=>k.defaultVisible===!1).map(k=>k.id),sizes:l()};d(F),s?.()},C=c.order.map(F=>t.find(k=>k.id===F)).filter(Boolean),P=C.filter(F=>!c.hidden.includes(F.id)),T=C.filter(F=>c.hidden.includes(F.id)),j=o?.({hiddenCount:T.length,showHiddenPanel:u,setShowHiddenPanel:m,resetLayout:N});return n.jsxs("div",{className:"space-y-4",children:[j,!i&&!o&&n.jsxs("div",{className:"flex items-center justify-end gap-2",children:[n.jsxs(Me,{variant:"secondary",size:"sm",onClick:N,children:[n.jsx(vs,{className:"w-4 h-4"}),"Reset Layout"]}),T.length>0&&n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>m(!u),children:[n.jsx(Ml,{className:"w-4 h-4"}),T.length," Hidden"]})]}),u&&T.length>0&&n.jsxs("div",{className:"p-4 bg-bambu-dark rounded-xl border border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-sm text-bambu-gray mb-3",children:"Hidden widgets (click to show):"}),n.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(F=>n.jsxs("button",{onClick:()=>x(F.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:[n.jsx(Ml,{className:"w-3 h-3"}),F.title]},F.id))})]}),n.jsx(Vce,{sensors:w,collisionDetection:Ece,onDragEnd:b,children:n.jsx(Kce,{items:P.map(F=>F.id),strategy:bU,children:n.jsx("div",{className:"grid gap-6",style:{gridTemplateColumns:`repeat(${g}, minmax(0, 1fr))`},children:P.map(F=>{const k=c.sizes[F.id]||2,M=Math.min(k,g);return n.jsx(srt,{id:F.id,title:F.title,component:F.component,isHidden:c.hidden.includes(F.id),size:k,columnSpan:M,onToggleVisibility:()=>x(F.id),onToggleSize:()=>S(F.id)},F.id)})})})}),P.length===0&&n.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[n.jsx("p",{children:"All widgets are hidden."}),n.jsx(Me,{className:"mt-4",onClick:N,children:"Reset Layout"})]})]})}function lrt(t){const e=new Date,a=e.getUTCFullYear(),r=e.getUTCMonth(),i=e.getUTCDate(),s=l=>l.toISOString().split("T")[0],o=s(e);switch(t){case"today":return{dateFrom:o,dateTo:o};case"this-week":{const l=e.getUTCDay(),c=new Date(Date.UTC(a,r,i-(l===0?6:l-1)));return{dateFrom:s(c),dateTo:o}}case"this-month":return{dateFrom:s(new Date(Date.UTC(a,r,1))),dateTo:o};case"last-7":return{dateFrom:s(new Date(Date.UTC(a,r,i-6))),dateTo:o};case"last-30":return{dateFrom:s(new Date(Date.UTC(a,r,i-29))),dateTo:o};case"last-90":return{dateFrom:s(new Date(Date.UTC(a,r,i-89))),dateTo:o};case"this-year":return{dateFrom:s(new Date(Date.UTC(a,0,1))),dateTo:o};case"all-time":return{dateFrom:void 0,dateTo:void 0};case"custom":return{}}}const crt=["today","this-week","this-month","last-7","last-30","last-90","this-year","all-time"],drt=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],nO=["12am","1am","2am","3am","4am","5am","6am","7am","8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm","5pm","6pm","7pm","8pm","9pm","10pm","11pm"],f3=[{key:"<30m",max:1800},{key:"30m-1h",max:3600},{key:"1-2h",max:7200},{key:"2-4h",max:14400},{key:"4-8h",max:28800},{key:"8-12h",max:43200},{key:"12-24h",max:86400},{key:"24h+",max:1/0}],hN={backgroundColor:"#2d2d2d",border:"1px solid #3d3d3d",borderRadius:"8px"};function urt({stats:t,currency:e}){const{t:a}=vt(),r=t?.energy_data_warming_up===!0,i=r?a("stats.energyWarmingUpTooltip"):void 0,s=[{icon:Hn,color:"text-bambu-green",label:a("stats.totalPrints"),value:`${t?.total_prints||0}`},{icon:Za,color:"text-blue-400",label:a("stats.printTime"),value:`${t?.total_print_time_hours?.toFixed(1)??"0"}h`},{icon:Hn,color:"text-orange-400",label:a("stats.filamentUsed"),value:yh(t?.total_filament_grams||0)},{icon:rC,color:"text-green-400",label:a("stats.filamentCost"),value:`${e} ${t?.total_cost?.toFixed(2)??"0.00"}`},{icon:Nc,color:"text-yellow-400",label:a("stats.energyUsed"),value:`${t?.total_energy_kwh?.toFixed(3)??"0.000"} kWh`,warning:r,tooltip:i},{icon:rC,color:"text-yellow-500",label:a("stats.energyCost"),value:`${e} ${t?.total_energy_cost?.toFixed(2)??"0.00"}`,warning:r,tooltip:i}];return n.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:s.map(o=>n.jsxs("div",{className:"flex items-start gap-3",title:o.tooltip,children:[n.jsx("div",{className:`p-2 rounded-lg bg-bambu-dark ${o.color}`,children:n.jsx(o.icon,{className:"w-5 h-5"})}),n.jsxs("div",{children:[n.jsxs("p",{className:"text-xs text-bambu-gray flex items-center gap-1",children:[o.label,o.warning&&n.jsx(ba,{className:"w-3 h-3 text-yellow-400","aria-label":o.tooltip})]}),n.jsx("p",{className:"text-xl font-bold text-white",children:o.value})]})]},o.label))})}function mrt({stats:t,printerMap:e,size:a=1}){const{t:r}=vt(),i=(t?.successful_prints||0)+(t?.failed_prints||0),s=i?Math.round((t?.successful_prints||0)/i*100):0,o=a===1?112:a===2?128:144,l=o/2-8,c=l*2*Math.PI;return n.jsxs("div",{className:"flex items-center gap-6",children:[n.jsxs("div",{className:"relative flex-shrink-0",style:{width:o,height:o},children:[n.jsxs("svg",{className:"w-full h-full -rotate-90",children:[n.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),n.jsx("circle",{cx:o/2,cy:o/2,r:l,fill:"none",stroke:"#00ae42",strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${s/100*c} ${c}`})]}),n.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:n.jsxs("span",{className:`font-bold text-white ${a>=2?"text-2xl":"text-xl"}`,children:[s,"%"]})})]}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(fn,{className:"w-4 h-4 text-status-ok flex-shrink-0"}),n.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.successful")}),n.jsx("span",{className:"text-sm text-white font-medium",children:t?.successful_prints||0})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Mn,{className:"w-4 h-4 text-status-error flex-shrink-0"}),n.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.failed")}),n.jsx("span",{className:"text-sm text-white font-medium",children:t?.failed_prints||0})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Xfe,{className:"w-4 h-4 text-status-warning flex-shrink-0"}),n.jsx("span",{className:"text-sm text-bambu-gray",children:r("stats.cancelled")}),n.jsx("span",{className:"text-sm text-white font-medium",children:t?.cancelled_prints||0})]})]}),a>=2&&t?.prints_by_printer&&Object.keys(t.prints_by_printer).length>0&&n.jsxs("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:r("stats.printsByPrinter")}),n.jsx("div",{className:`grid gap-x-6 gap-y-1 ${a===4?"grid-cols-3":"grid-cols-2"}`,style:{width:"fit-content"},children:Object.entries(t.prints_by_printer).map(([d,u])=>n.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[n.jsx("span",{className:"text-bambu-gray truncate max-w-[120px]",children:e.get(d)||`${r("common.printer")} ${d}`}),n.jsx("span",{className:"text-white font-medium",children:u})]},d))})]})]})]})}function prt({stats:t,printerMap:e,size:a=1}){const{t:r}=vt(),i=t?.average_time_accuracy;if(i==null)return n.jsx("div",{className:"flex items-center justify-center h-full",children:n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noTimeAccuracyData")})});const o=(Math.min(150,Math.max(50,i))-50)/100*100,c=(w=>w>=95&&w<=105?"#00ae42":w>105?"#3b82f6":"#f97316")(i),d=i-100,u=a===1?112:a===2?128:144,m=u/2-8,p=m*2*Math.PI,f=a===1?3:a===2?6:999,g=t?.time_accuracy_by_printer?Object.entries(t.time_accuracy_by_printer).slice(0,f):[];return n.jsxs("div",{className:"flex items-center gap-6",children:[n.jsxs("div",{className:"relative flex-shrink-0",style:{width:u,height:u},children:[n.jsxs("svg",{className:"w-full h-full -rotate-90",children:[n.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:"#3d3d3d",strokeWidth:"10"}),n.jsx("circle",{cx:u/2,cy:u/2,r:m,fill:"none",stroke:c,strokeWidth:"10",strokeLinecap:"round",strokeDasharray:`${o/100*p} ${p}`})]}),n.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[n.jsxs("span",{className:`font-bold text-white ${a>=2?"text-2xl":"text-xl"}`,children:[i.toFixed(0),"%"]}),n.jsxs("span",{className:`text-xs ${d>=0?"text-blue-400":"text-orange-400"}`,children:[d>=0?"+":"",d.toFixed(0),"%"]})]})]}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs text-bambu-gray",children:[n.jsx(rJ,{className:"w-3 h-3 flex-shrink-0"}),n.jsx("span",{children:r("stats.perfectEstimate")})]}),g.length>0&&n.jsx("div",{className:`mt-2 ${a===4?"grid grid-cols-3 gap-x-6 gap-y-1":a===2?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,style:{width:"fit-content"},children:g.map(([w,b])=>n.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[n.jsx("span",{className:"text-bambu-gray truncate max-w-[100px]",children:e.get(w)||`${r("common.printer")} ${w}`}),n.jsxs("span",{className:`font-medium ${b>=95&&b<=105?"text-status-ok":b>105?"text-blue-400":"text-status-warning"}`,children:[b.toFixed(0),"%"]})]},w))})]})]})}function hrt({printDates:t,dateFrom:e,dateTo:a}){const{days:r,hourlyCounts:i,maxCount:s}=y.useMemo(()=>{const u=new Date(e+"T00:00:00"),m=new Date(a+"T00:00:00"),p=[],f=x=>`${x.getFullYear()}-${String(x.getMonth()+1).padStart(2,"0")}-${String(x.getDate()).padStart(2,"0")}`,g=new Date(u);for(;g<=m;)p.push({key:f(g),label:g.toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric"})}),g.setDate(g.getDate()+1);const w={};let b=0;return t.forEach(x=>{const S=Qa(x);if(!S)return;const C=`${`${S.getFullYear()}-${String(S.getMonth()+1).padStart(2,"0")}-${String(S.getDate()).padStart(2,"0")}`}-${S.getHours()}`;w[C]=(w[C]||0)+1,w[C]>b&&(b=w[C])}),{days:p,hourlyCounts:w,maxCount:Math.max(1,b)}},[t,e,a]),o=u=>{if(u===0)return"bg-bambu-dark";const m=u/s;return m<=.25?"bg-bambu-green/30":m<=.5?"bg-bambu-green/50":m<=.75?"bg-bambu-green/75":"bg-bambu-green"},l=20,c=2,d=80;return n.jsxs("div",{className:"w-full overflow-x-auto",children:[n.jsxs("div",{className:"inline-flex flex-col",style:{gap:c},children:[n.jsx("div",{className:"flex",style:{gap:c,marginLeft:d+4},children:nO.map((u,m)=>n.jsx("div",{className:"text-bambu-gray text-[10px] text-center",style:{width:l,visibility:m%2===0?"visible":"hidden"},children:u},m))}),r.map(u=>n.jsxs("div",{className:"flex items-center",style:{gap:c},children:[n.jsx("div",{className:"text-bambu-gray text-[10px] flex-shrink-0 truncate",style:{width:d},children:u.label}),Array.from({length:24},(m,p)=>{const f=i[`${u.key}-${p}`]||0;return n.jsx("div",{className:`rounded-sm ${o(f)}`,style:{width:l,height:l},title:`${u.label} ${nO[p]}: ${f} print${f!==1?"s":""}`},p)})]},u.key))]}),n.jsxs("div",{className:"flex items-center gap-2 mt-3 text-bambu-gray text-xs",children:[n.jsx("span",{children:"Less"}),n.jsxs("div",{className:"flex",style:{gap:c},children:[n.jsx("div",{className:"rounded-sm bg-bambu-dark",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/30",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/50",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green/75",style:{width:l,height:l}}),n.jsx("div",{className:"rounded-sm bg-bambu-green",style:{width:l,height:l}})]}),n.jsx("span",{children:"More"})]})]})}function frt({printDates:t,size:e=2,dateFrom:a,dateTo:r}){const i=y.useMemo(()=>a&&r?Math.max((new Date(r).getTime()-new Date(a).getTime())/864e5,0)+1:a?Math.max((Date.now()-new Date(a).getTime())/864e5,0)+1:1/0,[a,r]);if(i<=7&&a&&r)return n.jsx(hrt,{printDates:t,dateFrom:a,dateTo:r});const o=i===1/0?e===1?3:e===2?6:12:Math.max(1,Math.ceil(i/30));return n.jsx(nrt,{printDates:t,months:o})}function grt({stats:t,archives:e,printerMap:a}){const{t:r}=vt(),[i,s]=y.useState("weight"),[o,l]=y.useState("weight"),c=y.useMemo(()=>{const x=new Map;return t?.prints_by_printer&&Object.entries(t.prints_by_printer).forEach(([S,N])=>{const C=x.get(S)||{prints:0,weight:0,time:0};C.prints=N,x.set(S,C)}),e.forEach(S=>{if(!S.printer_id)return;const N=String(S.printer_id),C=x.get(N)||{prints:0,weight:0,time:0};C.weight+=S.filament_used_grams||0,C.time+=S.actual_time_seconds||S.print_time_seconds||0,t?.prints_by_printer||C.prints++,x.set(N,C)}),Array.from(x.entries()).map(([S,N])=>({name:a.get(S)||`${r("common.printer")} ${S}`,value:i==="prints"?N.prints:i==="weight"?Math.round(N.weight):Math.round(N.time/3600*10)/10})).sort((S,N)=>N.value-S.value)},[t,e,a,i,r]),d=y.useMemo(()=>{const x=Array.from({length:24},(S,N)=>({hour:N,label:nO[N],total:0,failures:0}));return e.forEach(S=>{if(!S.started_at)return;const N=Qa(S.started_at);if(!N)return;const C=N.getHours();x[C].total++,S.status==="failed"&&x[C].failures++}),x},[e]),u=y.useMemo(()=>{const x=f3.map(S=>({name:S.key,count:0}));return e.forEach(S=>{const N=S.actual_time_seconds||S.print_time_seconds;if(!(!N||N<=0)){for(let C=0;C{const x=[0,0,0,0,0,0,0],S=new Set;e.forEach(C=>{const P=Qa(C.created_at)||new Date(C.created_at);let T=P.getDay()-1;T<0&&(T=6),o==="prints"?x[T]++:o==="weight"?x[T]+=C.filament_used_grams||0:x[T]+=(C.actual_time_seconds||C.print_time_seconds||0)/3600;const j=new Date(P);j.setDate(P.getDate()-(P.getDay()+6)%7),S.add(`${j.getFullYear()}-${String(j.getMonth()+1).padStart(2,"0")}-${String(j.getDate()).padStart(2,"0")}`)});const N=Math.max(S.size,1);return drt.map((C,P)=>({name:C,avg:Math.round(x[P]/N*10)/10}))},[e,o]),p=x=>({unit:x==="weight"?"g":x==="time"?"h":"",color:x==="weight"?"#00ae42":x==="time"?"#3b82f6":"#f59e0b"}),f=p(i),g=r(i==="weight"?"stats.filamentByWeight":i==="time"?"stats.hours":"common.prints"),w=p(o),b=r(o==="weight"?"stats.avgWeight":o==="time"?"stats.avgTime":"stats.avgPrints");return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printsByPrinter")}),n.jsx(ST,{value:i,onChange:s})]}),c.length>0?n.jsx(au,{width:"100%",height:Math.max(140,c.length*40),children:n.jsxs(Q1,{data:c,layout:"vertical",margin:{left:10},children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{type:"number",stroke:"#9ca3af",tick:{fontSize:11},unit:f.unit}),n.jsx(Fm,{type:"category",dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11},width:100}),n.jsx(ru,{contentStyle:hN,formatter:x=>[i==="weight"?yh(Number(x??0)):`${x??0}${f.unit}`,g]}),n.jsx($x,{dataKey:"value",fill:f.color,radius:[0,4,4,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noPrinterData")})]}),n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printDuration")}),e.length>0?n.jsx(au,{width:"100%",height:160,children:n.jsxs(Q1,{data:u,children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),n.jsx(ru,{contentStyle:hN}),n.jsx($x,{dataKey:"count",name:r("common.prints"),fill:"#00ae42",radius:[4,4,0,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray",children:r("stats.printHabits")}),n.jsx(ST,{value:o,onChange:l})]}),e.length>0?n.jsx(au,{width:"100%",height:160,children:n.jsxs(Q1,{data:m,children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"name",stroke:"#9ca3af",tick:{fontSize:11}}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:11},unit:w.unit}),n.jsx(ru,{contentStyle:hN,formatter:x=>[`${x??0}${w.unit}`,b]}),n.jsx($x,{dataKey:"avg",fill:w.color,radius:[4,4,0,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]}),n.jsxs("div",{className:"bg-bambu-dark rounded-lg p-4",children:[n.jsx("h4",{className:"text-sm font-medium text-bambu-gray mb-3",children:r("stats.printTimeOfDay")}),e.length>0?n.jsx(au,{width:"100%",height:160,children:n.jsxs(Q1,{data:d,children:[n.jsx(Em,{strokeDasharray:"3 3",stroke:"#3d3d3d"}),n.jsx(Dm,{dataKey:"label",stroke:"#9ca3af",tick:{fontSize:10},interval:5}),n.jsx(Fm,{stroke:"#9ca3af",tick:{fontSize:11},allowDecimals:!1}),n.jsx(ru,{contentStyle:hN}),n.jsx($x,{dataKey:"total",name:r("stats.totalPrints"),fill:"#00ae42",radius:[2,2,0,0]}),n.jsx($x,{dataKey:"failures",name:r("stats.failed"),fill:"#ef4444",radius:[2,2,0,0]})]})}):n.jsx("p",{className:"text-bambu-gray text-center py-4",children:r("stats.noArchiveData")})]})]})]})}function brt({archives:t,currency:e,dateFrom:a,dateTo:r}){const{t:i}=vt();return!t||t.length===0?n.jsx("p",{className:"text-bambu-gray text-center py-4",children:i("stats.noPrintData")}):n.jsx(irt,{archives:t,currency:e,dateFrom:a,dateTo:r})}function xrt({size:t=1,dateFrom:e,dateTo:a,createdById:r}){const{t:i}=vt(),s=!!(e||a),{data:o,isLoading:l}=Qe({queryKey:["failureAnalysis",e,a,r??"all"],queryFn:()=>ne.getFailureAnalysis({...s?{dateFrom:e,dateTo:a}:{days:30},createdById:r})});if(l)return n.jsx("div",{className:"flex justify-center py-4",children:n.jsx(pt,{className:"w-6 h-6 text-bambu-green animate-spin"})});if(!o||o.total_prints===0)return n.jsx("p",{className:"text-bambu-gray text-center py-4",children:i(s?"stats.noPrintDataInRange":"stats.noPrintDataLast30Days")});const c=t===1?5:t===2?8:999,d=Object.entries(o.failures_by_reason).sort(([,p],[,f])=>f-p),u=d.slice(0,c),m=d.length>c;return n.jsxs("div",{className:`${t>=2?"flex gap-8":"space-y-4"}`,children:[n.jsxs("div",{className:t>=2?"flex-shrink-0":"",children:[n.jsx("div",{className:"flex items-center gap-4",children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ba,{className:`w-5 h-5 ${o.failure_rate>20?"text-status-error":o.failure_rate>10?"text-status-warning":"text-status-ok"}`}),n.jsxs("span",{className:`font-bold text-white ${t>=2?"text-3xl":"text-2xl"}`,children:[o.failure_rate.toFixed(1),"%"]})]})}),n.jsx("div",{className:"text-sm text-bambu-gray mt-1",children:i("stats.failedPrintsCount",{failed:o.failed_prints,total:o.total_prints})}),o.trend&&o.trend.length>=2&&n.jsx("div",{className:`${t>=2?"mt-4":"mt-2 pt-2 border-t border-bambu-dark-tertiary"}`,children:n.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[n.jsx(US,{className:`w-4 h-4 ${o.trend[o.trend.length-1].failure_rate0&&n.jsxs("div",{className:`flex-1 ${t>=2?"border-l border-bambu-dark-tertiary pl-8":"pt-2"}`,children:[n.jsx("p",{className:"text-xs text-bambu-gray font-medium mb-2",children:t>=2?i("stats.failureReasons"):i("stats.topFailureReasons")}),n.jsx("div",{className:`${t===4?"grid grid-cols-2 gap-x-6 gap-y-1":"space-y-1"}`,children:u.map(([p,f])=>n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("span",{className:`text-white truncate ${t===4?"max-w-[200px]":"max-w-[160px]"}`,children:p||i("common.unknown")}),n.jsx("span",{className:"text-bambu-gray ml-2",children:f})]},p))}),m&&n.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:i("common.more",{count:d.length-c})})]})]})}function yrt({archives:t,currency:e}){const{t:a}=vt(),r=y.useMemo(()=>{const i=[];if(t.length===0)return i;const s=g=>{let w=null,b=0;return t.forEach(x=>{const S=g(x);S&&S>b&&(b=S,w=x)}),{archive:w,value:b}},o=s(g=>g.status==="completed"?g.actual_time_seconds:null);o.archive&&i.push({icon:Za,iconColor:"text-blue-400",label:a("stats.longestPrint"),value:hs(o.value),detail:o.archive.print_name||null});const l=s(g=>g.filament_used_grams);l.archive&&i.push({icon:Hn,iconColor:"text-orange-400",label:a("stats.heaviestPrint"),value:yh(l.value),detail:l.archive.print_name||null});const c=s(g=>g.cost);c.archive&&i.push({icon:rC,iconColor:"text-green-400",label:a("stats.mostExpensivePrint"),value:`${e}${c.value.toFixed(2)}`,detail:c.archive.print_name||null});const d=new Map;t.forEach(g=>{const w=Qa(g.created_at)||new Date(g.created_at),b=`${w.getFullYear()}-${String(w.getMonth()+1).padStart(2,"0")}-${String(w.getDate()).padStart(2,"0")}`;d.set(b,(d.get(b)||0)+1)});let u="",m=0;d.forEach((g,w)=>{g>m&&(m=g,u=w)}),m>1&&i.push({icon:vr,iconColor:"text-purple-400",label:a("stats.busiestDay"),value:`${m} ${a("common.prints")}`,detail:(()=>{const[g,w,b]=u.split("-").map(Number);return new Date(g,w-1,b).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})})()});const p=[...t].filter(g=>g.status==="completed"||g.status==="failed").sort((g,w)=>new Date(w.completed_at||w.created_at).getTime()-new Date(g.completed_at||g.created_at).getTime());let f=0;for(const g of p)if(g.status==="completed")f++;else break;return f>0&&i.push({icon:Nc,iconColor:"text-yellow-400",label:a("stats.successStreak"),value:`${f}`,detail:f===1?a("stats.streakPrint"):a("stats.streakPrints",{count:f})}),i},[t,e,a]);return r.length===0?n.jsx("p",{className:"text-bambu-gray text-center py-4",children:a("stats.noArchiveData")}):n.jsx("div",{className:"space-y-3",children:r.map((i,s)=>n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:`p-1.5 rounded-lg bg-bambu-dark ${i.iconColor}`,children:n.jsx(i.icon,{className:"w-4 h-4"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:i.label}),n.jsxs("div",{className:"flex items-baseline gap-2",children:[n.jsx("span",{className:"text-sm font-bold text-white",children:i.value}),i.detail&&n.jsx("span",{className:"text-xs text-bambu-gray truncate",children:i.detail})]})]})]},s))})}function vrt(){const{t}=vt(),{showToast:e}=ra(),{hasPermission:a,authEnabled:r}=un(),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(0),[u,m]=y.useState(0),[p,f]=y.useState(!1),[g,w]=y.useState(null),[b,x]=y.useState(!1),S=r&&a("stats:filter_by_user"),[N,C]=y.useState(()=>{try{const J=localStorage.getItem("bambusy-stats-timeframe");if(J){const A=JSON.parse(J);if(A.preset)return A}}catch{}return{preset:"all-time",dateFrom:void 0,dateTo:void 0}}),[P,T]=y.useState(!1);y.useEffect(()=>{localStorage.setItem("bambusy-stats-timeframe",JSON.stringify(N))},[N]);const j=y.useMemo(()=>N.preset==="custom"?{dateFrom:N.dateFrom,dateTo:N.dateTo}:lrt(N.preset),[N]);y.useEffect(()=>{const J=()=>{try{const E=localStorage.getItem("bambusy-dashboard-layout-v2");if(E){const z=JSON.parse(E);m(z.hidden?.length||0)}}catch{m(0)}};J(),window.addEventListener("storage",J);const A=setInterval(J,2e3);return()=>{window.removeEventListener("storage",J),clearInterval(A)}},[c]);const F=g!==null?g:void 0,{data:k,isLoading:M,isFetching:q,refetch:I}=Qe({queryKey:["archiveStats",j.dateFrom,j.dateTo,F??"all"],queryFn:()=>ne.getArchiveStats({dateFrom:j.dateFrom,dateTo:j.dateTo,createdById:F})}),{data:B}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),{data:R,isFetching:X,refetch:ee}=Qe({queryKey:["archivesSlim",j.dateFrom,j.dateTo,F??"all"],queryFn:()=>ne.getArchivesSlim(j.dateFrom,j.dateTo,F)}),{data:Q}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),{data:le}=Qe({queryKey:["users"],queryFn:ne.getUsers,enabled:S}),de=y.useMemo(()=>g===null?t("stats.allUsers","All Users"):g===-1?t("stats.noUser","No User (System)"):le?.find(J=>J.id===g)?.username??"?",[g,le,t]),ue=async J=>{l(!1),s(!0);try{const{blob:A,filename:E}=await ne.exportStats({format:J,days:90,createdById:F}),z=URL.createObjectURL(A),W=document.createElement("a");W.href=z,W.download=E,W.click(),URL.revokeObjectURL(z),e(t("stats.exportDownloaded"))}catch{e(t("stats.exportFailed"),"error")}finally{s(!1)}},Z=async()=>{f(!0);try{const J=await ne.recalculateCosts();await Promise.all([I(),ee()]),e(t("stats.recalculatedCosts",{count:J.updated}))}catch{e(t("stats.recalculateFailed"),"error")}finally{f(!1)}},oe=(q||X)&&!M,fe=Go(Q?.currency||"USD"),me=new Map(B?.map(J=>[String(J.id),J.name])||[]),be=y.useMemo(()=>R?.map(J=>J.created_at)||[],[R]);if(M)return n.jsx("div",{className:"p-4 md:p-8",children:n.jsx("div",{className:"text-center py-12 text-bambu-gray",children:t("stats.loadingStats")})});const H=[{id:"quick-stats",title:t("stats.quickStats"),component:n.jsx(urt,{stats:k,currency:fe}),defaultSize:2},{id:"success-rate",title:t("stats.successRate"),component:J=>n.jsx(mrt,{stats:k,printerMap:me,size:J}),defaultSize:1},{id:"time-accuracy",title:t("stats.timeAccuracy"),component:J=>n.jsx(prt,{stats:k,printerMap:me,size:J}),defaultSize:1},{id:"failure-analysis",title:t("stats.failureAnalysis"),component:J=>n.jsx(xrt,{size:J,dateFrom:j.dateFrom,dateTo:j.dateTo,createdById:F}),defaultSize:1},{id:"print-activity",title:t("stats.printActivity"),component:J=>n.jsx(frt,{printDates:be,size:J,dateFrom:j.dateFrom,dateTo:j.dateTo}),defaultSize:2},{id:"records",title:t("stats.records"),component:n.jsx(yrt,{archives:R||[],currency:fe}),defaultSize:1},{id:"printer-stats",title:t("stats.printerStats"),component:n.jsx(grt,{stats:k,archives:R||[],printerMap:me}),defaultSize:4},{id:"filament-trends",title:t("stats.filamentTrends"),component:n.jsx(brt,{archives:R||[],currency:fe,dateFrom:j.dateFrom,dateTo:j.dateTo}),defaultSize:4}];return n.jsxs("div",{className:"p-4 md:p-8",children:[n.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6",children:[n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("h1",{className:"text-2xl font-bold text-white flex items-center gap-3",children:[n.jsx(WZ,{className:"w-7 h-7 text-bambu-green"}),t("stats.title")]}),oe&&n.jsx(pt,{className:"w-5 h-5 text-bambu-green animate-spin"})]}),n.jsx("p",{className:"text-bambu-gray mt-1",children:t("stats.subtitle")})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[u>0&&n.jsxs(Me,{variant:"secondary",onClick:()=>{window.dispatchEvent(new CustomEvent("toggle-hidden-panel"))},children:[n.jsx(Ml,{className:"w-4 h-4"}),t("stats.hiddenCount",{count:u})]}),n.jsxs(Me,{variant:"secondary",onClick:()=>{localStorage.removeItem("bambusy-dashboard-layout-v2"),d(J=>J+1),e(t("stats.layoutReset"))},disabled:!a("settings:update"),title:a("settings:update")?void 0:t("stats.noPermissionResetLayout"),children:[n.jsx(vs,{className:"w-4 h-4"}),t("stats.resetLayout")]}),n.jsxs(Me,{variant:"secondary",onClick:Z,disabled:p||!a("archives:update_all"),title:a("archives:update_all")?t("stats.recalculateCostsHint"):t("stats.noPermissionRecalculate"),children:[p?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(pge,{className:"w-4 h-4"}),t("stats.recalculateCosts")]}),n.jsxs("div",{className:"relative",children:[n.jsxs(Me,{variant:"secondary",onClick:()=>l(!o),disabled:i,children:[i?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(sC,{className:"w-4 h-4"}),t("stats.exportStats")]}),o&&n.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:[n.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:()=>ue("csv"),children:[n.jsx(Bs,{className:"w-4 h-4"}),t("stats.exportAsCsv")]}),n.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:()=>ue("xlsx"),children:[n.jsx(sC,{className:"w-4 h-4"}),t("stats.exportAsExcel")]})]})]}),S&&le&&le.length>0&&n.jsxs("div",{className:"relative",children:[n.jsxs(Me,{variant:"secondary",onClick:()=>x(!b),children:[n.jsx(Sm,{className:"w-4 h-4"}),de,n.jsx(Da,{className:"w-3 h-3"})]}),b&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),n.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 p-2 max-h-64 overflow-y-auto",children:[n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===null?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(null),x(!1)},children:t("stats.allUsers","All Users")}),n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===-1?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(-1),x(!1)},children:t("stats.noUser","No User (System)")}),n.jsx("div",{className:"border-t border-bambu-dark-tertiary my-1"}),le.map(J=>n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${g===J.id?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{w(J.id),x(!1)},children:J.username},J.id))]})]})]}),n.jsxs("div",{className:"relative",children:[n.jsxs(Me,{variant:"secondary",onClick:()=>T(!P),children:[n.jsx(vr,{className:"w-4 h-4"}),t(`stats.timeframe.${N.preset}`),n.jsx(Da,{className:"w-3 h-3"})]}),P&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>T(!1)}),n.jsxs("div",{className:"absolute right-0 top-full mt-1 w-64 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2",children:[crt.map(J=>n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${N.preset===J?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>{C({preset:J,dateFrom:void 0,dateTo:void 0}),T(!1)},children:t(`stats.timeframe.${J}`)},J)),n.jsx("div",{className:"border-t border-bambu-dark-tertiary my-2"}),n.jsx("button",{className:`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${N.preset==="custom"?"bg-bambu-green text-white":"text-white hover:bg-bambu-dark-tertiary"}`,onClick:()=>C(J=>({...J,preset:"custom"})),children:t("stats.timeframe.custom")}),N.preset==="custom"&&n.jsxs("div",{className:"mt-2 px-1 pb-1 space-y-2",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.from")}),n.jsx("input",{type:"date",value:N.dateFrom||"",max:N.dateTo||new Date().toISOString().split("T")[0],onChange:J=>C(A=>({...A,dateFrom:J.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-xs text-bambu-gray block mb-1",children:t("stats.timeframe.to")}),n.jsx("input",{type:"date",value:N.dateTo||"",min:N.dateFrom,max:new Date().toISOString().split("T")[0],onChange:J=>C(A=>({...A,dateTo:J.target.value||void 0})),className:"w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"})]}),n.jsx(Me,{variant:"primary",onClick:()=>T(!1),className:"w-full",children:t("common.apply")})]})]})]})]})]})]}),n.jsx(ort,{widgets:H,storageKey:"bambusy-dashboard-layout-v2",stackBelow:640,hideControls:!0},c)]})}function fN(t){return t.length<8?"tooShort":/[A-Z]/.test(t)?/[a-z]/.test(t)?/\d/.test(t)?/[^A-Za-z0-9]/.test(t)?null:"needsSpecial":"needsDigit":"needsLowercase":"needsUppercase"}function wrt(){const{t}=vt(),e=ta(),{showToast:a}=ra(),r=y.useRef(null),[i,s]=y.useState(null),{data:o,isLoading:l}=Qe({queryKey:["slicer-bundles"],queryFn:ne.listSlicerBundles}),c=lt({mutationFn:m=>ne.importSlicerBundle(m),onSuccess:m=>{e.invalidateQueries({queryKey:["slicer-bundles"]}),a(t("settings.slicerBundles.uploadSuccess",{defaultValue:"Imported {{name}}",name:m.printer_preset_name}),"success"),r.current&&(r.current.value="")},onError:m=>{a(t("settings.slicerBundles.uploadError",{defaultValue:"Bundle upload failed: {{message}}",message:m.message}),"error"),r.current&&(r.current.value="")}}),d=lt({mutationFn:m=>ne.deleteSlicerBundle(m),onSuccess:()=>{e.invalidateQueries({queryKey:["slicer-bundles"]}),s(null),a(t("settings.slicerBundles.deleteSuccess",{defaultValue:"Bundle removed"}),"success")},onError:m=>{a(t("settings.slicerBundles.deleteError",{defaultValue:"Bundle delete failed: {{message}}",message:m.message}),"error"),s(null)}}),u=m=>{const p=m.target.files?.[0];p&&c.mutate(p)};return n.jsxs(Tt,{children:[n.jsx(fa,{children:n.jsxs("h3",{className:"text-base font-semibold text-white flex items-center gap-2",children:[n.jsx(Hn,{className:"w-4 h-4 text-bambu-green"}),t("settings.slicerBundles.title",{defaultValue:"Slicer Bundles"})]})}),n.jsxs(Mt,{className:"space-y-3",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.slicerBundles.description",{defaultValue:'Import a Printer Preset Bundle (.bbscfg) exported from BambuStudio (File → Export → Export Preset Bundle → "Printer preset bundle"). Once imported, slice requests can pick presets from the bundle by name without re-uploading the JSON profile triplet.'})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{ref:r,type:"file",accept:".bbscfg,.zip,application/zip",onChange:u,className:"hidden",disabled:c.isPending}),n.jsx(Me,{variant:"primary",onClick:()=>r.current?.click(),disabled:c.isPending,children:c.isPending?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),t("settings.slicerBundles.uploading",{defaultValue:"Uploading…"})]}):n.jsxs(n.Fragment,{children:[n.jsx(Sr,{className:"w-4 h-4"}),t("settings.slicerBundles.uploadButton",{defaultValue:"Upload bundle"})]})})]}),l?n.jsxs("div",{className:"flex items-center gap-2 text-sm text-bambu-gray",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),t("settings.slicerBundles.loading",{defaultValue:"Loading bundles…"})]}):o&&o.length>0?n.jsx("ul",{className:"divide-y divide-bambu-dark-tertiary border border-bambu-dark-tertiary rounded-lg",children:o.map(m=>n.jsxs("li",{className:"flex items-center justify-between px-3 py-2 hover:bg-bambu-dark-tertiary/30",children:[n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("p",{className:"text-sm text-white truncate",children:m.printer_preset_name}),n.jsxs("p",{className:"text-xs text-bambu-gray mt-0.5",children:[t("settings.slicerBundles.summary",{defaultValue:"{{processCount}} process · {{filamentCount}} filament presets",processCount:m.process.length,filamentCount:m.filament.length}),m.version&&` · v${m.version}`]})]}),n.jsx("button",{type:"button",onClick:()=>s(m),disabled:d.isPending,className:"ml-3 p-1.5 text-bambu-gray hover:text-red-400 disabled:opacity-40","aria-label":t("settings.slicerBundles.delete",{defaultValue:"Delete"}),children:n.jsx(ea,{className:"w-4 h-4"})})]},m.id))}):n.jsx("p",{className:"text-sm text-bambu-gray italic",children:t("settings.slicerBundles.empty",{defaultValue:"No bundles imported yet."})})]}),i&&n.jsx(ya,{title:t("settings.slicerBundles.confirmDeleteTitle",{defaultValue:"Remove this bundle?"}),message:t("settings.slicerBundles.confirmDeleteMessage",{defaultValue:'Slice requests that reference "{{name}}" will fail until the bundle is re-imported.',name:i.printer_preset_name}),confirmText:t("common.delete",{defaultValue:"Delete"}),variant:"danger",isLoading:d.isPending,onConfirm:()=>d.mutate(i.id),onCancel:()=>s(null)})]})}const yX=90,vX=365;function g3(t){return t?new Date(t).toLocaleString():"—"}function Srt(t){return new Date(t).getTime(){if(u.preventDefault(),!!r.trim()){c(!0);try{const m=await ne.createLongLivedCameraToken({name:r.trim(),expires_in_days:s});t(m),i(""),o(yX),a(e("cameraTokens.toast.created","Token created"))}catch(m){a(m instanceof Error?m.message:e("cameraTokens.toast.createFailed","Failed to create token"),"error")}finally{c(!1)}}};return n.jsxs("form",{onSubmit:d,className:"bg-bambu-dark-secondary rounded-lg p-4 mb-6 border border-bambu-dark-tertiary",children:[n.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:e("cameraTokens.create.title","Create new token")}),n.jsxs("div",{className:"grid gap-3 md:grid-cols-[1fr_140px_auto]",children:[n.jsx("input",{type:"text",maxLength:100,required:!0,value:r,onChange:u=>i(u.target.value),placeholder:e("cameraTokens.create.namePlaceholder","e.g. Home Assistant"),className:"px-3 py-2 bg-bambu-dark rounded-md text-white border border-bambu-dark-tertiary focus:border-bambu-green focus:outline-none","aria-label":e("cameraTokens.create.nameLabel","Token name")}),n.jsx("input",{type:"number",min:1,max:vX,required:!0,value:s,onChange:u=>{const m=Number(u.target.value);o(Math.min(Math.max(m,1),vX))},className:"px-3 py-2 bg-bambu-dark rounded-md text-white border border-bambu-dark-tertiary focus:border-bambu-green focus:outline-none","aria-label":e("cameraTokens.create.daysLabel","Days until expiry")}),n.jsxs("button",{type:"submit",disabled:l||!r.trim(),className:"flex items-center gap-2 px-4 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90 disabled:opacity-50 disabled:cursor-not-allowed",children:[n.jsx(en,{className:"w-4 h-4"}),e("cameraTokens.create.submit","Create")]})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-2",children:e("cameraTokens.create.hint","Maximum lifetime is 365 days. The token value is shown only once on creation — copy it now.")})]})}function _rt({token:t,onConfirm:e,onCancel:a}){const{t:r}=vt();return n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4",role:"dialog","aria-modal":"true",children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-md w-full border border-red-500/40",children:[n.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[n.jsx(ba,{className:"w-6 h-6 text-red-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:r("cameraTokens.confirmRevoke.title","Revoke this token?")}),n.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:r("cameraTokens.confirmRevoke.body",'Any device using "{{name}}" will lose access immediately. This cannot be undone.',{name:t.name})})]})]}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{type:"button",onClick:a,className:"px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80",children:r("cameraTokens.confirmRevoke.cancel","Cancel")}),n.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600",children:r("cameraTokens.confirmRevoke.confirm","Revoke")})]})]})})}function Nrt({token:t,onClose:e}){const{t:a}=vt(),{showToast:r}=ra(),i=t.token??"",s=async()=>{if(i)try{if(navigator.clipboard&&window.isSecureContext)await navigator.clipboard.writeText(i);else{const o=document.createElement("textarea");o.value=i,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o);try{o.select(),document.execCommand("copy")}finally{document.body.removeChild(o)}}r(a("cameraTokens.toast.copied","Copied to clipboard"))}catch{r(a("cameraTokens.toast.copyFailed","Copy failed — select and copy manually"),"error")}};return n.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4",children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg p-6 max-w-2xl w-full border border-bambu-green/40",children:[n.jsxs("div",{className:"flex items-start gap-3 mb-4",children:[n.jsx(ba,{className:"w-6 h-6 text-yellow-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("cameraTokens.created.title","Token created — copy it now")}),n.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:a("cameraTokens.created.warning","This is the only time this token will be visible. After you close this dialog you can never view it again.")})]})]}),n.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[n.jsx("code",{className:"flex-1 px-3 py-2 bg-bambu-dark rounded-md text-bambu-green text-xs break-all font-mono select-all",children:i}),n.jsxs("button",{type:"button",onClick:s,className:"flex items-center gap-2 px-3 py-2 bg-bambu-green text-white rounded-md hover:bg-bambu-green/90",children:[n.jsx(xi,{className:"w-4 h-4"}),a("cameraTokens.created.copy","Copy")]})]}),n.jsx("div",{className:"flex justify-end",children:n.jsx("button",{type:"button",onClick:e,className:"px-4 py-2 bg-bambu-dark-tertiary text-white rounded-md hover:bg-bambu-dark-tertiary/80",children:a("cameraTokens.created.dismiss","I've saved it")})})]})})}function Crt({token:t,showOwner:e,ownerLabel:a,onRevoke:r}){const{t:i}=vt(),s=Srt(t.expires_at);return n.jsxs("tr",{className:"border-b border-bambu-dark-tertiary last:border-b-0",children:[n.jsx("td",{className:"py-3 px-3 text-white",children:t.name}),e&&n.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:a}),n.jsxs("td",{className:"py-3 px-3 text-bambu-gray font-mono text-xs",children:[t.lookup_prefix,"…"]}),n.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:g3(t.created_at)}),n.jsxs("td",{className:`py-3 px-3 ${s?"text-red-400":"text-bambu-gray"}`,children:[g3(t.expires_at),s&&n.jsx("span",{className:"ml-2 px-2 py-0.5 text-xs bg-red-500/20 text-red-300 rounded",children:i("cameraTokens.list.expired","Expired")})]}),n.jsx("td",{className:"py-3 px-3 text-bambu-gray",children:g3(t.last_used_at)}),n.jsx("td",{className:"py-3 px-3 text-right",children:n.jsxs("button",{type:"button",onClick:()=>r(t.id),className:"inline-flex items-center gap-1 px-2 py-1 text-sm text-red-400 hover:text-red-300",title:i("cameraTokens.list.revoke","Revoke"),children:[n.jsx(ea,{className:"w-4 h-4"}),i("cameraTokens.list.revoke","Revoke")]})})]})}function wX({tokens:t,showOwner:e,userIdToName:a,onRevoke:r,emptyMessage:i}){const{t:s}=vt();return t.length===0?n.jsx("p",{className:"text-sm text-bambu-gray italic",children:i}):n.jsx("div",{className:"overflow-x-auto",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{className:"text-bambu-gray text-left border-b border-bambu-dark-tertiary",children:n.jsxs("tr",{children:[n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.name","Name")}),e&&n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.owner","Owner")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.prefix","Prefix")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.created","Created")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.expires","Expires")}),n.jsx("th",{className:"py-2 px-3 font-medium",children:s("cameraTokens.list.lastUsed","Last used")}),n.jsx("th",{className:"py-2 px-3"})]})}),n.jsx("tbody",{children:t.map(o=>n.jsx(Crt,{token:o,showOwner:e,ownerLabel:a?.get(o.user_id)??`#${o.user_id}`,onRevoke:r},o.id))})]})})}function Prt(){const{t}=vt(),{user:e,isAdmin:a}=un(),{showToast:r}=ra(),[i,s]=y.useState([]),[o,l]=y.useState([]),[c,d]=y.useState(new Map),[u,m]=y.useState(!0),[p,f]=y.useState(null),[g,w]=y.useState(null),b=async()=>{m(!0);try{const C=await ne.listMyLongLivedCameraTokens();if(s(C),a){const P=await ne.listAllLongLivedCameraTokens();l(P);try{const T=await ne.getUsers();d(new Map(T.map(j=>[j.id,j.username])))}catch{d(new Map)}}}catch(C){r(C instanceof Error?C.message:t("cameraTokens.toast.loadFailed","Failed to load tokens"),"error")}finally{m(!1)}};y.useEffect(()=>{b()},[a]);const x=async C=>{const P=[...i,...o].find(T=>T.id===C);P&&w(P)},S=async()=>{if(!g)return;const C=g.id;w(null);try{await ne.revokeLongLivedCameraToken(C),r(t("cameraTokens.toast.revoked","Token revoked")),await b()}catch(P){r(P instanceof Error?P.message:t("cameraTokens.toast.revokeFailed","Failed to revoke token"),"error")}},N=y.useMemo(()=>o.filter(C=>C.user_id!==e?.id),[o,e?.id]);return n.jsxs(n.Fragment,{children:[n.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:t("cameraTokens.description","Long-lived tokens for embedding the camera stream into Home Assistant, Frigate, kiosks, or any other tool that needs a stable URL. Each token is camera-stream-only and can be revoked at any time.")}),n.jsx(krt,{onCreated:C=>{f(C),b()}}),n.jsxs("div",{className:"mb-6",children:[n.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:t("cameraTokens.list.myTitle","My tokens")}),u?n.jsx("p",{className:"text-sm text-bambu-gray",children:t("cameraTokens.loading","Loading…")}):n.jsx(wX,{tokens:i,onRevoke:x,emptyMessage:t("cameraTokens.list.empty","No tokens yet.")})]}),a&&n.jsxs("div",{children:[n.jsx("h3",{className:"text-base font-semibold text-white mb-3",children:t("cameraTokens.list.allTitle","All users (admin view)")}),n.jsx(wX,{tokens:N,showOwner:!0,userIdToName:c,onRevoke:x,emptyMessage:t("cameraTokens.list.empty","No tokens yet.")})]}),p&&n.jsx(Nrt,{token:p,onClose:()=>f(null)}),g&&n.jsx(_rt,{token:g,onConfirm:()=>{S()},onCancel:()=>w(null)})]})}function Trt({plug:t,onEdit:e}){const{t:a}=vt(),r=ta(),{showToast:i}=ra(),[s,o]=y.useState(!1),[l,c]=y.useState(!1),[d,u]=y.useState(!1),[m,p]=y.useState(!1),{data:f,isLoading:g}=Qe({queryKey:["smart-plug-status",t.id],queryFn:()=>ne.getSmartPlugStatus(t.id),refetchInterval:3e4}),{data:w}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),b=w?.find(M=>M.id===t.printer_id),x=lt({mutationFn:M=>ne.controlSmartPlug(t.id,M),onMutate:async M=>{await r.cancelQueries({queryKey:["smart-plug-status",t.id]});const q=r.getQueryData(["smart-plug-status",t.id]),I=M==="on"?"ON":M==="off"||f?.state==="ON"?"OFF":"ON";return r.setQueryData(["smart-plug-status",t.id],B=>({...B,state:I})),{previousStatus:q}},onError:(M,q,I)=>{I?.previousStatus&&r.setQueryData(["smart-plug-status",t.id],I.previousStatus),i(a("smartPlugs.failedToTurn",{action:q,name:t.name}),"error")},onSettled:()=>{setTimeout(()=>{r.invalidateQueries({queryKey:["smart-plug-status",t.id]}),r.invalidateQueries({queryKey:["smart-plugs"]})},1e3)}}),S=lt({mutationFn:M=>ne.updateSmartPlug(t.id,M),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&(r.invalidateQueries({queryKey:["smartPlugByPrinter",t.printer_id]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]}))}}),N=lt({mutationFn:()=>ne.deleteSmartPlug(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),t.printer_id&&r.invalidateQueries({queryKey:["scriptPlugsByPrinter",t.printer_id]})}}),C=f?.state==="ON",P=t.plug_type==="mqtt"&&f?.energy?.power!==null&&f?.energy?.power!==void 0,T=(f?.reachable??!1)||P,j=x.isPending,k=(()=>{if(t.plug_type!=="tasmota"||!t.ip_address)return null;const M=t.ip_address;return t.username&&t.password?`http://${encodeURIComponent(t.username)}:${encodeURIComponent(t.password)}@${M}/`:`http://${M}/`})();return n.jsxs(n.Fragment,{children:[n.jsx(Tt,{className:"relative",children:n.jsxs(Mt,{className:"p-4",children:[n.jsxs("div",{className:"flex items-start justify-between gap-2 mb-3",children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[n.jsx("div",{className:`p-2 rounded-lg flex-shrink-0 ${t.plug_type==="mqtt"?T?"bg-teal-500/20":"bg-red-500/20":T?C?"bg-bambu-green/20":"bg-bambu-dark":"bg-red-500/20"}`,children:t.plug_type==="mqtt"?n.jsx(FO,{className:`w-5 h-5 ${T?"text-teal-400":"text-red-400"}`}):t.plug_type==="homeassistant"?n.jsx(ES,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):t.plug_type==="rest"?n.jsx(ro,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`}):n.jsx(xc,{className:`w-5 h-5 ${T?C?"text-bambu-green":"text-bambu-gray":"text-red-400"}`})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("h3",{className:"font-medium text-white truncate",children:t.name}),n.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.plug_type==="rest"?t.rest_on_url??t.rest_off_url??void 0:t.ip_address??void 0,children:t.plug_type==="mqtt"?t.mqtt_topic:t.plug_type==="homeassistant"?t.ha_entity_id:t.plug_type==="rest"?t.rest_on_url||t.rest_off_url:t.ip_address})]})]}),n.jsxs("div",{className:"flex flex-col items-end gap-1 flex-shrink-0",children:[g?n.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin"}):t.plug_type==="mqtt"?n.jsxs("div",{className:"flex items-center gap-1.5 text-sm whitespace-nowrap",children:[n.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&&n.jsx("span",{className:"text-status-ok",children:"✓"})]}):t.plug_type==="homeassistant"?n.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[n.jsx("span",{className:"px-1 py-0.5 bg-blue-500/20 text-blue-400 text-[10px] font-medium rounded",children:"HA"}),n.jsx("span",{className:T?C?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?f?.state||"?":a("smartPlugs.offline")})]}):t.plug_type==="rest"?n.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[n.jsx("span",{className:"px-1 py-0.5 bg-purple-500/20 text-purple-400 text-[10px] font-medium rounded",children:"REST"}),n.jsx("span",{className:T?C?"text-status-ok":"text-bambu-gray":"text-status-error",children:T?f?.state||"?":a("smartPlugs.offline")})]}):T?n.jsxs("div",{className:"flex items-center gap-1 text-sm",children:[n.jsx(Dh,{className:"w-4 h-4 text-status-ok"}),n.jsx("span",{className:C?"text-status-ok":"text-bambu-gray",children:f?.state||a("smartPlugs.unknown")})]}):n.jsxs("div",{className:"flex items-center gap-1 text-sm text-status-error",children:[n.jsx(pu,{className:"w-4 h-4"}),n.jsx("span",{children:a("smartPlugs.offline")})]}),k&&n.jsxs("a",{href:k,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:a("smartPlugs.openPlugAdminPage"),children:[n.jsx(En,{className:"w-3 h-3"}),a("smartPlugs.admin")]})]})]}),b&&n.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[n.jsxs("span",{className:"text-xs text-bambu-gray",children:[a("smartPlugs.linkedTo")," "]}),n.jsx("span",{className:"text-sm text-white",children:b.name})]}),(t.power_alert_enabled||t.schedule_enabled||t.plug_type==="mqtt")&&n.jsxs("div",{className:"flex flex-wrap gap-1.5 mb-3",children:[t.plug_type==="mqtt"&&n.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:[n.jsx(Ml,{className:"w-3 h-3"}),a("smartPlugs.monitorOnly")]}),t.power_alert_enabled&&n.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:[n.jsx(Th,{className:"w-3 h-3"}),a("smartPlugs.alerts")]}),t.schedule_enabled&&n.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:[n.jsx(vr,{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?a("smartPlugs.scheduleOn",{time:t.schedule_on_time}):a("smartPlugs.scheduleOff",{time:t.schedule_off_time})]})]}),t.plug_type!=="mqtt"&&n.jsxs("div",{className:"flex gap-2 mb-3",children:[n.jsxs(Me,{size:"sm",variant:C?"primary":"secondary",disabled:!T||j,onClick:()=>c(!0),className:"flex-1",children:[j?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Su,{className:"w-4 h-4"}),a("smartPlugs.on")]}),n.jsxs(Me,{size:"sm",variant:C?"secondary":"primary",disabled:!T||j,onClick:()=>u(!0),className:"flex-1",children:[j?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(IS,{className:"w-4 h-4"}),a("smartPlugs.off")]})]}),t.plug_type==="mqtt"&&f?.energy&&n.jsxs("div",{className:"flex gap-2 mb-3 px-3 py-2 bg-bambu-dark rounded-lg",children:[f.energy.power!==null&&f.energy.power!==void 0&&n.jsxs("div",{className:"flex-1 text-center",children:[n.jsxs("p",{className:"text-lg font-semibold text-white",children:[Math.round(f.energy.power),"W"]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.power")})]}),f.energy.today!==null&&f.energy.today!==void 0&&n.jsxs("div",{className:"flex-1 text-center border-l border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-lg font-semibold text-white",children:f.energy.today.toFixed(3)}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.kwhToday")})]})]}),n.jsxs("button",{onClick:()=>p(!m),className:"w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors",children:[n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(mu,{className:"w-4 h-4"}),t.plug_type==="mqtt"?a("smartPlugs.settings"):a("smartPlugs.automationSettings")]}),n.jsx("span",{children:m?"-":"+"})]}),m&&n.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(DS,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.showInSwitchbar")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.quickAccessSidebar")})]})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.show_in_switchbar,onChange:M=>S.mutate({show_in_switchbar:M.target.checked}),className:"sr-only peer"}),n.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"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.enabled")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.enableAutomation")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.enabled,onChange:M=>S.mutate({enabled:M.target.checked}),className:"sr-only peer"}),n.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"})]})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOn")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOnDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_on,onChange:M=>S.mutate({auto_on:M.target.checked}),className:"sr-only peer"}),n.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"})]})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOff")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOffDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_off,onChange:M=>S.mutate({auto_off:M.target.checked}),className:"sr-only peer"}),n.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&&n.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-bambu-dark-tertiary",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOffPersistent")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOffPersistentDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_off_persistent,onChange:M=>S.mutate({auto_off_persistent:M.target.checked}),className:"sr-only peer"}),n.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&&n.jsxs("div",{className:"space-y-3 pl-4 border-l-2 border-bambu-dark-tertiary",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white mb-2",children:a("smartPlugs.turnOffDelayMode")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"time"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="time"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[n.jsx(Za,{className:"w-4 h-4"}),a("smartPlugs.time")]}),n.jsxs("button",{onClick:()=>S.mutate({off_delay_mode:"temperature"}),className:`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg text-sm transition-colors ${t.off_delay_mode==="temperature"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white"}`,children:[n.jsx(zS,{className:"w-4 h-4"}),a("smartPlugs.temp")]})]})]}),t.off_delay_mode==="time"?n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("smartPlugs.delayMinutes")}),n.jsx("input",{type:"number",min:"1",max:"60",value:t.off_delay_minutes,onChange:M=>S.mutate({off_delay_minutes:parseInt(M.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"})]}):n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("smartPlugs.tempThreshold")}),n.jsx("input",{type:"number",min:"30",max:"100",value:t.off_temp_threshold,onChange:M=>S.mutate({off_temp_threshold:parseInt(M.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"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("smartPlugs.tempThresholdDescription")})]})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("smartPlugs.autoOffAfterDrying")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.autoOffAfterDryingDescription")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.auto_off_after_drying,onChange:M=>S.mutate({auto_off_after_drying:M.target.checked}),className:"sr-only peer"}),n.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_after_drying&&n.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary",children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("smartPlugs.delayAfterDryingMinutes")}),n.jsx("input",{type:"number",min:"0",max:"120",value:t.off_delay_after_drying_minutes,onChange:M=>S.mutate({off_delay_after_drying_minutes:parseInt(M.target.value)||10}),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"})]})]}),n.jsxs("div",{className:"flex gap-2 pt-2",children:[n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[n.jsx(fc,{className:"w-4 h-4"}),a("smartPlugs.edit")]}),n.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>o(!0),className:"text-red-400 hover:text-red-300",children:n.jsx(ea,{className:"w-4 h-4"})})]})]})]})}),s&&n.jsx(ya,{title:a("smartPlugs.deleteSmartPlug"),message:a("smartPlugs.deleteConfirm",{name:t.name}),confirmText:a("smartPlugs.delete"),variant:"danger",onConfirm:()=>{N.mutate(),o(!1)},onCancel:()=>o(!1)}),l&&n.jsx(ya,{title:a("smartPlugs.turnOnSmartPlug"),message:a("smartPlugs.turnOnConfirm",{name:t.name}),confirmText:a("smartPlugs.turnOn"),variant:"default",onConfirm:()=>{x.mutate("on"),c(!1)},onCancel:()=>c(!1)}),d&&n.jsx(ya,{title:a("smartPlugs.turnOffSmartPlug"),message:a("smartPlugs.turnOffConfirm",{name:t.name}),confirmText:a("smartPlugs.turnOff"),variant:"danger",onConfirm:()=>{x.mutate("off"),u(!1)},onCancel:()=>u(!1)})]})}function Art({plug:t,onClose:e}){const{t:a}=vt(),r=ta(),i=!!t,[s,o]=y.useState(t?.plug_type||"tasmota"),[l,c]=y.useState(t?.name||""),[d,u]=y.useState(t?.ip_address||""),[m,p]=y.useState(t?.username||""),[f,g]=y.useState(t?.password||""),[w,b]=y.useState(t?.ha_entity_id||""),[x,S]=y.useState(t?.mqtt_power_topic||t?.mqtt_topic||""),[N,C]=y.useState(t?.mqtt_power_path||""),[P,T]=y.useState((t?.mqtt_power_multiplier??t?.mqtt_multiplier??1).toString()),[j,F]=y.useState(t?.mqtt_energy_topic||""),[k,M]=y.useState(t?.mqtt_energy_path||""),[q,I]=y.useState((t?.mqtt_energy_multiplier??1).toString()),[B,R]=y.useState(t?.mqtt_state_topic||""),[X,ee]=y.useState(t?.mqtt_state_path||""),[Q,le]=y.useState(t?.mqtt_state_on_value||""),[de,ue]=y.useState(t?.rest_on_url||""),[Z,oe]=y.useState(t?.rest_on_body||""),[fe,me]=y.useState(t?.rest_off_url||""),[be,H]=y.useState(t?.rest_off_body||""),[J,A]=y.useState(t?.rest_method||"POST"),[E,z]=y.useState(t?.rest_headers||""),[W,O]=y.useState(t?.rest_status_url||""),[re,U]=y.useState(t?.rest_status_path||""),[V,K]=y.useState(t?.rest_status_on_value||""),[Y,ie]=y.useState(t?.rest_power_url||""),[se,pe]=y.useState(t?.rest_power_path||""),[ce,he]=y.useState((t?.rest_power_multiplier??1).toString()),[$,L]=y.useState(t?.rest_energy_url||""),[ae,ge]=y.useState(t?.rest_energy_path||""),[xe,Se]=y.useState((t?.rest_energy_multiplier??1).toString()),[Te,ve]=y.useState(t?.ha_power_entity||""),[we,ze]=y.useState(t?.ha_energy_today_entity||""),[De,Le]=y.useState(t?.ha_energy_total_entity||""),[Re,We]=y.useState(""),[Be,ot]=y.useState(""),[Ee,it]=y.useState(!1),Ne=y.useRef(null),[Ze,Ye]=y.useState(""),[Ae,Ie]=y.useState(!1),et=y.useRef(null),[Ke,Pe]=y.useState(""),[at,rt]=y.useState(!1),At=y.useRef(null),[Bt,gt]=y.useState(""),[Qt,Xt]=y.useState(!1),ia=y.useRef(null),[da,ut]=y.useState(t?.printer_id||null),[_t,Ct]=y.useState(null),[dt,Nt]=y.useState(null),[Oe,je]=y.useState(t?.power_alert_enabled||!1),[Ve,Je]=y.useState(t?.power_alert_high?.toString()||""),[Fe,bt]=y.useState(t?.power_alert_low?.toString()||""),[Ce,$e]=y.useState(t?.schedule_enabled||!1),[nt,st]=y.useState(t?.schedule_on_time||""),[tt,wt]=y.useState(t?.schedule_off_time||""),[kt,Ue]=y.useState(t?.show_in_switchbar||!1),[qe,Dt]=y.useState(t?.show_on_printer_card??!0),[It,Ft]=y.useState(!1),[Xe,Ge]=y.useState({scanned:0,total:0}),[Gt,ca]=y.useState([]),ma=y.useRef(null),{data:Jt}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),{data:pa}=Qe({queryKey:["smart-plugs"],queryFn:ne.getSmartPlugs}),{data:Pa}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),tn=!!(Pa?.ha_enabled&&Pa?.ha_url&&Pa?.ha_token);y.useEffect(()=>{const Ot=setTimeout(()=>{ot(Re)},300);return()=>clearTimeout(Ot)},[Re]),y.useEffect(()=>{const Ot=Ua=>{Ne.current&&!Ne.current.contains(Ua.target)&&it(!1),et.current&&!et.current.contains(Ua.target)&&Ie(!1),At.current&&!At.current.contains(Ua.target)&&rt(!1),ia.current&&!ia.current.contains(Ua.target)&&Xt(!1)};return document.addEventListener("mousedown",Ot),()=>document.removeEventListener("mousedown",Ot)},[]);const{data:In,isLoading:$a,error:Br}=Qe({queryKey:["ha-entities",Be],queryFn:()=>ne.getHAEntities(Be||void 0),enabled:s==="homeassistant"&&tn,retry:!1,staleTime:0}),{data:Ra}=Qe({queryKey:["ha-sensor-entities"],queryFn:ne.getHASensorEntities,enabled:s==="homeassistant"&&tn,retry:!1,staleTime:0});y.useEffect(()=>{const Ot=Ua=>{Ua.key==="Escape"&&e()};return window.addEventListener("keydown",Ot),()=>{window.removeEventListener("keydown",Ot),ma.current&&clearInterval(ma.current)}},[e]);const Vn=async()=>{Ft(!0),ca([]),Ge({scanned:0,total:0}),Nt(null);try{await ne.startTasmotaScan();const Ot=async()=>{try{const Ua=await ne.getTasmotaScanStatus();Ge({scanned:Ua.scanned,total:Ua.total});const ln=await ne.getDiscoveredTasmotaDevices();ca(ln),Ua.running||(Ft(!1),ma.current&&(clearInterval(ma.current),ma.current=null))}catch(Ua){console.error("Polling error:",Ua)}};await Ot(),ma.current=setInterval(Ot,500)}catch(Ot){Ft(!1);const Ua=Ot instanceof Error?Ot.message:typeof Ot=="string"?Ot:JSON.stringify(Ot);Nt(Ua||a("smartPlugs.failedToStartScan"))}},br=async()=>{try{await ne.stopTasmotaScan()}catch{}Ft(!1),ma.current&&(clearInterval(ma.current),ma.current=null)},xn=Ot=>{u(Ot.ip_address),c(Ot.name),Ct(null)},xr=lt({mutationFn:()=>ne.testSmartPlugConnection(d,m||null,f||null),onSuccess:Ot=>{Ct(Ot),Nt(null),!l&&Ot.device_name&&c(Ot.device_name)},onError:Ot=>{Ct(null),Nt(Ot.message)}}),ci=lt({mutationFn:Ot=>ne.createSmartPlug(Ot),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Ot=>{Nt(Ot.message)}}),ts=lt({mutationFn:Ot=>ne.updateSmartPlug(t.id,Ot),onSuccess:()=>{r.invalidateQueries({queryKey:["smart-plugs"]}),r.invalidateQueries({queryKey:["scriptPlugsByPrinter"]}),e()},onError:Ot=>{Nt(Ot.message)}}),Pu=Jt?.filter(Ot=>s==="tasmota"?!pa?.some(ln=>ln.printer_id===Ot.id&&ln.id!==t?.id&&ln.plug_type==="tasmota"):!0),Sd=Ot=>{if(Ot.preventDefault(),Nt(null),!l.trim()){Nt(a("smartPlugs.nameRequired"));return}if(s==="tasmota"&&!d.trim()){Nt("IP address is required for Tasmota plugs");return}if(s==="homeassistant"&&!w){Nt(a("smartPlugs.entityRequired"));return}if(s==="mqtt"){const ln=x.trim(),Ht=j.trim(),Lc=B.trim();if(!ln&&!Ht&&!Lc){Nt(a("smartPlugs.mqttTopicRequired"));return}}if(s==="rest"&&!de.trim()&&!fe.trim()){Nt(a("smartPlugs.restUrlRequired"));return}const Ua={name:l.trim(),plug_type:s,ip_address:s==="tasmota"?d.trim():null,ha_entity_id:s==="homeassistant"?w:null,ha_power_entity:s==="homeassistant"&&Te||null,ha_energy_today_entity:s==="homeassistant"&&we||null,ha_energy_total_entity:s==="homeassistant"&&De||null,mqtt_power_topic:s==="mqtt"&&x.trim()||null,mqtt_power_path:s==="mqtt"&&N.trim()||null,mqtt_power_multiplier:s==="mqtt"&&parseFloat(P)||1,mqtt_energy_topic:s==="mqtt"&&j.trim()||null,mqtt_energy_path:s==="mqtt"&&k.trim()||null,mqtt_energy_multiplier:s==="mqtt"&&parseFloat(q)||1,mqtt_state_topic:s==="mqtt"&&B.trim()||null,mqtt_state_path:s==="mqtt"&&X.trim()||null,mqtt_state_on_value:s==="mqtt"&&Q.trim()||null,rest_on_url:s==="rest"&&de.trim()||null,rest_on_body:s==="rest"&&Z.trim()||null,rest_off_url:s==="rest"&&fe.trim()||null,rest_off_body:s==="rest"&&be.trim()||null,rest_method:s==="rest"?J:null,rest_headers:s==="rest"&&E.trim()||null,rest_status_url:s==="rest"&&W.trim()||null,rest_status_path:s==="rest"&&re.trim()||null,rest_status_on_value:s==="rest"&&V.trim()||null,rest_power_url:s==="rest"&&Y.trim()||null,rest_power_path:s==="rest"&&se.trim()||null,rest_power_multiplier:s==="rest"&&parseFloat(ce)||1,rest_energy_url:s==="rest"&&$.trim()||null,rest_energy_path:s==="rest"&&ae.trim()||null,rest_energy_multiplier:s==="rest"&&parseFloat(xe)||1,username:s==="tasmota"&&m.trim()||null,password:s==="tasmota"&&f.trim()||null,printer_id:da,power_alert_enabled:Oe,power_alert_high:Ve?parseFloat(Ve):null,power_alert_low:Fe?parseFloat(Fe):null,schedule_enabled:Ce,schedule_on_time:nt||null,schedule_off_time:tt||null,show_in_switchbar:kt,show_on_printer_card:qe};i?ts.mutate(Ua):ci.mutate(Ua)},Il=ci.isPending||ts.isPending;return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:n.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:Ot=>Ot.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary flex-shrink-0",children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a(i?"smartPlugs.editTitle":"smartPlugs.addTitle")}),n.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:n.jsx($t,{className:"w-5 h-5"})})]}),n.jsxs("form",{onSubmit:Sd,className:"p-6 space-y-4 overflow-y-auto",children:[dt&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:dt}),!i&&n.jsxs("div",{className:"flex gap-2 mb-2",children:[n.jsxs("button",{type:"button",onClick:()=>{o("tasmota"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="tasmota"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(xc,{className:"w-4 h-4"}),"Tasmota"]}),n.jsxs("button",{type:"button",onClick:()=>{o("homeassistant"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="homeassistant"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(ES,{className:"w-4 h-4"}),"HA"]}),n.jsxs("button",{type:"button",onClick:()=>{o("mqtt"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="mqtt"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(FO,{className:"w-4 h-4"}),"MQTT"]}),n.jsxs("button",{type:"button",onClick:()=>{o("rest"),Ct(null),Nt(null)},className:`flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg font-medium transition-colors ${s==="rest"?"bg-bambu-green text-white":"bg-bambu-dark text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:[n.jsx(ro,{className:"w-4 h-4"}),"REST"]})]}),!i&&s==="tasmota"&&n.jsxs("div",{className:"space-y-3",children:[It?n.jsxs(Me,{type:"button",variant:"secondary",onClick:br,className:"w-full",children:[n.jsx($t,{className:"w-4 h-4"}),a("smartPlugs.stopScanning")]}):n.jsxs(Me,{type:"button",variant:"primary",onClick:Vn,className:"w-full",children:[n.jsx(gn,{className:"w-4 h-4"}),a("smartPlugs.discoverTasmota")]}),It&&Xe.total>0&&n.jsxs("div",{className:"space-y-1",children:[n.jsxs("div",{className:"flex justify-between text-xs text-bambu-gray",children:[n.jsx("span",{children:a("smartPlugs.addSmartPlug.scanningNetwork")}),n.jsxs("span",{children:[Xe.scanned," / ",Xe.total]})]}),n.jsx("div",{className:"w-full bg-bambu-dark-tertiary rounded-full h-2",children:n.jsx("div",{className:"bg-bambu-green h-2 rounded-full transition-all duration-300",style:{width:`${Xe.scanned/Xe.total*100}%`}})})]}),Gt.length>0&&n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.foundDevices",{count:Gt.length})}),n.jsx("div",{className:"max-h-40 overflow-y-auto space-y-1",children:Gt.map(Ot=>n.jsxs("button",{type:"button",onClick:()=>xn(Ot),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:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(xc,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:Ot.name}),n.jsx("p",{className:"text-xs text-bambu-gray",children:Ot.ip_address})]})]}),Ot.state&&n.jsxs("span",{className:`flex items-center gap-1 text-xs ${Ot.state==="ON"?"text-bambu-green":"text-bambu-gray"}`,children:[n.jsx(Su,{className:"w-3 h-3"}),Ot.state]})]},Ot.ip_address))})]}),!It&&Gt.length===0&&Xe.total>0&&n.jsx("p",{className:"text-xs text-bambu-gray text-center py-2",children:a("smartPlugs.noDevicesFound")})]}),s==="homeassistant"&&n.jsxs("div",{className:"space-y-3",children:[!tn&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[a("smartPlugs.haNotConfigured")," ",n.jsx("span",{className:"font-medium",children:a("smartPlugs.haSettingsPath")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1 opacity-50",children:a("smartPlugs.selectEntity")}),n.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:n.jsx("option",{children:a("smartPlugs.addSmartPlug.chooseEntity")})})]})]}),tn&&n.jsxs(n.Fragment,{children:[$a&&n.jsxs("div",{className:"flex items-center justify-center py-4 text-bambu-gray",children:[n.jsx(pt,{className:"w-5 h-5 animate-spin mr-2"}),a("smartPlugs.loadingEntities")]}),Br&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:a("smartPlugs.failedToLoadEntities",{error:Br.message})}),(()=>{const Ot=pa?.filter(Ht=>Ht.ha_entity_id&&Ht.id!==t?.id).map(Ht=>Ht.ha_entity_id)||[],Ua=(In||[]).filter(Ht=>!Ot.includes(Ht.entity_id)),ln=In?.find(Ht=>Ht.entity_id===w);return n.jsxs("div",{ref:Ne,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.selectEntity")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:Ee?Re:ln?`${ln.friendly_name} (${ln.entity_id})`:"",onChange:Ht=>{We(Ht.target.value),Ee||it(!0)},onFocus:()=>{it(!0),We("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchEntities"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),w&&!Ee&&n.jsx("button",{type:"button",onClick:()=>{b(""),We("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})}),$a&&n.jsx(pt,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray animate-spin"})]}),Ee&&n.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:[$a&&n.jsxs("div",{className:"px-3 py-2 text-sm text-bambu-gray flex items-center gap-2",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),a("smartPlugs.loading")]}),!$a&&Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:Be?a("smartPlugs.noEntitiesMatching",{search:Be}):a("smartPlugs.noEntitiesAvailable")}),!$a&&Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{b(Ht.entity_id),it(!1),We(""),l||c(Ht.friendly_name)},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary transition-colors ${Ht.entity_id===w?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray flex items-center justify-between",children:[n.jsx("span",{children:Ht.entity_id}),n.jsx("span",{className:Ht.state==="on"?"text-bambu-green":"",children:Ht.state})]})]},Ht.entity_id))]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:Be?a("smartPlugs.searchingEntities",{count:Ua.length}):a("smartPlugs.showingEntities",{count:Ua.length})})]})})(),w&&Ra&&Ra.length>0&&n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 mt-4 space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white font-medium mb-1",children:a("smartPlugs.energyMonitoringOptional")}),n.jsx("p",{className:"text-xs text-bambu-gray mb-3",children:a("smartPlugs.energyMonitoringHint")})]}),(()=>{const Ot=Ra.filter(Ht=>Ht.unit_of_measurement==="W"||Ht.unit_of_measurement==="kW"||Ht.unit_of_measurement==="mW"),Ua=Ze?Ot.filter(Ht=>Ht.entity_id.toLowerCase().includes(Ze.toLowerCase())||Ht.friendly_name.toLowerCase().includes(Ze.toLowerCase())):Ot,ln=Ra.find(Ht=>Ht.entity_id===Te);return n.jsxs("div",{ref:et,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.powerSensorW")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:Ae?Ze:ln?`${ln.friendly_name} (${ln.state} ${ln.unit_of_measurement})`:"",onChange:Ht=>{Ye(Ht.target.value),Ae||Ie(!0)},onFocus:()=>{Ie(!0),Ye("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchPowerSensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),Te&&!Ae&&n.jsx("button",{type:"button",onClick:()=>{ve(""),Ye("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Ae&&n.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:[n.jsx("button",{type:"button",onClick:()=>{ve(""),Ie(!1),Ye("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:a("smartPlugs.none")}),Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{ve(Ht.entity_id),Ie(!1),Ye("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ht.entity_id===Te?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ht.entity_id," • ",Ht.state," ",Ht.unit_of_measurement]})]},Ht.entity_id)),Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:a("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const Ot=Ra.filter(Ht=>Ht.unit_of_measurement==="kWh"||Ht.unit_of_measurement==="Wh"||Ht.unit_of_measurement==="MWh"),Ua=Ke?Ot.filter(Ht=>Ht.entity_id.toLowerCase().includes(Ke.toLowerCase())||Ht.friendly_name.toLowerCase().includes(Ke.toLowerCase())):Ot,ln=Ra.find(Ht=>Ht.entity_id===we);return n.jsxs("div",{ref:At,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.energyTodayKwh")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:at?Ke:ln?`${ln.friendly_name} (${ln.state} ${ln.unit_of_measurement})`:"",onChange:Ht=>{Pe(Ht.target.value),at||rt(!0)},onFocus:()=>{rt(!0),Pe("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),we&&!at&&n.jsx("button",{type:"button",onClick:()=>{ze(""),Pe("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),at&&n.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:[n.jsx("button",{type:"button",onClick:()=>{ze(""),rt(!1),Pe("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:a("smartPlugs.none")}),Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{ze(Ht.entity_id),rt(!1),Pe("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ht.entity_id===we?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ht.entity_id," • ",Ht.state," ",Ht.unit_of_measurement]})]},Ht.entity_id)),Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:a("smartPlugs.noMatchingSensors")})]})]})})(),(()=>{const Ot=Ra.filter(Ht=>Ht.unit_of_measurement==="kWh"||Ht.unit_of_measurement==="Wh"||Ht.unit_of_measurement==="MWh"),Ua=Bt?Ot.filter(Ht=>Ht.entity_id.toLowerCase().includes(Bt.toLowerCase())||Ht.friendly_name.toLowerCase().includes(Bt.toLowerCase())):Ot,ln=Ra.find(Ht=>Ht.entity_id===De);return n.jsxs("div",{ref:ia,className:"relative",children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.totalEnergyKwh")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"}),n.jsx("input",{type:"text",value:Qt?Bt:ln?`${ln.friendly_name} (${ln.state} ${ln.unit_of_measurement})`:"",onChange:Ht=>{gt(Ht.target.value),Qt||Xt(!0)},onFocus:()=>{Xt(!0),gt("")},placeholder:a("smartPlugs.addSmartPlug.placeholders.searchEnergySensors"),className:"w-full pl-9 pr-8 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"}),De&&!Qt&&n.jsx("button",{type:"button",onClick:()=>{Le(""),gt("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1 hover:bg-bambu-dark-tertiary rounded",children:n.jsx($t,{className:"w-4 h-4 text-bambu-gray hover:text-white"})})]}),Qt&&n.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:[n.jsx("button",{type:"button",onClick:()=>{Le(""),Xt(!1),gt("")},className:"w-full px-3 py-2 text-left text-sm text-bambu-gray hover:bg-bambu-dark-tertiary",children:a("smartPlugs.none")}),Ua.map(Ht=>n.jsxs("button",{type:"button",onClick:()=>{Le(Ht.entity_id),Xt(!1),gt("")},className:`w-full px-3 py-2 text-left text-sm hover:bg-bambu-dark-tertiary ${Ht.entity_id===De?"bg-bambu-green/20 text-bambu-green":"text-white"}`,children:[n.jsx("div",{className:"font-medium",children:Ht.friendly_name}),n.jsxs("div",{className:"text-xs text-bambu-gray",children:[Ht.entity_id," • ",Ht.state," ",Ht.unit_of_measurement]})]},Ht.entity_id)),Ua.length===0&&n.jsx("div",{className:"px-3 py-2 text-sm text-bambu-gray",children:a("smartPlugs.noMatchingSensors")})]})]})})()]})]})]}),s==="mqtt"&&n.jsxs("div",{className:"space-y-3",children:[!Pa?.mqtt_broker&&n.jsxs("div",{className:"p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-sm text-yellow-400",children:[a("smartPlugs.mqttNotConfigured")," ",n.jsx("span",{className:"font-medium",children:a("smartPlugs.mqttSettingsPath")})," ",a("smartPlugs.mqttNotConfiguredSuffix")]}),Pa?.mqtt_broker&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg text-sm text-blue-300",children:[n.jsx("p",{className:"font-medium mb-1",children:a("smartPlugs.monitorOnly")}),n.jsx("p",{className:"text-xs opacity-80",children:a("smartPlugs.mqttMonitorOnlyDescription")})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-white font-medium text-sm",children:a("smartPlugs.powerMonitoring")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.topic")}),n.jsx("input",{type:"text",value:x,onChange:Ot=>S(Ot.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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.jsonPath")}),n.jsx("input",{type:"text",value:N,onChange:Ot=>C(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.multiplier")}),n.jsx("input",{type:"text",value:P,onChange:Ot=>T(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:a("smartPlugs.mqttPowerHint")})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.energyMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.topic")}),n.jsx("input",{type:"text",value:j,onChange:Ot=>F(Ot.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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.jsonPath")}),n.jsx("input",{type:"text",value:k,onChange:Ot=>M(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.multiplier")}),n.jsx("input",{type:"text",value:q,onChange:Ot=>I(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:a("smartPlugs.mqttEnergyHint")})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.stateMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.topic")}),n.jsx("input",{type:"text",value:B,onChange:Ot=>R(Ot.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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.jsonPath")}),n.jsx("input",{type:"text",value:X,onChange:Ot=>ee(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.onValue")}),n.jsx("input",{type:"text",value:Q,onChange:Ot=>le(Ot.target.value),placeholder:a("smartPlugs.addSmartPlug.placeholders.mqttStateOnValue"),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",style:{whiteSpace:"pre-line"},children:a("smartPlugs.mqttStateHint")})]})]})]}),s==="rest"&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsx("p",{className:"text-white font-medium text-sm",children:a("smartPlugs.restControl")}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restMethod")}),n.jsxs("select",{value:J,onChange:Ot=>A(Ot.target.value),className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:"GET",children:"GET"}),n.jsx("option",{value:"POST",children:"POST"}),n.jsx("option",{value:"PUT",children:"PUT"}),n.jsx("option",{value:"PATCH",children:"PATCH"})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restOnUrl")}),n.jsx("input",{type:"text",value:de,onChange:Ot=>{ue(Ot.target.value),Ct(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",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"})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restOnBody")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:Z,onChange:Ot=>oe(Ot.target.value),placeholder:a("smartPlugs.restBodyHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restOffUrl")}),n.jsx("input",{type:"text",value:fe,onChange:Ot=>{me(Ot.target.value),Ct(null)},placeholder:"http://openhab:8080/rest/items/MyPlug",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"})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restOffBody")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:be,onChange:Ot=>H(Ot.target.value),placeholder:a("smartPlugs.restBodyHint"),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"})]})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.restHeaders")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("div",{children:n.jsx("textarea",{value:E,onChange:Ot=>z(Ot.target.value),placeholder:a("smartPlugs.restHeadersHint"),rows:2,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 font-mono text-sm"})})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.stateMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restStatusUrl")}),n.jsx("input",{type:"text",value:W,onChange:Ot=>O(Ot.target.value),placeholder:a("smartPlugs.restStatusHint"),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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restStatusPath")}),n.jsx("input",{type:"text",value:re,onChange:Ot=>U(Ot.target.value),placeholder:a("smartPlugs.restPathHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restStatusOnValue")}),n.jsx("input",{type:"text",value:V,onChange:Ot=>K(Ot.target.value),placeholder:"ON",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"})]})]})]}),n.jsxs("div",{className:"space-y-3 p-3 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsxs("p",{className:"text-white font-medium text-sm",children:[a("smartPlugs.energyMonitoring")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restPowerUrl")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:Y,onChange:Ot=>ie(Ot.target.value),placeholder:a("smartPlugs.restPowerUrlHint"),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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restPowerPath")}),n.jsx("input",{type:"text",value:se,onChange:Ot=>pe(Ot.target.value),placeholder:a("smartPlugs.restPathHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restPowerMultiplier")}),n.jsx("input",{type:"text",value:ce,onChange:Ot=>he(Ot.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"})]})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("smartPlugs.restEnergyUrl")," ",n.jsxs("span",{className:"text-bambu-gray font-normal",children:["(",a("smartPlugs.optional"),")"]})]}),n.jsx("input",{type:"text",value:$,onChange:Ot=>L(Ot.target.value),placeholder:a("smartPlugs.restEnergyUrlHint"),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"})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restEnergyPath")}),n.jsx("input",{type:"text",value:ae,onChange:Ot=>ge(Ot.target.value),placeholder:a("smartPlugs.restPathHint"),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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.restEnergyMultiplier")}),n.jsx("input",{type:"text",value:xe,onChange:Ot=>Se(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.restEnergyHint")})]}),(de.trim()||fe.trim())&&n.jsx("div",{className:"flex gap-2",children:n.jsxs(Me,{type:"button",variant:"secondary",onClick:async()=>{Ct(null);try{const Ot=de.trim()||fe.trim(),Ua=await ne.testRESTConnection(Ot,J,E.trim()||null);Ct({success:Ua.success}),Ua.success||Nt(Ua.error||a("smartPlugs.addSmartPlug.connectionFailed"))}catch{Ct({success:!1}),Nt(a("smartPlugs.addSmartPlug.connectionFailed"))}},className:"w-full",children:[n.jsx(Dh,{className:"w-4 h-4"}),a("smartPlugs.testConnection")]})}),_t&&n.jsxs("div",{className:`flex items-center gap-2 text-sm ${_t.success?"text-green-400":"text-red-400"}`,children:[_t.success?n.jsx(fn,{className:"w-4 h-4"}):n.jsx(pu,{className:"w-4 h-4"}),_t.success?a("smartPlugs.connectionSuccess"):a("smartPlugs.addSmartPlug.connectionFailed")]})]}),s==="tasmota"&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.ipAddress")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{type:"text",value:d,onChange:Ot=>{u(Ot.target.value),Ct(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"}),n.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>xr.mutate(),disabled:!d.trim()||xr.isPending,children:[xr.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Dh,{className:"w-4 h-4"}),a("smartPlugs.test")]})]})]}),s==="tasmota"&&_t&&n.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${_t.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:_t.success?n.jsxs(n.Fragment,{children:[n.jsx(fn,{className:"w-5 h-5"}),n.jsxs("div",{children:[n.jsx("p",{className:"font-medium",children:a("smartPlugs.connectedResult")}),n.jsxs("p",{className:"text-sm opacity-80",children:[_t.device_name&&a("smartPlugs.deviceLabel",{name:_t.device_name}),a("smartPlugs.stateLabel",{state:_t.state})]})]})]}):n.jsxs(n.Fragment,{children:[n.jsx(pu,{className:"w-5 h-5"}),n.jsx("span",{children:a("smartPlugs.addSmartPlug.connectionFailed")})]})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.nameLabel")}),n.jsx("input",{type:"text",value:l,onChange:Ot=>c(Ot.target.value),placeholder:a("smartPlugs.addSmartPlug.placeholders.plugName"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),s==="tasmota"&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.username")}),n.jsx("input",{type:"text",value:m,onChange:Ot=>p(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.password")}),n.jsx("input",{type:"password",value:f,onChange:Ot=>g(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray -mt-2",children:a("smartPlugs.authHint")})]}),s!=="mqtt"&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.linkToPrinter")}),n.jsxs("select",{value:da??"",onChange:Ot=>ut(Ot.target.value?Number(Ot.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:[n.jsx("option",{value:"",children:a("smartPlugs.noPrinter")}),Pu?.map(Ot=>n.jsx("option",{value:Ot.id,children:Ot.name},Ot.id))]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("smartPlugs.linkingDescription")})]}),n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Th,{className:"w-4 h-4 text-bambu-green"}),n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.powerAlerts")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:Oe,onChange:Ot=>je(Ot.target.checked),className:"sr-only peer"}),n.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"})]})]}),Oe&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.alertAbove")}),n.jsx("input",{type:"number",value:Ve,onChange:Ot=>Je(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.alertBelow")}),n.jsx("input",{type:"number",value:Fe,onChange:Ot=>bt(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.alertDescription")})]})]}),s!=="mqtt"&&n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Za,{className:"w-4 h-4 text-bambu-green"}),n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.dailySchedule")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:Ce,onChange:Ot=>$e(Ot.target.checked),className:"sr-only peer"}),n.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"})]})]}),Ce&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.turnOnAt")}),n.jsx("input",{type:"time",value:nt,onChange:Ot=>st(Ot.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("smartPlugs.turnOffAt")}),n.jsx("input",{type:"time",value:tt,onChange:Ot=>wt(Ot.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"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.scheduleDescription")})]})]}),n.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(DS,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.showInSwitchbar")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.quickAccessSidebar")})]})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:kt,onChange:Ot=>Ue(Ot.target.checked),className:"sr-only peer"}),n.jsx("div",{className:"w-11 h-6 bg-bambu-dark-tertiary peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-bambu-green"})]})]})}),s==="homeassistant"&&n.jsx("div",{className:"border-t border-bambu-dark-tertiary pt-4",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ml,{className:"w-4 h-4 text-bambu-green"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-white font-medium",children:a("smartPlugs.showOnPrinterCard")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("smartPlugs.displayOnPrinterCard")})]})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:qe,onChange:Ot=>Dt(Ot.target.checked),className:"sr-only peer"}),n.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"})]})]})}),n.jsxs("div",{className:"flex gap-3 pt-2",children:[n.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("smartPlugs.cancel")}),n.jsxs(Me,{type:"submit",disabled:Il,className:"flex-1",children:[Il?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(fs,{className:"w-4 h-4"}),a(i?"smartPlugs.save":"smartPlugs.add")]})]})]})]})})}function ja({checked:t,onChange:e,disabled:a}){const r=i=>{i.preventDefault(),i.stopPropagation(),a||e(!t)};return n.jsx("button",{type:"button",role:"switch","aria-checked":t,disabled:a,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 ${a?"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:n.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"}`})})}function jrt({provider:t,onEdit:e}){const{t:a}=vt(),r=ta(),[i,s]=y.useState(!1),[o,l]=y.useState(!1),[c,d]=y.useState(null),{data:u}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),m=u?.find(b=>b.id===t.printer_id),p=lt({mutationFn:b=>ne.updateNotificationProvider(t.id,b),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),f=lt({mutationFn:()=>ne.deleteNotificationProvider(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]})}}),g=lt({mutationFn:()=>ne.testNotificationProvider(t.id),onSuccess:b=>{d(b),r.invalidateQueries({queryKey:["notification-providers"]})},onError:b=>{d({success:!1,message:b.message})}}),w=b=>b||"";return n.jsxs(n.Fragment,{children:[n.jsx(Tt,{className:"relative",children:n.jsxs(Mt,{className:"p-3",children:[n.jsxs("div",{className:`flex items-start justify-between ${t.enabled?"mb-3":"mb-0"}`,children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:`p-2 rounded-lg ${t.enabled?"bg-bambu-green/20":"bg-bambu-dark"}`,children:n.jsx(Th,{className:`w-5 h-5 ${t.enabled?"text-bambu-green":"text-bambu-gray"}`})}),n.jsxs("div",{children:[n.jsx("h3",{className:"font-medium text-white",children:t.name}),n.jsx("p",{className:"text-sm text-bambu-gray",children:a(`notifications.providerTypes.${t.provider_type}`,t.provider_type)})]})]}),n.jsxs("div",{className:"flex items-center gap-3",children:[t.last_success&&n.jsx("span",{className:"text-xs text-status-ok hidden sm:inline",children:a("notifications.lastSuccess",{date:zg(t.last_success)})}),t.last_error&&t.last_error_at&&(!t.last_success||(Qa(t.last_error_at)?.getTime()||0)>(Qa(t.last_success)?.getTime()||0))&&n.jsx("span",{className:"text-xs text-status-error",title:t.last_error,children:a("notifications.error")}),n.jsx(ja,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]})]}),t.enabled&&n.jsxs(n.Fragment,{children:[m&&n.jsxs("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:[n.jsxs("span",{className:"text-xs text-bambu-gray",children:[a("notifications.printer")," "]}),n.jsx("span",{className:"text-sm text-white",children:m.name})]}),!m&&!t.printer_id&&n.jsx("div",{className:"mb-3 px-2 py-1.5 bg-bambu-dark rounded-lg",children:n.jsx("span",{className:"text-xs text-bambu-gray",children:a("notifications.allPrinters")})}),n.jsxs("div",{className:"mb-3 flex flex-wrap gap-1",children:[t.on_print_start&&n.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-400 text-xs rounded",children:a("notifications.start")}),t.on_plate_not_empty&&n.jsx("span",{className:"px-2 py-0.5 bg-rose-600/20 text-rose-300 text-xs rounded",children:a("notifications.plateCheck")}),t.on_print_complete&&n.jsx("span",{className:"px-2 py-0.5 bg-bambu-green/20 text-bambu-green text-xs rounded",children:a("notifications.complete")}),t.on_print_failed&&n.jsx("span",{className:"px-2 py-0.5 bg-red-500/20 text-red-400 text-xs rounded",children:a("notifications.failed")}),t.on_print_stopped&&n.jsx("span",{className:"px-2 py-0.5 bg-orange-500/20 text-orange-400 text-xs rounded",children:a("notifications.stopped")}),t.on_print_progress&&n.jsx("span",{className:"px-2 py-0.5 bg-yellow-500/20 text-yellow-400 text-xs rounded",children:a("notifications.progress")}),t.on_printer_offline&&n.jsx("span",{className:"px-2 py-0.5 bg-gray-500/20 text-gray-400 text-xs rounded",children:a("notifications.offline")}),t.on_printer_error&&n.jsx("span",{className:"px-2 py-0.5 bg-rose-500/20 text-rose-400 text-xs rounded",children:a("notifications.error")}),t.on_filament_low&&n.jsx("span",{className:"px-2 py-0.5 bg-cyan-500/20 text-cyan-400 text-xs rounded",children:a("notifications.lowFilament")}),t.on_maintenance_due&&n.jsx("span",{className:"px-2 py-0.5 bg-purple-500/20 text-purple-400 text-xs rounded",children:a("notifications.maintenance")}),t.on_ams_humidity_high&&n.jsx("span",{className:"px-2 py-0.5 bg-blue-600/20 text-blue-300 text-xs rounded",children:a("notifications.amsHumidity")}),t.on_ams_temperature_high&&n.jsx("span",{className:"px-2 py-0.5 bg-orange-600/20 text-orange-300 text-xs rounded",children:a("notifications.amsTemp")}),t.on_ams_ht_humidity_high&&n.jsx("span",{className:"px-2 py-0.5 bg-cyan-600/20 text-cyan-300 text-xs rounded",children:a("notifications.amsHtHumidity")}),t.on_ams_ht_temperature_high&&n.jsx("span",{className:"px-2 py-0.5 bg-amber-600/20 text-amber-300 text-xs rounded",children:a("notifications.amsHtTemp")}),t.on_bed_cooled&&n.jsx("span",{className:"px-2 py-0.5 bg-teal-500/20 text-teal-400 text-xs rounded",children:a("notifications.bedCooled")}),t.on_first_layer_complete&&n.jsx("span",{className:"px-2 py-0.5 bg-emerald-600/20 text-emerald-300 text-xs rounded",children:a("notifications.firstLayer")}),t.on_print_missing_spool_assignment&&n.jsx("span",{className:"px-2 py-0.5 bg-amber-500/20 text-amber-300 text-xs rounded",children:a("notifications.missingSpoolAssignmentLabel")}),t.on_stock_reorder_alert&&n.jsx("span",{className:"px-2 py-0.5 bg-lime-500/20 text-lime-400 text-xs rounded",children:a("notifications.stockReorderAlert")}),t.on_stock_break_alert&&n.jsx("span",{className:"px-2 py-0.5 bg-red-600/20 text-red-300 text-xs rounded",children:a("notifications.stockBreakAlert")}),t.quiet_hours_enabled&&n.jsxs("span",{className:"px-2 py-0.5 bg-indigo-500/20 text-indigo-400 text-xs rounded flex items-center gap-1",children:[n.jsx(cC,{className:"w-3 h-3"}),a("notifications.quiet")]}),t.daily_digest_enabled&&n.jsxs("span",{className:"px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-xs rounded flex items-center gap-1",children:[n.jsx(vr,{className:"w-3 h-3"}),a("notifications.digest",{time:t.daily_digest_time})]})]}),n.jsx("div",{className:"mb-3",children:n.jsxs(Me,{size:"sm",variant:"secondary",disabled:g.isPending,onClick:()=>{d(null),g.mutate()},className:"w-full",children:[g.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(OS,{className:"w-4 h-4"}),a("notifications.sendTestNotification")]})}),c&&n.jsxs("div",{className:`mb-3 p-2 rounded-lg flex items-center gap-2 text-sm ${c.success?"bg-bambu-green/20 text-bambu-green":"bg-red-500/20 text-red-400"}`,children:[c.success?n.jsx(fn,{className:"w-4 h-4"}):n.jsx(Mn,{className:"w-4 h-4"}),n.jsx("span",{children:c.message})]})]}),n.jsxs("button",{onClick:()=>l(!o),className:`w-full flex items-center justify-between py-2 text-sm text-bambu-gray hover:text-white transition-colors ${t.enabled?"border-t border-bambu-dark-tertiary":"mt-2 border-t border-bambu-dark-tertiary"}`,children:[n.jsxs("span",{className:"flex items-center gap-2",children:[n.jsx(mu,{className:"w-4 h-4"}),a("notifications.eventSettings")]}),o?n.jsx(al,{className:"w-4 h-4"}):n.jsx(Da,{className:"w-4 h-4"})]}),o&&n.jsxs("div",{className:"pt-3 border-t border-bambu-dark-tertiary space-y-4",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.enabled")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.sendFromProvider")})]}),n.jsx(ja,{checked:t.enabled,onChange:b=>p.mutate({enabled:b})})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.printEvents")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printStarted")}),n.jsx(ja,{checked:t.on_print_start,onChange:b=>p.mutate({on_print_start:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.plateNotEmpty")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.plateNotEmptyDescription")})]}),n.jsx(ja,{checked:t.on_plate_not_empty??!0,onChange:b=>p.mutate({on_plate_not_empty:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printCompleted")}),n.jsx(ja,{checked:t.on_print_complete,onChange:b=>p.mutate({on_print_complete:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.bedCooledLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.bedCooledDescription")})]}),n.jsx(ja,{checked:t.on_bed_cooled??!1,onChange:b=>p.mutate({on_bed_cooled:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.firstLayerCompleteLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.firstLayerCompleteDescription")})]}),n.jsx(ja,{checked:t.on_first_layer_complete??!1,onChange:b=>p.mutate({on_first_layer_complete:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.missingSpoolAssignmentLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.missingSpoolAssignmentDescription")})]}),n.jsx(ja,{checked:t.on_print_missing_spool_assignment??!1,onChange:b=>p.mutate({on_print_missing_spool_assignment:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printFailed")}),n.jsx(ja,{checked:t.on_print_failed,onChange:b=>p.mutate({on_print_failed:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printStopped")}),n.jsx(ja,{checked:t.on_print_stopped,onChange:b=>p.mutate({on_print_stopped:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.progressMilestones")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.progressMilestonesDescription")})]}),n.jsx(ja,{checked:t.on_print_progress,onChange:b=>p.mutate({on_print_progress:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.printerStatus")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printerOffline")}),n.jsx(ja,{checked:t.on_printer_offline,onChange:b=>p.mutate({on_printer_offline:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.printerError")}),n.jsx(ja,{checked:t.on_printer_error,onChange:b=>p.mutate({on_printer_error:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.lowFilamentLabel")}),n.jsx(ja,{checked:t.on_filament_low,onChange:b=>p.mutate({on_filament_low:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.maintenanceDue")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.maintenanceDueDescription")})]}),n.jsx(ja,{checked:t.on_maintenance_due??!1,onChange:b=>p.mutate({on_maintenance_due:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.amsAlarms")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsHumidityHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsHumidityHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_humidity_high??!1,onChange:b=>p.mutate({on_ams_humidity_high:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsTemperatureHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsTemperatureHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_temperature_high??!1,onChange:b=>p.mutate({on_ams_temperature_high:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.amsHtAlarms")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsHtHumidityHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsHtHumidityHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_ht_humidity_high??!1,onChange:b=>p.mutate({on_ams_ht_humidity_high:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.amsHtTemperatureHigh")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.amsHtTemperatureHighDescription")})]}),n.jsx(ja,{checked:t.on_ams_ht_temperature_high??!1,onChange:b=>p.mutate({on_ams_ht_temperature_high:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.inventoryAlerts")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.stockReorderAlert")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.stockReorderAlertDescription")})]}),n.jsx(ja,{checked:t.on_stock_reorder_alert??!1,onChange:b=>p.mutate({on_stock_reorder_alert:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.stockBreakAlert")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.stockBreakAlertDescription")})]}),n.jsx(ja,{checked:t.on_stock_break_alert??!1,onChange:b=>p.mutate({on_stock_break_alert:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide",children:a("notifications.printQueue")}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobAdded")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobAddedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_added??!1,onChange:b=>p.mutate({on_queue_job_added:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobAssigned")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobAssignedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_assigned??!1,onChange:b=>p.mutate({on_queue_job_assigned:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobStarted")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobStartedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_started??!1,onChange:b=>p.mutate({on_queue_job_started:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobWaiting")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobWaitingDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_waiting??!0,onChange:b=>p.mutate({on_queue_job_waiting:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobSkipped")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobSkippedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_skipped??!0,onChange:b=>p.mutate({on_queue_job_skipped:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.jobFailed")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.jobFailedDescription")})]}),n.jsx(ja,{checked:t.on_queue_job_failed??!0,onChange:b=>p.mutate({on_queue_job_failed:b})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:a("notifications.queueComplete")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.queueCompleteDescription")})]}),n.jsx(ja,{checked:t.on_queue_completed??!1,onChange:b=>p.mutate({on_queue_completed:b})})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(cC,{className:"w-4 h-4 text-purple-400"}),n.jsx("p",{className:"text-sm text-white",children:a("notifications.quietHours")})]}),n.jsx(ja,{checked:t.quiet_hours_enabled,onChange:b=>p.mutate({quiet_hours_enabled:b})})]}),t.quiet_hours_enabled&&n.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.noNotificationsDuring")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Za,{className:"w-4 h-4 text-bambu-gray"}),n.jsxs("span",{className:"text-sm text-white",children:[w(t.quiet_hours_start)||"22:00"," - ",w(t.quiet_hours_end)||"07:00"]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.editProviderToChangeQuietHours")})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(vr,{className:"w-4 h-4 text-emerald-400"}),n.jsx("p",{className:"text-sm text-white",children:a("notifications.dailyDigest")})]}),n.jsx(ja,{checked:t.daily_digest_enabled,onChange:b=>p.mutate({daily_digest_enabled:b})})]}),t.daily_digest_enabled&&n.jsxs("div",{className:"pl-4 border-l-2 border-bambu-dark-tertiary space-y-2",children:[n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.batchNotifications")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Za,{className:"w-4 h-4 text-bambu-gray"}),n.jsx("span",{className:"text-sm text-white",children:a("notifications.sendAt",{time:w(t.daily_digest_time)||"08:00"})})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.editProviderToChangeDigestTime")})]})]}),n.jsxs("div",{className:"flex gap-2 pt-2",children:[n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>e(t),className:"flex-1",children:[n.jsx(fc,{className:"w-4 h-4"}),a("notifications.edit")]}),n.jsx(Me,{size:"sm",variant:"secondary",onClick:()=>s(!0),className:"text-red-400 hover:text-red-300",children:n.jsx(ea,{className:"w-4 h-4"})})]})]})]})}),i&&n.jsx(ya,{title:a("notifications.deleteProvider"),message:a("notifications.deleteConfirm",{name:t.name}),confirmText:a("notifications.delete"),variant:"danger",onConfirm:()=>{f.mutate(),s(!1)},onCancel:()=>s(!1)})]})}const Mrt=["email","telegram","discord","ntfy","pushover","callmebot","webhook","homeassistant"];function Ert({provider:t,onClose:e}){const{t:a}=vt(),r=ta(),i=!!t,[s,o]=y.useState(t?.name||""),[l,c]=y.useState(t?.provider_type||"email"),[d,u]=y.useState(t?.printer_id||null),[m,p]=y.useState(t?.quiet_hours_enabled||!1),[f,g]=y.useState(t?.quiet_hours_start||"22:00"),[w,b]=y.useState(t?.quiet_hours_end||"07:00"),[x,S]=y.useState(t?.daily_digest_enabled||!1),[N,C]=y.useState(t?.daily_digest_time||"08:00"),[P,T]=y.useState(t?.on_print_start??!1),[j,F]=y.useState(t?.on_print_complete??!0),[k,M]=y.useState(t?.on_print_failed??!0),[q,I]=y.useState(t?.on_print_stopped??!0),[B,R]=y.useState(t?.on_print_progress??!1),[X,ee]=y.useState(t?.on_printer_offline??!1),[Q,le]=y.useState(t?.on_printer_error??!1),[de,ue]=y.useState(t?.on_filament_low??!1),[Z,oe]=y.useState(t?.on_maintenance_due??!1),[fe,me]=y.useState(t?.on_stock_reorder_alert??!1),[be,H]=y.useState(t?.on_stock_break_alert??!1),[J,A]=y.useState(t?.on_bed_cooled??!1),[E,z]=y.useState(t?.on_first_layer_complete??!1),[W,O]=y.useState(t?.config?Object.fromEntries(Object.entries(t.config).filter(([Te])=>Te!=="event_priorities").map(([Te,ve])=>[Te,String(ve)])):{}),re=(()=>{const Te=t?.config?.event_priorities;if(!Te||typeof Te!="object")return{};const ve={};for(const[we,ze]of Object.entries(Te)){const De=Number(ze);Number.isInteger(De)&&De>=1&&De<=5&&(ve[we]=De)}return ve})(),[U,V]=y.useState(re),[K,Y]=y.useState(null),[ie,se]=y.useState(null),{data:pe}=Qe({queryKey:["printers"],queryFn:ne.getPrinters});y.useEffect(()=>{const Te=ve=>{ve.key==="Escape"&&e()};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[e]);const ce=lt({mutationFn:()=>ne.testNotificationConfig({provider_type:l,config:W}),onSuccess:Te=>{Y(Te),se(null)},onError:Te=>{Y({success:!1,message:Te.message})}}),he=lt({mutationFn:Te=>ne.createNotificationProvider(Te),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:Te=>{se(Te.message)}}),$=lt({mutationFn:Te=>ne.updateNotificationProvider(t.id,Te),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-providers"]}),e()},onError:Te=>{se(Te.message)}}),L=Te=>{if(Te.preventDefault(),se(null),!s.trim()){se(a("notifications.nameRequired"));return}const ve=xe(l);for(const De of ve)if(!W[De.key]?.trim()){se(a("notifications.fieldRequired",{field:De.label}));return}const we=l==="ntfy"&&Object.keys(U).length>0?{...W,event_priorities:U}:W,ze={name:s.trim(),provider_type:l,config:we,printer_id:d,quiet_hours_enabled:m,quiet_hours_start:m?f:null,quiet_hours_end:m?w:null,daily_digest_enabled:x,daily_digest_time:x?N:null,on_print_start:P,on_print_complete:j,on_print_failed:k,on_print_stopped:q,on_print_progress:B,on_printer_offline:X,on_printer_error:Q,on_filament_low:de,on_maintenance_due:Z,on_stock_reorder_alert:fe,on_stock_break_alert:be,on_bed_cooled:J,on_first_layer_complete:E};i?$.mutate(ze):he.mutate(ze)},ae=he.isPending||$.isPending,ge=Te=>{switch(Te){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:ve=>ve.payload_format!=="slack"},{key:"field_message",label:"Message Field Name",placeholder:"message",type:"text",required:!1,showIf:ve=>ve.payload_format!=="slack"}];case"homeassistant":return[{key:"service",label:"Home Assistant Service",placeholder:"notify.mobile_app_myphone",type:"text",required:!1}];default:return[]}},xe=Te=>ge(Te).filter(ve=>ve.required),Se=ge(l);return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4 overflow-y-auto",onClick:e,children:n.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:Te=>Te.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a(i?"notifications.editTitle":"notifications.addTitle")}),n.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:n.jsx($t,{className:"w-5 h-5"})})]}),n.jsxs("form",{onSubmit:L,className:"p-6 space-y-4",children:[ie&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:ie}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("notifications.nameLabel")}),n.jsx("input",{type:"text",value:s,onChange:Te=>o(Te.target.value),placeholder:a("notifications.namePlaceholder"),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("notifications.providerTypeLabel")}),n.jsx("select",{value:l,onChange:Te=>{c(Te.target.value),O({}),Y(null)},disabled:i,className:"w-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:Mrt.map(Te=>n.jsx("option",{value:Te,children:a(`notifications.providerTypes.${Te}`,Te)},Te))}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a(`notifications.providerDescriptions.${l}`,"")})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:a("notifications.configuration")}),Se.filter(Te=>!("showIf"in Te)||Te.showIf?.(W)!==!1).map(Te=>n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[Te.label," ",Te.required&&"*"]}),Te.type==="select"&&"options"in Te&&Te.options?n.jsx("select",{value:W[Te.key]||Te.options[0]?.value||"",onChange:ve=>{O({...W,[Te.key]:ve.target.value}),Y(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:Te.options.map(ve=>n.jsx("option",{value:ve.value,children:ve.label},ve.value))}):n.jsx("input",{type:Te.type,value:W[Te.key]||"",onChange:ve=>{O({...W,[Te.key]:ve.target.value}),Y(null)},placeholder:Te.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"})]},Te.key))]}),n.jsx("div",{className:"flex gap-2",children:n.jsxs(Me,{type:"button",variant:"secondary",onClick:()=>{Y(null),ce.mutate()},disabled:ce.isPending||xe(l).length>0&&!W[xe(l)[0]?.key],className:"flex-1",children:[ce.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(OS,{className:"w-4 h-4"}),a("notifications.testConfiguration")]})}),K&&n.jsx("div",{className:`p-3 rounded-lg flex items-center gap-2 ${K.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:K.success?n.jsxs(n.Fragment,{children:[n.jsx(fn,{className:"w-5 h-5"}),n.jsx("span",{children:K.message})]}):n.jsxs(n.Fragment,{children:[n.jsx(Mn,{className:"w-5 h-5"}),n.jsx("span",{children:K.message})]})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("notifications.printerFilter")}),n.jsxs("select",{value:d??"",onChange:Te=>u(Te.target.value?Number(Te.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:[n.jsx("option",{value:"",children:a("notifications.allPrinters")}),pe?.map(Te=>n.jsx("option",{value:Te.id,children:Te.name},Te.id))]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("notifications.onlyFromPrinter")})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-sm text-white",children:a("notifications.quietHoursDnd")}),n.jsx(ja,{checked:m,onChange:p})]}),m&&n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("notifications.quietStart")}),n.jsx("input",{type:"time",value:f,onChange:Te=>g(Te.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"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("notifications.quietEnd")}),n.jsx("input",{type:"time",value:w,onChange:Te=>b(Te.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"})]})]})]}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("label",{className:"text-sm text-white",children:a("notifications.dailyDigestLabel")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("notifications.batchNotifications")})]}),n.jsx(ja,{checked:x,onChange:S})]}),x&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-xs text-bambu-gray mb-1",children:a("notifications.sendDigestAt")}),n.jsx("input",{type:"time",value:N,onChange:Te=>C(Te.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"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("notifications.digestCollected")})]})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:a("notifications.notificationEvents")}),n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:a("notifications.printEvents")}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.start")}),n.jsx(ja,{checked:P,onChange:T})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.complete")}),n.jsx(ja,{checked:j,onChange:F})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.failed")}),n.jsx(ja,{checked:k,onChange:M})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.stopped")}),n.jsx(ja,{checked:q,onChange:I})]}),n.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.progress")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.progressPercent")})]}),n.jsx(ja,{checked:B,onChange:R})]}),n.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.bedCooled")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.bedCooledAfterPrint")})]}),n.jsx(ja,{checked:J,onChange:A})]}),n.jsxs("div",{className:"flex items-center justify-between col-span-2",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.firstLayerCompleteLabel")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.firstLayerCompleteDescription")})]}),n.jsx(ja,{checked:E,onChange:z})]})]})]}),n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:a("notifications.printerStatus")}),n.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.offline")}),n.jsx(ja,{checked:X,onChange:ee})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.error")}),n.jsx(ja,{checked:Q,onChange:le})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.lowFilament")}),n.jsx(ja,{checked:de,onChange:ue})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.maintenance")}),n.jsx(ja,{checked:Z,onChange:oe})]})]})]}),n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-2",children:a("notifications.inventoryAlerts")}),n.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.stockReorderAlert")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.stockReorderAlertDescription")})]}),n.jsx(ja,{checked:fe,onChange:me})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("notifications.stockBreakAlert")}),n.jsx("span",{className:"text-xs text-bambu-gray ml-1",children:a("notifications.stockBreakAlertDescription")})]}),n.jsx(ja,{checked:be,onChange:H})]})]})]}),l==="ntfy"&&(()=>{const Te=[];return P&&Te.push({key:"on_print_start",label:a("notifications.start")}),j&&Te.push({key:"on_print_complete",label:a("notifications.complete")}),k&&Te.push({key:"on_print_failed",label:a("notifications.failed")}),q&&Te.push({key:"on_print_stopped",label:a("notifications.stopped")}),B&&Te.push({key:"on_print_progress",label:a("notifications.progress")}),J&&Te.push({key:"on_bed_cooled",label:a("notifications.bedCooled")}),E&&Te.push({key:"on_first_layer_complete",label:a("notifications.firstLayerCompleteLabel")}),X&&Te.push({key:"on_printer_offline",label:a("notifications.offline")}),Q&&Te.push({key:"on_printer_error",label:a("notifications.error")}),de&&Te.push({key:"on_filament_low",label:a("notifications.lowFilament")}),Z&&Te.push({key:"on_maintenance_due",label:a("notifications.maintenance")}),fe&&Te.push({key:"on_stock_reorder_alert",label:a("notifications.stockReorderAlert")}),be&&Te.push({key:"on_stock_break_alert",label:a("notifications.stockBreakAlert")}),Te.length===0?null:n.jsxs("div",{className:"space-y-2 p-3 bg-bambu-dark rounded-lg",children:[n.jsx("p",{className:"text-xs text-bambu-gray uppercase tracking-wide mb-1",children:a("notifications.eventPriority.sectionTitle")}),n.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:a("notifications.eventPriority.helpNtfy")}),n.jsx("div",{className:"space-y-2",children:Te.map(ve=>n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("span",{className:"text-sm text-white",children:ve.label}),n.jsxs("select",{value:U[ve.key]??3,onChange:we=>{const ze=Number(we.target.value);V(De=>({...De,[ve.key]:ze}))},className:"px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-sm text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:1,children:a("notifications.eventPriority.min")}),n.jsx("option",{value:2,children:a("notifications.eventPriority.low")}),n.jsx("option",{value:3,children:a("notifications.eventPriority.default")}),n.jsx("option",{value:4,children:a("notifications.eventPriority.high")}),n.jsx("option",{value:5,children:a("notifications.eventPriority.urgent")})]})]},ve.key))})]})})()]}),n.jsxs("div",{className:"flex gap-3 pt-2",children:[n.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:a("notifications.cancel")}),n.jsxs(Me,{type:"submit",disabled:ae,className:"flex-1",children:[ae?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(fs,{className:"w-4 h-4"}),a(i?"notifications.save":"notifications.add")]})]})]})]})})}function Drt({template:t,onClose:e}){const{t:a}=vt(),r=ta(),i=y.useRef(null),[s,o]=y.useState(t.title_template),[l,c]=y.useState(t.body_template),[d,u]=y.useState(null),[m,p]=y.useState(!0),{data:f}=Qe({queryKey:["template-variables"],queryFn:ne.getTemplateVariables}),g=f?.find(T=>T.event_type===t.event_type),{data:w,isLoading:b}=Qe({queryKey:["template-preview",t.event_type,s,l],queryFn:()=>ne.previewTemplate({event_type:t.event_type,title_template:s,body_template:l}),enabled:m&&s.length>0&&l.length>0});y.useEffect(()=>{const T=j=>{j.key==="Escape"&&e()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[e]);const x=lt({mutationFn:T=>ne.updateNotificationTemplate(t.id,T),onSuccess:()=>{r.invalidateQueries({queryKey:["notification-templates"]}),e()},onError:T=>{u(T.message)}}),S=lt({mutationFn:()=>ne.resetNotificationTemplate(t.id),onSuccess:T=>{o(T.title_template),c(T.body_template),r.invalidateQueries({queryKey:["notification-templates"]})},onError:T=>{u(T.message)}}),N=T=>{if(T.preventDefault(),u(null),!s.trim()){u(a("notifications.titleRequired"));return}if(!l.trim()){u(a("notifications.bodyRequired"));return}x.mutate({title_template:s,body_template:l})},C=T=>{const j=i.current;if(!j)return;const F=j.selectionStart,k=j.selectionEnd,M=l,q=M.substring(0,F),I=M.substring(k),B=q+`{${T}}`+I;c(B),setTimeout(()=>{j.focus();const R=F+T.length+2;j.setSelectionRange(R,R)},0)},P=s!==t.title_template||l!==t.body_template;return n.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-50 p-4",children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col",children:[n.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0",children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("notifications.editTemplate",{name:t.name})}),n.jsx("button",{onClick:e,className:"p-1 hover:bg-bambu-dark-tertiary rounded transition-colors",children:n.jsx($t,{className:"w-5 h-5 text-bambu-gray"})})]}),n.jsxs("form",{onSubmit:N,className:"flex-1 overflow-y-auto p-4 space-y-4",children:[d&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded text-red-400 text-sm",children:d}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("notifications.titleLabel")}),n.jsx("input",{type:"text",value:s,onChange:T=>o(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:a("notifications.titlePlaceholder")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:a("notifications.bodyLabel")}),n.jsx("textarea",{ref:i,value:l,onChange:T=>c(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:a("notifications.bodyPlaceholder")})]}),g&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-2",children:a("notifications.availableVariables")}),n.jsx("div",{className:"flex flex-wrap gap-2",children:g.variables.map(T=>n.jsxs("button",{type:"button",onClick:()=>C(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:[n.jsx(en,{className:"w-3 h-3"}),T]},T))}),n.jsx("p",{className:"text-xs text-bambu-gray/60 mt-1",children:a("notifications.clickToInsert")})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsxs("label",{className:"text-sm font-medium text-bambu-gray flex items-center gap-2",children:[n.jsx(Ml,{className:"w-4 h-4"}),a("notifications.livePreview")]}),n.jsx("button",{type:"button",onClick:()=>p(!m),className:"text-xs text-bambu-green hover:text-bambu-green-light",children:a(m?"notifications.hide":"notifications.show")})]}),m&&n.jsx("div",{className:"bg-bambu-dark border border-bambu-dark-tertiary rounded p-3 space-y-2",children:b?n.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),a("notifications.loadingPreview")]}):w?n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[n.jsx("span",{className:"text-xs text-bambu-gray",children:a("notifications.titlePreview")}),n.jsx("div",{className:"text-white font-medium",children:w.title})]}),n.jsxs("div",{children:[n.jsx("span",{className:"text-xs text-bambu-gray",children:a("notifications.bodyPreview")}),n.jsx("div",{className:"text-white whitespace-pre-wrap text-sm",children:w.body})]})]}):n.jsx("div",{className:"text-bambu-gray text-sm",children:a("notifications.enterTemplateContent")})})]})]}),n.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-bambu-dark-tertiary shrink-0",children:[n.jsxs(Me,{type:"button",variant:"ghost",onClick:()=>S.mutate(),disabled:S.isPending,className:"text-orange-400 hover:text-orange-300",children:[S.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):n.jsx(vs,{className:"w-4 h-4 mr-2"}),a("notifications.resetToDefault")]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Me,{type:"button",variant:"secondary",onClick:e,children:a("notifications.cancel")}),n.jsxs(Me,{onClick:N,disabled:x.isPending||!P,children:[x.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}):n.jsx(fs,{className:"w-4 h-4 mr-2"}),a("notifications.save")]})]})]})]})})}const Frt={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 Lrt({onClose:t}){const{t:e}=vt(),a=ta(),{showToast:r}=ra(),[i,s]=y.useState(7),[o,l]=y.useState(null),[c,d]=y.useState(!1),{data:u}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),m=u?.time_format||"system",{data:p,isLoading:f,refetch:g,isRefetching:w}=Qe({queryKey:["notification-logs",i,c],queryFn:()=>ne.getNotificationLogs({days:i,limit:100,success:c?!1:void 0})}),{data:b}=Qe({queryKey:["notification-log-stats",i],queryFn:()=>ne.getNotificationLogStats(i)}),x=lt({mutationFn:()=>ne.clearNotificationLogs(30),onSuccess:N=>{r(N.message,"success"),a.invalidateQueries({queryKey:["notification-logs"]}),a.invalidateQueries({queryKey:["notification-log-stats"]})},onError:N=>{r(`Failed to clear logs: ${N.message}`,"error")}}),S=N=>{const C=Qa(N);if(!C)return"";const T=new Date().getTime()-C.getTime();return T<6e4?e("notifications.justNow"):T<36e5?`${Math.floor(T/6e4)}m ago`:T<864e5?`${Math.floor(T/36e5)}h ago`:C.toLocaleDateString()+" "+xJ(C,m)};return n.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:n.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:[n.jsxs("div",{className:"p-4 border-b border-bambu-dark-tertiary flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx(Wh,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:e("notifications.notificationLog")})]}),n.jsx("button",{onClick:t,className:"text-bambu-gray hover:text-white transition-colors",children:"×"})]}),b&&n.jsx("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary bg-bambu-dark/50",children:n.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[n.jsxs("span",{className:"text-bambu-gray",children:[e("notifications.statsSummary",{days:i})," ",n.jsx("span",{className:"text-white font-medium",children:b.total})," ",e("notifications.statsNotifications")]}),n.jsxs("span",{className:"flex items-center gap-1 text-bambu-green",children:[n.jsx(fn,{className:"w-4 h-4"}),e("notifications.statsSent",{count:b.success_count})]}),b.failure_count>0&&n.jsxs("span",{className:"flex items-center gap-1 text-red-400",children:[n.jsx(Mn,{className:"w-4 h-4"}),e("notifications.statsFailed",{count:b.failure_count})]})]})}),n.jsxs("div",{className:"px-4 py-3 border-b border-bambu-dark-tertiary flex items-center gap-4",children:[n.jsxs("select",{value:i,onChange:N=>s(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:[n.jsx("option",{value:1,children:e("notifications.last24Hours")}),n.jsx("option",{value:7,children:e("notifications.last7Days")}),n.jsx("option",{value:30,children:e("notifications.last30Days")}),n.jsx("option",{value:90,children:e("notifications.last90Days")})]}),n.jsxs("label",{className:"flex items-center gap-2 text-sm text-bambu-gray cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:c,onChange:N=>d(N.target.checked),className:"rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),e("notifications.showFailedOnly")]}),n.jsx("div",{className:"flex-1"}),n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>g(),disabled:w,children:[w?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),e("notifications.refresh")]}),n.jsxs(Me,{size:"sm",variant:"secondary",onClick:()=>x.mutate(),disabled:x.isPending,className:"text-red-400 hover:text-red-300",children:[x.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(ea,{className:"w-4 h-4"}),e("notifications.clearOld")]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:f?n.jsx("div",{className:"flex justify-center py-12",children:n.jsx(pt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):p&&p.length>0?n.jsx("div",{className:"space-y-2",children:p.map(N=>n.jsx(Rrt,{log:N,isExpanded:o===N.id,onToggle:()=>l(o===N.id?null:N.id),formatDate:S,formatFullDate:C=>Ug(C,m)},N.id))}):n.jsxs("div",{className:"text-center py-12 text-bambu-gray",children:[n.jsx(Wh,{className:"w-12 h-12 mx-auto mb-3 opacity-30"}),n.jsx("p",{className:"text-sm",children:e(c?"notifications.noFailedNotifications":"notifications.noNotificationsLogged")})]})})]})})}function Rrt({log:t,isExpanded:e,onToggle:a,formatDate:r,formatFullDate:i}){const{t:s}=vt();return n.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:[n.jsxs("button",{className:"w-full px-3 py-2 flex items-center gap-3 text-left hover:bg-bambu-dark/50 transition-colors",onClick:a,children:[t.success?n.jsx(fn,{className:"w-4 h-4 text-bambu-green shrink-0"}):n.jsx(Mn,{className:"w-4 h-4 text-red-400 shrink-0"}),n.jsx("span",{className:`text-xs font-medium ${Frt[t.event_type]||"text-bambu-gray"}`,children:s(`notifications.eventTypes.${t.event_type}`,t.event_type)}),n.jsx("span",{className:"text-sm text-white truncate flex-1",children:t.provider_name||s("notifications.unknownProvider")}),t.printer_name&&n.jsx("span",{className:"text-xs text-bambu-gray",children:t.printer_name}),n.jsx("span",{className:"text-xs text-bambu-gray shrink-0",children:r(t.created_at)}),e?n.jsx(al,{className:"w-4 h-4 text-bambu-gray shrink-0"}):n.jsx(Da,{className:"w-4 h-4 text-bambu-gray shrink-0"})]}),e&&n.jsxs("div",{className:"px-3 py-2 border-t border-bambu-dark-tertiary bg-bambu-dark/20 space-y-2",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logTitle")}),n.jsx("p",{className:"text-sm text-white",children:t.title})]}),n.jsxs("div",{children:[n.jsx("p",{className:"text-xs text-bambu-gray mb-1",children:s("notifications.logMessage")}),n.jsx("p",{className:"text-sm text-white whitespace-pre-wrap",children:t.message})]}),!t.success&&t.error_message&&n.jsxs("div",{children:[n.jsx("p",{className:"text-xs text-red-400 mb-1",children:s("notifications.logError")}),n.jsx("p",{className:"text-sm text-red-300",children:t.error_message})]}),n.jsxs("div",{className:"flex gap-4 text-xs text-bambu-gray pt-1",children:[n.jsx("span",{children:s("notifications.logProvider",{type:t.provider_type})}),n.jsx("span",{children:s("notifications.logTime",{time:i(t.created_at)})})]})]})]})}const Irt=300,I0=2;function Jce({onSuccess:t}){const{t:e}=vt(),a=ta(),[r,i]=y.useState(""),[s,o]=y.useState(""),[l,c]=y.useState(null),[d,u]=y.useState(null);y.useEffect(()=>{const N=r.trim();if(N.lengtho(N),Irt);return()=>clearTimeout(C)},[r]),y.useEffect(()=>{c(null),u(null)},[s]);const m=Qe({queryKey:["ldap-search",s],queryFn:()=>ne.searchLDAPDirectory(s),enabled:s.length>=I0,staleTime:3e4}),p=lt({mutationFn:N=>ne.provisionLDAPUser(N),onSuccess:N=>{a.invalidateQueries({queryKey:["users"]}),t(N)},onError:N=>{u(N.message||e("users.modal.ldapErrorProvision"))}}),f=y.useMemo(()=>m.data?.find(N=>N.dn===l)??null,[m.data,l]),g=r.trim().length>0&&r.trim().length=I0,b=!!m.data&&m.data.length>0,x=!w&&!!m.data&&m.data.length===0&&s.length>=I0,S=()=>{!f||f.already_provisioned||(u(null),p.mutate(f.username))};return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:e("users.modal.ldapSearchLabel")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"w-4 h-4 text-bambu-gray absolute left-3 top-1/2 -translate-y-1/2"}),n.jsx("input",{type:"text",value:r,onChange:N=>i(N.target.value),className:"w-full pl-9 pr-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:e("users.modal.ldapSearchPlaceholder"),autoComplete:"off"})]}),g&&n.jsx("p",{className:"mt-1 text-xs text-bambu-gray",children:e("users.modal.ldapMinChars")})]}),n.jsxs("div",{className:"min-h-[8rem] max-h-64 overflow-y-auto bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[w&&n.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin mr-2"}),n.jsx("span",{children:e("users.modal.ldapSearching")})]}),x&&n.jsx("div",{className:"flex items-center justify-center py-8 text-bambu-gray text-sm",children:e("users.modal.ldapNoResults")}),m.isError&&n.jsx("div",{className:"px-3 py-4 text-sm text-red-400",children:m.error instanceof Error?m.error.message:e("users.modal.ldapSearchError")}),!w&&b&&n.jsx("ul",{className:"divide-y divide-bambu-dark-tertiary",children:m.data.map(N=>n.jsx(Ort,{result:N,selected:l===N.dn,onSelect:()=>c(N.dn)},N.dn))}),!w&&!m.data&&!m.isError&&n.jsx("div",{className:"flex items-center justify-center py-8 text-bambu-gray text-sm",children:e("users.modal.ldapTypeToSearch")})]}),f&&n.jsxs("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3 space-y-1",children:[n.jsxs("p",{className:"text-sm text-white",children:[n.jsxs("span",{className:"text-bambu-gray",children:[e("users.modal.ldapSelectedLabel"),": "]}),n.jsx("span",{className:"font-medium",children:f.username}),f.display_name&&n.jsxs("span",{className:"text-bambu-gray",children:[" — ",f.display_name]})]}),f.email&&n.jsx("p",{className:"text-xs text-bambu-gray",children:f.email}),n.jsx("p",{className:"text-xs text-bambu-gray break-all",children:f.dn})]}),d&&n.jsx("div",{className:"bg-red-500/10 border border-red-500/30 rounded-lg p-3",children:n.jsx("p",{className:"text-sm text-red-400",children:d})}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Me,{onClick:S,disabled:!f||f.already_provisioned||p.isPending,children:p.isPending?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),e("users.modal.ldapProvisioning")]}):n.jsxs(n.Fragment,{children:[n.jsx(en,{className:"w-4 h-4"}),e("users.modal.ldapProvision")]})})})]})}function Ort({result:t,selected:e,onSelect:a}){const{t:r}=vt(),i=t.already_provisioned;return n.jsx("li",{children:n.jsxs("button",{type:"button",onClick:a,disabled:i,className:`w-full text-left px-3 py-2 flex items-center gap-3 transition-colors ${i?"opacity-50 cursor-not-allowed":e?"bg-bambu-green/10":"hover:bg-bambu-dark-tertiary"}`,children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("p",{className:"text-sm text-white truncate",children:[n.jsx("span",{className:"font-medium",children:t.username}),t.display_name&&n.jsxs("span",{className:"text-bambu-gray",children:[" — ",t.display_name]})]}),t.email&&n.jsx("p",{className:"text-xs text-bambu-gray truncate",children:t.email})]}),i&&n.jsxs("span",{className:"flex items-center gap-1 text-xs text-bambu-gray whitespace-nowrap",children:[n.jsx(no,{className:"w-3.5 h-3.5"}),r("users.modal.ldapAlreadyProvisioned")]})]})})}function zrt({formData:t,setFormData:e,groups:a,onClose:r,onCreate:i,isCreating:s,isCreateButtonDisabled:o,ldapEnabled:l=!1,onLdapProvisioned:c}){const{t:d}=vt(),[u,m]=y.useState("local");y.useEffect(()=>{const f=g=>{g.key==="Escape"&&r()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r]);const p=f=>{e({...t,group_ids:t.group_ids.includes(f)?t.group_ids.filter(g=>g!==f):[...t.group_ids,f]})};return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:r,children:n.jsxs(Tt,{className:"w-full max-w-md",onClick:f=>f.stopPropagation(),children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex flex-col gap-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Sm,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:d("users.modal.createUser")})]}),n.jsx("p",{className:"text-sm text-bambu-gray ml-7",children:d("users.modal.advancedAuthSubtitle")||"with Advanced Authentication"})]}),n.jsx(Me,{variant:"ghost",size:"sm",onClick:r,children:n.jsx($t,{className:"w-5 h-5"})})]})}),n.jsxs(Mt,{children:[l&&n.jsxs("div",{className:"mb-4 flex items-center gap-1 p-1 bg-bambu-dark-secondary rounded-lg",role:"tablist","aria-label":d("users.modal.tabsAriaLabel"),children:[n.jsx("button",{type:"button",role:"tab","aria-selected":u==="local",onClick:()=>m("local"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${u==="local"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:d("users.modal.localTab")}),n.jsx("button",{type:"button",role:"tab","aria-selected":u==="ldap",onClick:()=>m("ldap"),className:`flex-1 px-3 py-2 text-sm rounded-md transition-colors ${u==="ldap"?"bg-bambu-green/15 text-bambu-green":"text-bambu-gray hover:text-white"}`,children:d("users.modal.ldapTab")})]}),u==="ldap"&&l?n.jsx(Jce,{onSuccess:f=>{c?.(f)}}):n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[d("users.form.username")," ",n.jsx("span",{className:"text-red-400",children:"*"})]}),n.jsx("input",{type:"text",value:t.username,onChange:f=>e({...t,username:f.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:d("users.form.usernamePlaceholder"),autoComplete:"username",required:!0})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm font-medium text-white mb-2",children:[d("users.form.email")||"Email"," ",n.jsx("span",{className:"text-red-400",children:"*"})]}),n.jsx("input",{type:"email",value:t.email,onChange:f=>e({...t,email:f.target.value}),className:"w-full px-4 py-3 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",placeholder:d("users.form.emailPlaceholder")||"user@example.com",required:!0})]}),n.jsx("div",{className:"bg-bambu-dark-secondary/50 border border-bambu-green/20 rounded-lg p-3",children:n.jsx("p",{className:"text-sm text-bambu-gray",children:d("users.form.autoGeneratedPassword")||"A secure password will be automatically generated and emailed to the user."})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-2",children:d("users.form.groups")}),n.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg",children:[a.map(f=>n.jsxs("label",{className:"flex items-center gap-3 px-2 py-1.5 rounded hover:bg-bambu-dark-tertiary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:t.group_ids.includes(f.id),onChange:()=>p(f.id),className:"w-4 h-4 rounded border-bambu-gray text-bambu-green focus:ring-bambu-green focus:ring-offset-0 bg-bambu-dark"}),n.jsx("span",{className:"text-sm text-white",children:f.name}),f.is_system&&n.jsxs("span",{className:"text-xs text-yellow-400",children:["(",d("users.system"),")"]})]},f.id)),a.length===0&&n.jsx("p",{className:"text-sm text-bambu-gray",children:d("users.noGroupsAvailable")})]})]})]}),n.jsxs("div",{className:"mt-6 flex justify-end gap-3",children:[n.jsx(Me,{variant:"secondary",onClick:r,children:d("users.modal.cancel")}),u==="local"&&n.jsx(Me,{onClick:i,disabled:o,children:s?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),d("users.modal.creating")]}):n.jsxs(n.Fragment,{children:[n.jsx(en,{className:"w-4 h-4"}),d("users.modal.createUser")]})})]})]})]})})}function Urt(){const{t}=vt(),e=ta(),{showToast:a}=ra(),[r,i]=y.useState(!1),[s,o]=y.useState(""),[l,c]=y.useState("auto"),[d,u]=y.useState(!1),[m,p]=y.useState(!0),[f,g]=y.useState("all"),[w,b]=y.useState(!1),[x,S]=y.useState(!1),[N,C]=y.useState(!1),[P,T]=y.useState(!1),{data:j,isLoading:F}=Qe({queryKey:["spoolman-settings"],queryFn:ne.getSpoolmanSettings}),{data:k,isLoading:M,refetch:q}=Qe({queryKey:["spoolman-status"],queryFn:ne.getSpoolmanStatus,refetchInterval:3e4}),{data:I}=Qe({queryKey:["printers"],queryFn:ne.getPrinters});y.useEffect(()=>{j&&(i(j.spoolman_enabled==="true"),o(j.spoolman_url||""),c(j.spoolman_sync_mode||"auto"),u(j.spoolman_disable_weight_sync==="true"),p(j.spoolman_report_partial_usage!=="false"),b(!0))},[j]),y.useEffect(()=>{if(!w||!j)return;if(j.spoolman_enabled==="true"!==r||(j.spoolman_url||"")!==s||(j.spoolman_sync_mode||"auto")!==l||j.spoolman_disable_weight_sync==="true"!==d||j.spoolman_report_partial_usage!=="false"!==m){const be=setTimeout(()=>{B.mutate()},500);return()=>clearTimeout(be)}},[r,s,l,d,m,w]);const B=lt({mutationFn:()=>ne.updateSpoolmanSettings({spoolman_enabled:r?"true":"false",spoolman_url:s,spoolman_sync_mode:l,spoolman_disable_weight_sync:d?"true":"false",spoolman_report_partial_usage:m?"true":"false"}),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolman-settings"]}),e.invalidateQueries({queryKey:["spoolman-status"]}),e.invalidateQueries({queryKey:["spool-assignments"]}),e.invalidateQueries({queryKey:["settings"]}),e.invalidateQueries({queryKey:["spoolman-inventory-filaments"]}),a(t("settings.toast.settingsSaved"))},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),R=lt({mutationFn:ne.connectSpoolman,onSuccess:()=>{q()},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),X=lt({mutationFn:ne.disconnectSpoolman,onSuccess:()=>{q()},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),ee=lt({mutationFn:ne.syncAllPrintersAms,onSuccess:me=>{a(t("settings.spoolmanAmsSyncSuccess",{synced:me.synced_count,skipped:0}),"success")},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),Q=lt({mutationFn:me=>ne.syncPrinterAms(me),onSuccess:me=>{a(t("settings.spoolmanAmsSyncSuccess",{synced:me.synced_count,skipped:0}),"success")},onError:()=>{a(t("settings.toast.saveFailed"),"error")}}),le=()=>{f==="all"?ee.mutate():Q.mutate(f)},de=lt({mutationFn:ne.syncWeightsFromAms,onSuccess:me=>{e.invalidateQueries({queryKey:["spools"]}),e.invalidateQueries({queryKey:["inventory-spools"]}),a(t("settings.amsSyncSuccess",{synced:me.synced,skipped:me.skipped}),"success"),C(!1)},onError:()=>{a(t("settings.amsSyncError"),"error"),C(!1)}}),ue=lt({mutationFn:ne.syncSpoolmanAmsWeights,onSuccess:me=>{e.invalidateQueries({queryKey:["spoolman-inventory-spools"]}),a(t("settings.spoolmanAmsSyncSuccess",{synced:me.synced,skipped:me.skipped}),"success"),T(!1)},onError:me=>{me instanceof Hi&&me.status===503?a(t("settings.spoolmanAmsSyncErrorUnreachable"),"error"):me instanceof Hi&&me.status===400?a(t("settings.spoolmanAmsSyncErrorNotConfigured"),"error"):a(t("settings.spoolmanAmsSyncError"),"error"),T(!1)}}),Z=ee.isPending||Q.isPending,oe=f==="all"?ee.data:Q.data,fe=f==="all"?ee.isSuccess:Q.isSuccess;return F?n.jsxs(Tt,{id:"card-spoolman",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(hc,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]})}),n.jsx(Mt,{children:n.jsx("div",{className:"flex justify-center py-8",children:n.jsx(pt,{className:"w-6 h-6 text-bambu-green animate-spin"})})})]}):n.jsxs(Tt,{id:"card-spoolman",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(hc,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.filamentTracking")})]}),B.isPending&&n.jsx(pt,{className:"w-4 h-4 text-bambu-green animate-spin"})]})}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.filamentTrackingDesc")}),n.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[n.jsxs("button",{type:"button",onClick:()=>i(!1),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50":"border-bambu-green bg-bambu-green/10"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx(Hn,{className:`w-4 h-4 ${r?"text-bambu-gray":"text-bambu-green"}`}),n.jsx("span",{className:`text-sm font-medium ${r?"text-bambu-gray":"text-white"}`,children:t("settings.trackingModeBuiltIn")})]}),n.jsx("p",{className:`text-xs ${r?"text-bambu-gray/60":"text-bambu-gray"}`,children:t("settings.trackingModeBuiltInDesc")}),!r&&n.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[n.jsx(_n,{className:"w-3 h-3 text-bambu-green"}),n.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]}),n.jsxs("button",{type:"button",onClick:()=>i(!0),className:`p-3 rounded-lg border-2 text-left transition-colors ${r?"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary bg-bambu-dark hover:border-bambu-gray/50"}`,children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[n.jsx(En,{className:`w-4 h-4 ${r?"text-bambu-green":"text-bambu-gray"}`}),n.jsx("span",{className:`text-sm font-medium ${r?"text-white":"text-bambu-gray"}`,children:"Spoolman"})]}),n.jsx("p",{className:`text-xs ${r?"text-bambu-gray":"text-bambu-gray/60"}`,children:t("settings.trackingModeSpoolmanDesc")}),r&&n.jsxs("div",{className:"flex items-center gap-1 mt-2",children:[n.jsx(_n,{className:"w-3 h-3 text-bambu-green"}),n.jsx("span",{className:"text-xs text-bambu-green",children:t("common.enabled")})]})]})]}),!r&&n.jsxs("div",{className:"space-y-3",children:[n.jsx("div",{className:"p-3 bg-bambu-green/5 border border-bambu-green/20 rounded-lg",children:n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Ei,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-0.5"}),n.jsx("div",{className:"text-xs text-bambu-gray",children:n.jsxs("ul",{className:"list-disc list-inside space-y-0.5",children:[n.jsx("li",{children:t("settings.builtInFeatureRfid")}),n.jsx("li",{children:t("settings.builtInFeatureUsage")}),n.jsx("li",{children:t("settings.builtInFeatureCatalog")}),n.jsx("li",{children:t("settings.builtInFeatureThirdParty")})]})})]})}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>C(!0),disabled:de.isPending,children:[de.isPending?n.jsx(pt,{className:"w-4 h-4 mr-2 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4 mr-2"}),t("settings.amsSyncButton")]})]}),r&&n.jsxs("div",{className:"space-y-4",children:[n.jsx("div",{className:"p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg",children:n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Ei,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{className:"text-xs text-blue-300",children:[n.jsx("p",{className:"font-medium mb-1",children:t("settings.howSyncWorks")}),n.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-blue-300/80",children:[n.jsx("li",{children:t("settings.syncInfoRfidOnly")}),n.jsx("li",{children:t("settings.syncInfoAutoCreate")}),n.jsx("li",{children:t("settings.syncInfoThirdPartySkipped")})]}),n.jsx("p",{className:"font-medium mt-2 mb-1",children:t("settings.linkingExistingSpools")}),n.jsx("p",{className:"text-blue-300/80",children:t("settings.linkingExistingSpoolsDesc")})]})]})}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.spoolmanUrl")}),n.jsx("input",{type:"text",placeholder:"http://192.168.1.100:7912",value:s,onChange:me=>o(me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray/50 focus:border-bambu-green focus:outline-none"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.spoolmanUrlHint")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("settings.syncMode")}),n.jsxs("select",{value:l,onChange:me=>c(me.target.value),className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:"auto",children:t("settings.syncModeAuto")}),n.jsx("option",{value:"manual",children:t("settings.syncModeManual")})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t(l==="auto"?"settings.syncModeAutoDesc":"settings.syncModeManualDesc")})]}),l==="auto"&&n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white",children:t("spoolman.disableWeightSync")}),n.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.disableWeightSyncDesc")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:d,onChange:me=>u(me.target.checked),className:"sr-only peer"}),n.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"})]})]}),d&&n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white",children:t("spoolman.reportPartialUsage")}),n.jsx("p",{className:"text-sm text-bambu-gray",children:t("spoolman.reportPartialUsageDesc")})]}),n.jsxs("label",{className:"relative inline-flex items-center cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:m,onChange:me=>p(me.target.checked),className:"sr-only peer"}),n.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"})]})]}),n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("span",{className:"text-sm text-bambu-gray",children:[t("settings.status"),":"]}),M?n.jsx(pt,{className:"w-4 h-4 text-bambu-gray animate-spin"}):k?.connected?n.jsxs("span",{className:"flex items-center gap-1 text-sm text-green-500",children:[n.jsx(_n,{className:"w-4 h-4"}),t("settings.spoolmanConnected")]}):n.jsxs("span",{className:"flex items-center gap-1 text-sm text-red-500",children:[n.jsx($t,{className:"w-4 h-4"}),t("settings.spoolmanDisconnected")]})]}),n.jsx("div",{className:"flex gap-2",children:k?.connected?n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>X.mutate(),disabled:X.isPending,children:[X.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Lxe,{className:"w-4 h-4"}),t("settings.disconnect")]}):n.jsxs(Me,{size:"sm",onClick:()=>R.mutate(),disabled:R.isPending||!s,children:[R.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Eh,{className:"w-4 h-4"}),t("settings.connect")]})})]}),(R.isError||X.isError)&&n.jsx("div",{className:"mb-3 p-2 bg-red-500/20 border border-red-500/50 rounded text-sm text-red-400",children:(R.error||X.error).message}),k?.connected&&n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:t("settings.syncAmsData")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.syncAmsDataDesc")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsxs("div",{className:"relative flex-1",children:[n.jsxs("select",{value:f,onChange:me=>g(me.target.value==="all"?"all":Number(me.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:[n.jsx("option",{value:"all",children:t("settings.allPrinters")}),I?.map(me=>n.jsx("option",{value:me.id,children:me.name},me.id))]}),n.jsx(Da,{className:"absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:le,disabled:Z,children:[Z?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),t("spoolman.sync")]})]})]}),k?.connected&&n.jsx("div",{className:"mt-4 pt-4 border-t border-bambu-dark-tertiary",children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-sm text-white",children:t("settings.spoolmanAmsSyncButton")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:t("settings.spoolmanAmsSyncMessage")})]}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:()=>T(!0),disabled:ue.isPending,children:[ue.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),ue.isPending?t("settings.spoolmanAmsSyncing"):t("settings.spoolmanAmsSyncButton")]})]})}),fe&&oe&&n.jsxs("div",{className:"mt-3 space-y-2",children:[n.jsx("div",{className:`p-2 rounded text-sm ${oe.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:oe.success?`Synced ${oe.synced_count} spool${oe.synced_count!==1?"s":""} successfully`:`Synced ${oe.synced_count} spool${oe.synced_count!==1?"s":""} with ${oe.errors.length} error${oe.errors.length!==1?"s":""}`}),oe.skipped_count>0&&n.jsxs("div",{className:"p-2 bg-amber-500/10 border border-amber-500/30 rounded text-sm",children:[n.jsxs("div",{className:"flex items-center justify-between text-amber-400 mb-1",children:[n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx(ba,{className:"w-3.5 h-3.5"}),n.jsxs("span",{className:"font-medium",children:[oe.skipped_count," spool",oe.skipped_count!==1?"s":""," skipped"]})]}),oe.skipped_count>5&&n.jsx("button",{onClick:()=>S(!x),className:"text-xs text-amber-400 hover:text-amber-300 underline",children:x?"Show less":"Show all"})]}),n.jsxs("ul",{className:"text-xs text-amber-300/80 space-y-0.5",children:[(x?oe.skipped:oe.skipped.slice(0,5)).map((me,be)=>n.jsxs("li",{className:"flex items-center gap-2",children:[me.color&&n.jsx("span",{className:"w-3 h-3 rounded-full border border-black/20",style:{backgroundColor:`#${me.color}`}}),n.jsx("span",{children:me.location}),n.jsxs("span",{className:"text-amber-300/60",children:["- ",me.reason]})]},be)),!x&&oe.skipped_count>5&&n.jsxs("li",{className:"text-amber-300/60 italic",children:["...and ",oe.skipped_count-5," more"]})]})]}),oe.errors.length>0&&n.jsxs("div",{className:"p-2 bg-red-500/10 border border-red-500/30 rounded text-sm",children:[n.jsx("div",{className:"text-red-400 font-medium mb-1",children:"Errors:"}),n.jsx("ul",{className:"text-xs text-red-300/80 space-y-0.5",children:oe.errors.map((me,be)=>n.jsx("li",{children:me},be))})]})]})]})]})]}),N&&n.jsx(ya,{title:t("settings.amsSyncTitle"),message:t("settings.amsSyncMessage"),confirmText:t("settings.amsSyncButton"),variant:"warning",isLoading:de.isPending,loadingText:t("settings.amsSyncing"),onConfirm:()=>de.mutate(),onCancel:()=>C(!1)}),P&&n.jsx(ya,{title:t("settings.spoolmanAmsSyncTitle"),message:t("settings.spoolmanAmsSyncMessage"),confirmText:t("settings.spoolmanAmsSyncButton"),variant:"warning",isLoading:ue.isPending,loadingText:t("settings.spoolmanAmsSyncing"),onConfirm:()=>ue.mutate(),onCancel:()=>T(!1)})]})}function Brt(){const{t}=vt(),{showToast:e}=ra(),[a,r]=y.useState([]),[i,s]=y.useState(!0),[o,l]=y.useState(""),c=y.useRef(null),[d,u]=y.useState(!1),[m,p]=y.useState(null),[f,g]=y.useState(""),[w,b]=y.useState(""),[x,S]=y.useState(!1),[N,C]=y.useState(new Set),[P,T]=y.useState(!1),[j,F]=y.useState(null),[k,M]=y.useState(!1),q=y.useCallback(async()=>{try{const me=await ne.getSpoolCatalog();r(me)}catch(me){console.error("SpoolCatalogSettings.loadCatalog failed:",me),e(t("settings.catalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);y.useEffect(()=>{q()},[q]);const I=a.filter(me=>me.name.toLowerCase().includes(o.toLowerCase())),B=async()=>{if(!f.trim()||!w){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const me=await ne.addCatalogEntry({name:f.trim(),weight:parseInt(w)});r(be=>[...be,me].sort((H,J)=>H.name.localeCompare(J.name))),u(!1),g(""),b(""),e(t("settings.catalog.entryAdded"),"success")}catch(me){console.error("SpoolCatalogSettings.handleAdd failed:",me),e(t("settings.catalog.addFailed"),"error")}finally{S(!1)}},R=me=>{p(me.id),g(me.name),b(me.weight.toString())},X=()=>{p(null),g(""),b("")},ee=async me=>{if(!f.trim()||!w){e(t("settings.catalog.nameWeightRequired"),"error");return}S(!0);try{const be=await ne.updateCatalogEntry(me,{name:f.trim(),weight:parseInt(w)});r(H=>H.map(J=>J.id===me?be:J).sort((J,A)=>J.name.localeCompare(A.name))),p(null),g(""),b(""),e(t("settings.catalog.entryUpdated"),"success")}catch(be){console.error("SpoolCatalogSettings.handleUpdate failed:",be),e(t("settings.catalog.updateFailed"),"error")}finally{S(!1)}},Q=async()=>{if(j)try{await ne.deleteCatalogEntry(j.id),r(me=>me.filter(be=>be.id!==j.id)),e(t("settings.catalog.entryDeleted"),"success")}catch(me){console.error("SpoolCatalogSettings.handleDelete failed:",me),e(t("settings.catalog.deleteFailed"),"error")}finally{F(null)}},le=async()=>{M(!1),s(!0);try{await ne.resetSpoolCatalog(),await q(),e(t("settings.catalog.resetSuccess"),"success")}catch(me){console.error("SpoolCatalogSettings.handleReset failed:",me),e(t("settings.catalog.resetFailed"),"error"),s(!1)}},de=me=>{C(be=>{const H=new Set(be);return H.has(me)?H.delete(me):H.add(me),H})},ue=()=>{N.size===I.length?C(new Set):C(new Set(I.map(me=>me.id)))},Z=async()=>{if(T(!1),N.size!==0)try{const me=await ne.bulkDeleteCatalogEntries([...N]);r(be=>be.filter(H=>!N.has(H.id))),C(new Set),e(t("settings.catalog.bulkDeleted",{count:me.deleted}),"success")}catch(me){console.error("SpoolCatalogSettings.handleBulkDelete failed:",me),e(t("settings.catalog.bulkDeleteFailed"),"error")}},oe=()=>{const me=a.map(({name:A,weight:E})=>({name:A,weight:E})),be=new Blob([JSON.stringify(me,null,2)],{type:"application/json"}),H=URL.createObjectURL(be),J=document.createElement("a");J.href=H,J.download="spool-catalog.json",document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(H),e(t("settings.catalog.exported",{count:a.length}),"success")},fe=async me=>{const be=me.target.files?.[0];if(be){try{const H=await be.text(),J=JSON.parse(H);if(!Array.isArray(J))throw new Error("Invalid format");let A=0,E=0;for(const z of J){if(!z.name||typeof z.weight!="number"){E++;continue}if(a.some(O=>O.name.toLowerCase()===z.name.toLowerCase())){E++;continue}try{const O=await ne.addCatalogEntry({name:z.name,weight:z.weight});r(re=>[...re,O].sort((U,V)=>U.name.localeCompare(V.name))),A++}catch(O){console.error("SpoolCatalogSettings import item failed:",O),E++}}e(t("settings.catalog.imported",{added:A,skipped:E}),"success")}catch(H){console.error("SpoolCatalogSettings.handleImport failed:",H),e(t("settings.catalog.importFailed"),"error")}c.current&&(c.current.value="")}};return n.jsxs(Tt,{id:"card-spool-catalog",children:[n.jsxs(fa,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(hc,{className:"w-5 h-5 text-bambu-gray"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.catalog.spoolCatalog")}),n.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",a.length,")"]})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsxs("button",{onClick:oe,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.exportTooltip"),children:[n.jsx(Bn,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),n.jsxs("button",{onClick:()=>c.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.importTooltip"),children:[n.jsx(Sr,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),n.jsx("input",{ref:c,type:"file",accept:".json",className:"hidden",onChange:fe}),n.jsxs("button",{onClick:()=>M(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.catalog.resetTooltip"),children:[n.jsx(vs,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),n.jsxs("button",{onClick:()=>u(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[n.jsx(en,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),N.size>0&&n.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[n.jsx("span",{className:"text-sm text-red-400",children:t("settings.catalog.selectedCount",{count:N.size})}),n.jsxs("button",{onClick:()=>T(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[n.jsx(ea,{className:"w-4 h-4"}),t("settings.catalog.deleteSelected")]}),n.jsx("button",{onClick:()=>C(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.catalog.spoolCatalogDescription")}),n.jsxs("div",{className:"relative",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),n.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.searchCatalog"),value:o,onChange:me=>l(me.target.value)})]}),d&&n.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.catalog.addNewEntry")}),n.jsxs("div",{className:"flex gap-2 items-center",children:[n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx("input",{type:"text",className:"w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.catalog.namePlaceholder"),value:f,onChange:me=>g(me.target.value)})}),n.jsx("input",{type:"number",className:"w-20 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-center focus:border-bambu-green focus:outline-none",placeholder:"g",value:w,onChange:me=>b(me.target.value)}),n.jsx("span",{className:"text-bambu-gray shrink-0",children:"g"}),n.jsxs("button",{onClick:B,disabled:x,className:"px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center gap-1 shrink-0",children:[x?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(_n,{className:"w-4 h-4"}),t("common.add")]}),n.jsx("button",{onClick:()=>{u(!1),g(""),b("")},className:"p-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:n.jsx($t,{className:"w-4 h-4"})})]})]}),i?n.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[n.jsx(pt,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):n.jsx("div",{className:"max-h-[600px] overflow-y-auto border border-bambu-dark-tertiary rounded-lg",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:n.jsxs("tr",{children:[n.jsx("th",{className:"px-2 py-2 w-10",children:n.jsx("input",{type:"checkbox",checked:I.length>0&&N.size===I.length,onChange:ue,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("th",{className:"px-4 py-2 text-left text-bambu-gray font-medium",children:t("common.name")}),n.jsx("th",{className:"px-4 py-2 text-right text-bambu-gray font-medium w-24",children:t("settings.catalog.weight")}),n.jsx("th",{className:"px-4 py-2 text-center text-bambu-gray font-medium w-20",children:t("settings.catalog.type")}),n.jsx("th",{className:"px-4 py-2 w-24"})]})}),n.jsx("tbody",{children:I.length===0?n.jsx("tr",{children:n.jsx("td",{colSpan:5,className:"px-4 py-8 text-center text-bambu-gray",children:t(o?"settings.catalog.noMatch":"settings.catalog.empty")})}):I.map(me=>n.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${N.has(me.id)?"bg-bambu-dark":""}`,children:m===me.id?n.jsxs(n.Fragment,{children:[n.jsx("td",{className:"px-2 py-2",children:n.jsx("input",{type:"checkbox",checked:N.has(me.id),onChange:()=>de(me.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("td",{className:"px-4 py-2",children:n.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white focus:border-bambu-green focus:outline-none",value:f,onChange:be=>g(be.target.value)})}),n.jsx("td",{className:"px-4 py-2",children:n.jsx("input",{type:"number",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-right focus:border-bambu-green focus:outline-none",value:w,onChange:be=>b(be.target.value)})}),n.jsx("td",{className:"px-4 py-2 text-center",children:n.jsx("span",{className:"text-xs text-bambu-gray",children:"-"})}),n.jsx("td",{className:"px-4 py-2",children:n.jsxs("div",{className:"flex justify-end gap-1",children:[n.jsx("button",{onClick:()=>ee(me.id),disabled:x,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:x?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(_n,{className:"w-4 h-4"})}),n.jsx("button",{onClick:X,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:n.jsx($t,{className:"w-4 h-4"})})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx("td",{className:"px-2 py-2",children:n.jsx("input",{type:"checkbox",checked:N.has(me.id),onChange:()=>de(me.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("td",{className:"px-4 py-2 text-white",children:me.name}),n.jsxs("td",{className:"px-4 py-2 text-right font-mono text-white",children:[me.weight,"g"]}),n.jsx("td",{className:"px-4 py-2 text-center",children:me.is_default?n.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-dark-tertiary text-bambu-gray",children:t("settings.catalog.default")}):n.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-bambu-green/20 text-bambu-green",children:t("settings.catalog.custom")})}),n.jsx("td",{className:"px-4 py-2",children:n.jsxs("div",{className:"flex justify-end gap-1",children:[n.jsx("button",{onClick:()=>R(me),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:n.jsx(yi,{className:"w-4 h-4"})}),n.jsx("button",{onClick:()=>F(me),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:n.jsx(ea,{className:"w-4 h-4"})})]})})]})},me.id))})]})})]}),j&&n.jsx(ya,{title:t("settings.catalog.deleteEntry"),message:t("settings.catalog.deleteConfirm",{name:j.name}),confirmText:t("common.delete"),variant:"danger",onConfirm:Q,onCancel:()=>F(null)}),P&&n.jsx(ya,{title:t("settings.catalog.deleteSelected"),message:t("settings.catalog.bulkDeleteConfirm",{count:N.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:Z,onCancel:()=>T(!1)}),k&&n.jsx(ya,{title:t("settings.catalog.resetCatalog"),message:t("settings.catalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:le,onCancel:()=>M(!1)})]})}const qrt=2166136261,Hrt=16777619;function $rt(...t){let e=qrt;const a=new TextEncoder,r=a.encode("__|");for(const i of t)typeof i=="string"?e=SX(e,a.encode(i+"|")):i==null&&(e=SX(e,r));return e>>>0}function SX(t,e){for(const a of e)t^=a,t=Math.imul(t,Hrt)>>>0;return t}function Vrt(t){const e=()=>{t|=0,t=t+1831565813|0;let r=Math.imul(t^t>>>15,1|t);return r=r+Math.imul(r^r>>>7,61|r)^r,(r^r>>>14)>>>0},a=(r,i)=>{if(!Number.isFinite(r)||!Number.isFinite(i))throw new RangeError("from and to must be finite numbers");if(r>i)throw new RangeError("from must be less than or equal to to");return r===i?r:r+e()/4294967295*(i-r)};return{next:()=>e()/4294967295,floatBetween:(r,i)=>a(r,i),intBetween:(r,i)=>{if(!Number.isInteger(r)||!Number.isInteger(i))throw new RangeError("from and to must be integers");return Math.round(a(r,i))}}}const kX={table:{dotCount:5,dotScale:1},preview:{dotCount:8,dotScale:1.5},card:{dotCount:40,dotScale:2},bar:{dotCount:20,dotScale:2},groupheader:{dotCount:80,dotScale:2}},rO=[{value:"",labelKey:"inventory.colorEffect.none"},{value:"sparkle",labelKey:"inventory.colorEffect.sparkle"},{value:"wood",labelKey:"inventory.colorEffect.wood"},{value:"marble",labelKey:"inventory.colorEffect.marble"},{value:"glow",labelKey:"inventory.colorEffect.glow"},{value:"matte",labelKey:"inventory.colorEffect.matte"},{value:"silk",labelKey:"inventory.colorEffect.silk"},{value:"galaxy",labelKey:"inventory.colorEffect.galaxy"},{value:"rainbow",labelKey:"inventory.colorEffect.rainbow"},{value:"metal",labelKey:"inventory.colorEffect.metal"},{value:"translucent",labelKey:"inventory.colorEffect.translucent"},{value:"gradient",labelKey:"inventory.colorEffect.gradient"},{value:"dual-color",labelKey:"inventory.colorEffect.dualColor"},{value:"tri-color",labelKey:"inventory.colorEffect.triColor"},{value:"multicolor",labelKey:"inventory.colorEffect.multicolor"}],Grt="repeating-conic-gradient(#979797 0% 25%, #f5f5f5 0% 50%)",Wrt="12px 12px",Krt={sparkle:(t=0,e="table")=>{const a=Vrt(t),r=kX[e]??kX.table,i=[];for(let s=0;s"repeating-linear-gradient(90deg, rgba(0,0,0,0.18) 0 1px, transparent 1px 6px, rgba(0,0,0,0.08) 6px 7px, transparent 7px 12px)",marble:()=>"repeating-linear-gradient(135deg, rgba(255,255,255,0.18) 0 2px, transparent 2px 8px), repeating-linear-gradient(45deg, rgba(0,0,0,0.10) 0 1px, transparent 1px 7px)",glow:()=>"radial-gradient(circle at 50% 50%, rgba(255,255,255,0.35) 0%, rgba(255,255,255,0) 70%)",matte:()=>"linear-gradient(180deg, rgba(0,0,0,0.10) 0%, rgba(0,0,0,0) 50%, rgba(0,0,0,0.10) 100%)",silk:()=>"linear-gradient(110deg, rgba(255,255,255,0) 30%, rgba(255,255,255,0.30) 50%, rgba(255,255,255,0) 70%)",galaxy:()=>"linear-gradient(110deg, rgba(255,255,255,0) 25%, rgba(255,255,255,0.40) 50%, rgba(255,255,255,0) 75%)",metal:()=>"repeating-linear-gradient(90deg, rgba(255,255,255,0.10) 0 1px, transparent 1px 3px), linear-gradient(180deg, rgba(255,255,255,0.18) 0%, rgba(0,0,0,0.18) 100%)"};function ede(t){const e=t.trim().replace(/^#/,"");return e.length!==6&&e.length!==8||!/^[0-9a-fA-F]+$/.test(e)?null:`#${e}`}function tde(t){return t?t.split(",").map(e=>ede(e)).filter(e=>!!e):[]}function Qrt(t,e,a,r){const i=t?ede(t):null;if(e.length===0)return`linear-gradient(${i??"#808080"}, ${i??"#808080"})`;const s=e.length===1?[e[0],e[0]]:e,o=(a??"").toLowerCase(),l=(r??"").toLowerCase();if(o==="multicolor"||l==="multicolor"){const c=s.length;return`conic-gradient(from 0deg, ${s.map((u,m)=>{const p=(m/c*360).toFixed(3),f=((m+1)/c*360).toFixed(3);return`${u} ${p}deg ${f}deg`}).join(", ")})`}if(l==="dual-color"||l==="tri-color"){const c=s.length;return`linear-gradient(to right, ${s.map((u,m)=>{const p=(m/c*100).toFixed(3),f=((m+1)/c*100).toFixed(3);return`${u} ${p}% ${f}%`}).join(", ")})`}return`linear-gradient(135deg, ${s.join(", ")})`}function Yrt(t,e,a){const r=Krt[t];return r?r(a,e):null}function pj(t){const e=tde(t.extraColors),a=Qrt(t.rgba,e,t.subtype,t.effectType),r=$rt(t.rgba,t.extraColors,t.subtype,t.effectType),i=typeof t.effectType=="string"?Yrt(t.effectType,t.effectSize,r):null,s=[];return i&&(Array.isArray(i)?i:[i]).forEach(l=>{s.push({image:l,size:"cover"})}),s.push({image:a,size:"cover"}),s.push({image:Grt,size:Wrt}),{backgroundImage:s.map(o=>o.image).join(", "),backgroundSize:s.map(o=>o.size).join(", ")}}function xU({rgba:t,extraColors:e,effectType:a,subtype:r,className:i="w-5 h-5",shape:s="circle",style:o,title:l,effectSize:c}){const d=y.useMemo(()=>tde(e),[e]),u=y.useMemo(()=>pj({effectSize:c,rgba:t,extraColors:e,effectType:a,subtype:r}),[c,t,e,a,r]),m=u.backgroundImage,p=u.backgroundSize,f=s==="circle"||s==="pill"?"rounded-full":"rounded",g=l??(d.length>0?d.join(", "):t?`#${t.substring(0,6)}`:void 0);return n.jsx("span",{"data-testid":"filament-swatch",className:`${i} ${f} border border-black/20 inline-block flex-shrink-0`,style:{backgroundImage:m,backgroundSize:p,...o},title:g})}function Xrt(){const{t}=vt(),{showToast:e}=ra(),[a,r]=y.useState([]),[i,s]=y.useState(!0),[o,l]=y.useState(""),[c,d]=y.useState(""),u=y.useRef(null),[m,p]=y.useState(!1),[f,g]=y.useState(null),[w,b]=y.useState(""),[x,S]=y.useState(""),[N,C]=y.useState("#FFFFFF"),[P,T]=y.useState(""),[j,F]=y.useState(""),[k,M]=y.useState(""),[q,I]=y.useState(!1),[B,R]=y.useState(new Set),[X,ee]=y.useState(!1),[Q,le]=y.useState(!1),[de,ue]=y.useState(null),[Z,oe]=y.useState(null),[fe,me]=y.useState(!1),be=y.useCallback(async()=>{try{const ce=await ne.getColorCatalog();r(ce)}catch{e(t("settings.colorCatalog.loadFailed"),"error")}finally{s(!1)}},[e,t]);y.useEffect(()=>{be()},[be]);const H=[...new Set(a.map(ce=>ce.manufacturer))].sort(),J=a.filter(ce=>{const he=o===""||ce.manufacturer.toLowerCase().includes(o.toLowerCase())||ce.color_name.toLowerCase().includes(o.toLowerCase())||(ce.material?.toLowerCase().includes(o.toLowerCase())??!1),$=c===""||ce.manufacturer===c;return he&&$}),A=()=>{b(""),S(""),C("#FFFFFF"),T(""),F(""),M("")},E=async()=>{if(!w.trim()||!x.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}I(!0);try{const ce=await ne.addColorEntry({manufacturer:w.trim(),color_name:x.trim(),hex_color:N,material:P.trim()||null,extra_colors:j.trim()||null,effect_type:k.trim()||null});r(he=>[...he,ce].sort(($,L)=>$.manufacturer.localeCompare(L.manufacturer)||($.material||"").localeCompare(L.material||"")||$.color_name.localeCompare(L.color_name))),p(!1),A(),e(t("settings.colorCatalog.colorAdded"),"success")}catch{e(t("settings.colorCatalog.addFailed"),"error")}finally{I(!1)}},z=ce=>{g(ce.id),b(ce.manufacturer),S(ce.color_name),C(ce.hex_color),T(ce.material||""),F(ce.extra_colors||""),M(ce.effect_type||"")},W=()=>{g(null),A()},O=async ce=>{if(!w.trim()||!x.trim()||!N){e(t("settings.colorCatalog.fieldsRequired"),"error");return}I(!0);try{const he=await ne.updateColorEntry(ce,{manufacturer:w.trim(),color_name:x.trim(),hex_color:N,material:P.trim()||null,extra_colors:j.trim()||null,effect_type:k.trim()||null});r($=>$.map(L=>L.id===ce?he:L).sort((L,ae)=>L.manufacturer.localeCompare(ae.manufacturer)||(L.material||"").localeCompare(ae.material||"")||L.color_name.localeCompare(ae.color_name))),g(null),A(),e(t("settings.colorCatalog.colorUpdated"),"success")}catch{e(t("settings.colorCatalog.updateFailed"),"error")}finally{I(!1)}},re=async()=>{if(Z)try{await ne.deleteColorEntry(Z.id),r(ce=>ce.filter(he=>he.id!==Z.id)),e(t("settings.colorCatalog.colorDeleted"),"success")}catch{e(t("settings.colorCatalog.deleteFailed"),"error")}finally{oe(null)}},U=async()=>{me(!1),s(!0);try{await ne.resetColorCatalog(),await be(),e(t("settings.colorCatalog.resetSuccess"),"success")}catch{e(t("settings.colorCatalog.resetFailed"),"error"),s(!1)}},V=async()=>{le(!0),ue(null);try{const ce={},he=Jm();he&&(ce.Authorization=`Bearer ${he}`);const $=await fetch("/api/v1/inventory/colors/sync",{method:"POST",headers:ce});if(!$.ok)throw new Error("Failed to start sync");const L=$.body?.getReader();if(!L)throw new Error("No response body");const ae=new TextDecoder;let ge="";for(;;){const{done:xe,value:Se}=await L.read();if(xe)break;ge+=ae.decode(Se,{stream:!0});const Te=ge.split(` `);ge=Te.pop()||"";for(const ve of Te)if(ve.startsWith("data: "))try{const we=JSON.parse(ve.slice(6));we.type==="progress"?ue({fetched:we.total_fetched,total:we.total_available}):we.type==="complete"?we.added===0?e(t("settings.colorCatalog.syncUpToDate",{count:we.total_fetched}),"success"):e(t("settings.colorCatalog.syncComplete",{added:we.added,skipped:we.skipped}),"success"):we.type==="error"&&e(`${t("settings.colorCatalog.syncError")}: ${we.error}`,"error")}catch{}}await be()}catch{e(t("settings.colorCatalog.syncFailed"),"error")}finally{le(!1),ue(null)}},K=ce=>{R(he=>{const $=new Set(he);return $.has(ce)?$.delete(ce):$.add(ce),$})},Y=()=>{B.size===J.length?R(new Set):R(new Set(J.map(ce=>ce.id)))},ie=async()=>{if(ee(!1),B.size!==0)try{const ce=await ne.bulkDeleteColorEntries([...B]);r(he=>he.filter($=>!B.has($.id))),R(new Set),e(t("settings.colorCatalog.bulkDeleted",{count:ce.deleted}),"success")}catch{e(t("settings.colorCatalog.bulkDeleteFailed"),"error")}},se=()=>{const ce=a.map(({manufacturer:ae,color_name:ge,hex_color:xe,material:Se,extra_colors:Te,effect_type:ve})=>({manufacturer:ae,color_name:ge,hex_color:xe,material:Se,extra_colors:Te,effect_type:ve})),he=new Blob([JSON.stringify(ce,null,2)],{type:"application/json"}),$=URL.createObjectURL(he),L=document.createElement("a");L.href=$,L.download="color-catalog.json",document.body.appendChild(L),L.click(),document.body.removeChild(L),URL.revokeObjectURL($),e(t("settings.colorCatalog.exported",{count:a.length}),"success")},pe=async ce=>{const he=ce.target.files?.[0];if(he){try{const $=await he.text(),L=JSON.parse($);if(!Array.isArray(L))throw new Error("Invalid format");let ae=0,ge=0;for(const xe of L){if(!xe.manufacturer||!xe.color_name||!xe.hex_color){ge++;continue}if(a.some(Te=>Te.manufacturer.toLowerCase()===xe.manufacturer.toLowerCase()&&Te.color_name.toLowerCase()===xe.color_name.toLowerCase()&&(Te.material||"").toLowerCase()===(xe.material||"").toLowerCase())){ge++;continue}try{const Te=await ne.addColorEntry({manufacturer:xe.manufacturer,color_name:xe.color_name,hex_color:xe.hex_color,material:xe.material||null,extra_colors:xe.extra_colors||null,effect_type:xe.effect_type||null});r(ve=>[...ve,Te].sort((we,ze)=>we.manufacturer.localeCompare(ze.manufacturer)||(we.material||"").localeCompare(ze.material||"")||we.color_name.localeCompare(ze.color_name))),ae++}catch{ge++}}e(t("settings.colorCatalog.imported",{added:ae,skipped:ge}),"success")}catch{e(t("settings.colorCatalog.importFailed"),"error")}u.current&&(u.current.value="")}};return n.jsxs(Tt,{id:"card-color-catalog",children:[n.jsxs(fa,{children:[n.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[n.jsx(LS,{className:"w-5 h-5 text-bambu-gray"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.colorCatalog.title")}),n.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",a.length,")"]})]}),n.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[n.jsxs("button",{onClick:se,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[n.jsx(Bn,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.export")})]}),n.jsxs("button",{onClick:()=>u.current?.click(),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[n.jsx(Sr,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.import")})]}),n.jsx("input",{ref:u,type:"file",accept:".json",className:"hidden",onChange:pe}),n.jsxs("button",{onClick:V,disabled:Q,className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",title:t("settings.colorCatalog.syncTooltip"),children:[Q?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Gh,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:Q?de?`${Math.min(de.fetched,de.total)} / ${de.total}`:t("settings.colorCatalog.starting"):t("settings.colorCatalog.sync")})]}),n.jsxs("button",{onClick:()=>me(!0),className:"px-3 py-1.5 text-sm bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-bambu-gray hover:text-white transition-colors flex items-center gap-1.5",children:[n.jsx(vs,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.reset")})]}),n.jsxs("button",{onClick:()=>p(!0),className:"px-3 py-1.5 text-sm bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 transition-colors flex items-center gap-1.5",children:[n.jsx(en,{className:"w-4 h-4"}),n.jsx("span",{className:"hidden sm:inline",children:t("common.add")})]})]}),B.size>0&&n.jsxs("div",{className:"flex items-center gap-2 mt-2 px-3 py-2 bg-red-500/10 border border-red-500/30 rounded-lg",children:[n.jsx("span",{className:"text-sm text-red-400",children:t("settings.colorCatalog.selectedCount",{count:B.size})}),n.jsxs("button",{onClick:()=>ee(!0),className:"ml-auto px-3 py-1.5 text-sm bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-1.5",children:[n.jsx(ea,{className:"w-4 h-4"}),t("settings.colorCatalog.deleteSelected")]}),n.jsx("button",{onClick:()=>R(new Set),className:"px-3 py-1.5 text-sm text-bambu-gray hover:text-white transition-colors",children:t("common.cancel")})]})]}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:t("settings.colorCatalog.description")}),n.jsxs("div",{className:"flex gap-2 flex-wrap",children:[n.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[n.jsx(gn,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray"}),n.jsx("input",{type:"text",className:"w-full pl-10 pr-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.searchColors"),value:o,onChange:ce=>l(ce.target.value)})]}),n.jsxs("select",{className:"px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",value:c,onChange:ce=>d(ce.target.value),children:[n.jsx("option",{value:"",children:t("settings.colorCatalog.allManufacturers")}),H.map(ce=>n.jsx("option",{value:ce,children:ce},ce))]})]}),m&&n.jsxs("div",{className:"p-4 bg-bambu-dark rounded-lg border border-bambu-dark-tertiary",children:[n.jsx("h3",{className:"text-sm font-medium text-white mb-3",children:t("settings.colorCatalog.addNewColor")}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end",children:[n.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.manufacturer"),value:w,onChange:ce=>b(ce.target.value)}),n.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.colorName"),value:x,onChange:ce=>S(ce.target.value)}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"color",className:"w-20 h-10 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:ce=>C(ce.target.value)}),n.jsx("input",{type:"text",className:"w-32 px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:"#FFFFFF",value:N,onChange:ce=>C(ce.target.value)})]}),n.jsxs("div",{className:"flex items-center gap-1",children:[n.jsx("input",{type:"text",className:"flex-1 max-w-lg min-w-[200px] px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("settings.colorCatalog.materialOptional"),value:P,onChange:ce=>T(ce.target.value)}),n.jsxs("button",{onClick:E,disabled:q,className:"w-24 px-3 py-2 bg-bambu-green text-white rounded-lg hover:bg-bambu-green/80 flex items-center justify-center gap-3",children:[q?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(_n,{className:"w-4 h-4"}),t("common.add")]}),n.jsx("button",{onClick:()=>{p(!1),A()},className:"p-2 ml-2 rounded-lg text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary",children:n.jsx($t,{className:"w-4 h-4"})})]})]}),n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mt-2",children:[n.jsx("input",{type:"text",className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm font-mono placeholder-bambu-gray focus:border-bambu-green focus:outline-none",placeholder:t("inventory.extraColorsPlaceholder"),value:j,onChange:ce=>F(ce.target.value)}),n.jsx("select",{className:"px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none",value:k,onChange:ce=>M(ce.target.value),children:rO.map(ce=>n.jsx("option",{value:ce.value,children:t(ce.labelKey)},ce.value||"none"))})]})]}),(o||c)&&n.jsx("div",{className:"text-xs text-bambu-gray",children:t("settings.colorCatalog.showing",{filtered:J.length,total:a.length})}),i?n.jsxs("div",{className:"flex items-center justify-center py-8 text-bambu-gray",children:[n.jsx(pt,{className:"w-5 h-5 animate-spin mr-2"}),t("common.loading")]}):n.jsx("div",{className:"max-h-[600px] overflow-auto border border-bambu-dark-tertiary rounded-lg",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{className:"bg-bambu-dark sticky top-0",children:n.jsxs("tr",{children:[n.jsx("th",{className:"px-2 py-2 w-10",children:n.jsx("input",{type:"checkbox",checked:J.length>0&&B.size===J.length,onChange:Y,className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-12"}),n.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.manufacturer")}),n.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("inventory.material")}),n.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium",children:t("settings.colorCatalog.colorName")}),n.jsx("th",{className:"px-3 py-2 text-left text-bambu-gray font-medium w-24",children:t("settings.colorCatalog.hex")}),n.jsx("th",{className:"px-3 py-2 w-16"})]})}),n.jsx("tbody",{children:J.length===0?n.jsx("tr",{children:n.jsx("td",{colSpan:7,className:"px-3 py-8 text-center text-bambu-gray",children:t(o||c?"settings.colorCatalog.noMatch":"settings.colorCatalog.empty")})}):J.map(ce=>n.jsxs(y.Fragment,{children:[n.jsx("tr",{className:`border-t border-bambu-dark-tertiary hover:bg-bambu-dark ${B.has(ce.id)?"bg-bambu-dark":""}`,children:f===ce.id?n.jsxs(n.Fragment,{children:[n.jsx("td",{className:"px-2 py-2",children:n.jsx("input",{type:"checkbox",checked:B.has(ce.id),onChange:()=>K(ce.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("td",{className:"px-3 py-2",children:n.jsx("input",{type:"color",className:"w-8 h-8 rounded cursor-pointer border border-bambu-dark-tertiary",value:N,onChange:he=>C(he.target.value)})}),n.jsx("td",{className:"px-3 py-2",children:n.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:w,onChange:he=>b(he.target.value)})}),n.jsx("td",{className:"px-3 py-2",children:n.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:P,onChange:he=>T(he.target.value)})}),n.jsx("td",{className:"px-3 py-2",children:n.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:x,onChange:he=>S(he.target.value)})}),n.jsx("td",{className:"px-3 py-2",children:n.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:N,onChange:he=>C(he.target.value)})}),n.jsx("td",{className:"px-3 py-2",children:n.jsxs("div",{className:"flex justify-end gap-1",children:[n.jsx("button",{onClick:()=>O(ce.id),disabled:q,className:"p-1.5 rounded hover:bg-green-500/20 text-green-500",children:q?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(_n,{className:"w-4 h-4"})}),n.jsx("button",{onClick:W,className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray",children:n.jsx($t,{className:"w-4 h-4"})})]})})]}):n.jsxs(n.Fragment,{children:[n.jsx("td",{className:"px-2 py-2",children:n.jsx("input",{type:"checkbox",checked:B.has(ce.id),onChange:()=>K(ce.id),className:"w-4 h-4 accent-bambu-green cursor-pointer"})}),n.jsx("td",{className:"px-3 py-2",children:n.jsx(xU,{rgba:ce.hex_color.replace(/^#/,"")+(ce.hex_color.length===7?"FF":""),extraColors:ce.extra_colors,effectType:ce.effect_type,className:"w-8 h-8",shape:"square",title:ce.hex_color,effectSize:"table"})}),n.jsx("td",{className:"px-3 py-2 text-white",children:ce.manufacturer}),n.jsx("td",{className:"px-3 py-2 text-bambu-gray",children:ce.material||"-"}),n.jsx("td",{className:"px-3 py-2 text-white",children:ce.color_name}),n.jsx("td",{className:"px-3 py-2 font-mono text-xs text-bambu-gray",children:ce.hex_color}),n.jsx("td",{className:"px-3 py-2",children:n.jsxs("div",{className:"flex justify-end gap-1",children:[n.jsx("button",{onClick:()=>z(ce),className:"p-1.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white",children:n.jsx(yi,{className:"w-4 h-4"})}),n.jsx("button",{onClick:()=>oe(ce),className:"p-1.5 rounded bg-red-500/10 hover:bg-red-500/20 text-red-500",children:n.jsx(ea,{className:"w-4 h-4"})})]})})]})}),f===ce.id&&n.jsxs("tr",{className:"border-t border-bambu-dark-tertiary/50 bg-bambu-dark",children:[n.jsx("td",{colSpan:2}),n.jsx("td",{className:"px-3 py-2",colSpan:2,children:n.jsx("input",{type:"text",className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm font-mono focus:border-bambu-green focus:outline-none",placeholder:t("inventory.extraColorsPlaceholder"),value:j,onChange:he=>F(he.target.value)})}),n.jsx("td",{className:"px-3 py-2",colSpan:2,children:n.jsx("select",{className:"w-full px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-sm focus:border-bambu-green focus:outline-none",value:k,onChange:he=>M(he.target.value),children:rO.map(he=>n.jsx("option",{value:he.value,children:t(he.labelKey)},he.value||"none"))})}),n.jsx("td",{})]})]},ce.id))})]})})]}),Z&&n.jsx(ya,{title:t("settings.colorCatalog.deleteColor"),message:t("settings.colorCatalog.deleteConfirm",{name:`${Z.manufacturer} - ${Z.color_name}`}),confirmText:t("common.delete"),variant:"danger",onConfirm:re,onCancel:()=>oe(null)}),X&&n.jsx(ya,{title:t("settings.colorCatalog.deleteSelected"),message:t("settings.colorCatalog.bulkDeleteConfirm",{count:B.size}),confirmText:t("common.delete"),variant:"danger",onConfirm:ie,onCancel:()=>ee(!1)}),fe&&n.jsx(ya,{title:t("settings.colorCatalog.resetCatalog"),message:t("settings.colorCatalog.resetConfirm"),confirmText:t("common.reset"),variant:"danger",onConfirm:U,onCancel:()=>me(!1)})]})}function Zrt({link:t,onClose:e}){const{t:a}=vt(),r=ta(),i=!!t,s=y.useRef(null),[o,l]=y.useState(t?.name||""),[c,d]=y.useState(t?.url||""),[u,m]=y.useState(t?.icon||"link"),[p,f]=y.useState(t?.open_in_new_tab||!1),[g,w]=y.useState(!!t?.custom_icon),[b,x]=y.useState(t?.custom_icon?ne.getExternalLinkIconUrl(t.id):null),[S,N]=y.useState(null),[C,P]=y.useState(null);y.useEffect(()=>{const B=R=>{R.key==="Escape"&&e()};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[e]);const T=lt({mutationFn:async B=>{const R=await ne.createExternalLink(B);return S?await ne.uploadExternalLinkIcon(R.id,S):R},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:B=>{P(B.message)}}),j=lt({mutationFn:async B=>{let R=await ne.updateExternalLink(t.id,B);return S?R=await ne.uploadExternalLinkIcon(t.id,S):!g&&t?.custom_icon&&(R=await ne.deleteExternalLinkIcon(t.id)),R},onSuccess:()=>{r.invalidateQueries({queryKey:["external-links"]}),e()},onError:B=>{P(B.message)}}),F=B=>{const R=B.target.files?.[0];if(R){if(!["image/png","image/jpeg","image/gif","image/svg+xml","image/webp","image/x-icon"].includes(R.type)){P("Please select a valid image file (PNG, JPG, GIF, SVG, WebP, or ICO)");return}if(R.size>1024*1024){P("Image file must be less than 1MB");return}N(R),w(!0);const ee=new FileReader;ee.onload=Q=>{x(Q.target?.result)},ee.readAsDataURL(R)}},k=()=>{N(null),x(null),w(!1),s.current&&(s.current.value="")},M=B=>{if(B.preventDefault(),P(null),!o.trim()){P("Name is required");return}if(!c.trim()){P("URL is required");return}if(!c.startsWith("http://")&&!c.startsWith("https://")){P("URL must start with http:// or https://");return}const R={name:o.trim(),url:c.trim(),icon:u,open_in_new_tab:p};i?j.mutate(R):T.mutate(R)},q=T.isPending||j.isPending,I=DT(u);return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:e,children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-md",onClick:B=>B.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"flex items-center gap-3",children:[n.jsx("div",{className:"p-2 rounded-full bg-bambu-green/20 text-bambu-green",children:g&&b?n.jsx("img",{src:b,alt:"",className:"w-5 h-5 rounded"}):n.jsx(I,{className:"w-5 h-5"})}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:i?"Edit Link":"Add External Link"})]}),n.jsx("button",{onClick:e,className:"text-bambu-gray hover:text-white transition-colors",children:n.jsx($t,{className:"w-5 h-5"})})]}),n.jsxs("form",{onSubmit:M,className:"p-6 space-y-4",children:[C&&n.jsx("div",{className:"p-3 bg-red-500/20 border border-red-500/50 rounded-lg text-sm text-red-400",children:C}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"Name *"}),n.jsx("input",{type:"text",value:o,onChange:B=>l(B.target.value),placeholder:"My Link",maxLength:50,className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:"URL *"}),n.jsx("input",{type:"text",value:c,onChange:B=>d(B.target.value),placeholder:"https://example.com",className:"w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("label",{className:"text-sm text-bambu-gray",children:a("externalLinks.openInNewTab")}),n.jsx("button",{type:"button",onClick:()=>f(!p),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${p?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:n.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${p?"translate-x-6":"translate-x-1"}`})})]}),n.jsxs("div",{className:"space-y-3",children:[n.jsx("label",{className:"block text-sm text-bambu-gray",children:"Icon"}),n.jsxs("div",{className:"p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"flex items-center justify-between mb-2",children:[n.jsx("span",{className:"text-sm text-white",children:"Custom Icon"}),n.jsx("input",{ref:s,type:"file",accept:"image/png,image/jpeg,image/gif,image/svg+xml,image/webp,image/x-icon",className:"hidden",onChange:F}),g&&b?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("img",{src:b,alt:"Custom icon",className:"w-8 h-8 rounded border border-bambu-dark-tertiary"}),n.jsx("button",{type:"button",onClick:k,className:"p-1 text-red-400 hover:text-red-300 transition-colors",title:"Remove custom icon",children:n.jsx(ea,{className:"w-4 h-4"})})]}):n.jsxs(Me,{type:"button",variant:"secondary",size:"sm",onClick:()=>s.current?.click(),children:[n.jsx(Sr,{className:"w-4 h-4"}),"Upload"]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:"PNG, JPG, GIF, SVG, WebP, or ICO. Max 1MB."})]}),!g&&n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-bambu-gray block mb-2",children:"Or choose a preset icon"}),n.jsx(m0e,{value:u,onChange:m})]})]}),n.jsxs("div",{className:"flex gap-3 pt-2",children:[n.jsx(Me,{type:"button",variant:"secondary",onClick:e,className:"flex-1",children:"Cancel"}),n.jsxs(Me,{type:"submit",disabled:q,className:"flex-1",children:[q?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(fs,{className:"w-4 h-4"}),i?"Save":"Add"]})]})]})]})})}function Jrt(){const{t}=vt(),e=ta(),[a,r]=y.useState(!1),[i,s]=y.useState(null),[o,l]=y.useState(null),[c,d]=y.useState(null),{data:u,isLoading:m}=Qe({queryKey:["external-links"],queryFn:ne.getExternalLinks}),p=lt({mutationFn:N=>ne.deleteExternalLink(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),f=lt({mutationFn:N=>ne.reorderExternalLinks(N),onSuccess:()=>{e.invalidateQueries({queryKey:["external-links"]})}}),g=(N,C)=>{d(C),N.dataTransfer.effectAllowed="move"},w=N=>{N.preventDefault(),N.dataTransfer.dropEffect="move"},b=(N,C)=>{if(N.preventDefault(),c===null||c===C||!u)return;const P=u.map(k=>k.id),T=P.indexOf(c),j=P.indexOf(C);if(T===-1||j===-1)return;const F=[...P];F.splice(T,1),F.splice(j,0,c),f.mutate(F),d(null)},x=N=>{l(N)},S=()=>{o&&(p.mutate(o.id),l(null))};return n.jsxs(n.Fragment,{children:[n.jsxs(Tt,{id:"card-sidebar-links",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Eh,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:"Sidebar Links"})]}),n.jsxs(Me,{size:"sm",onClick:()=>r(!0),children:[n.jsx(en,{className:"w-4 h-4"}),"Add Link"]})]})}),n.jsxs(Mt,{children:[n.jsx("p",{className:"text-sm text-bambu-gray mb-4",children:"Add external links to the sidebar navigation. Drag to reorder."}),m?n.jsx("div",{className:"flex justify-center py-8",children:n.jsx(pt,{className:"w-6 h-6 text-bambu-green animate-spin"})}):u&&u.length>0?n.jsx("div",{className:"space-y-2",children:u.map(N=>{const C=DT(N.icon);return n.jsxs("div",{draggable:!0,onDragStart:P=>g(P,N.id),onDragOver:w,onDrop:P=>b(P,N.id),className:`flex items-center gap-3 p-3 rounded-lg bg-bambu-dark border border-bambu-dark-tertiary transition-colors ${c===N.id?"opacity-50":""}`,children:[n.jsx(Mh,{className:"w-6 h-6 md:w-4 md:h-4 text-bambu-gray cursor-grab flex-shrink-0"}),n.jsx("div",{className:"p-2 rounded-lg bg-bambu-dark-tertiary text-bambu-gray",children:n.jsx(C,{className:"w-4 h-4"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-white font-medium truncate",children:N.name}),n.jsx(En,{className:"w-3 h-3 text-bambu-gray flex-shrink-0"})]}),n.jsx("span",{className:"text-sm text-bambu-gray truncate block",children:N.url})]}),n.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[n.jsx("button",{onClick:()=>s(N),className:"p-2 rounded-lg hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors",title:t("common.edit"),children:n.jsx(yi,{className:"w-4 h-4"})}),n.jsx("button",{onClick:()=>x(N),disabled:p.isPending,className:"p-2 rounded-lg hover:bg-red-500/20 text-bambu-gray hover:text-red-400 transition-colors disabled:opacity-50",title:t("externalLinks.deleteLink"),children:n.jsx(ea,{className:"w-4 h-4"})})]})]},N.id)})}):n.jsxs("div",{className:"text-center py-8 text-bambu-gray",children:[n.jsx(Eh,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),n.jsx("p",{children:t("externalLinks.noLinksConfigured")}),n.jsx("p",{className:"text-sm",children:'Click "Add Link" to add one'})]})]})]}),(a||i)&&n.jsx(Zrt,{link:i,onClose:()=>{r(!1),s(null)}}),o&&n.jsx(ya,{title:"Delete Link",message:`Are you sure you want to delete "${o.name}"? This action cannot be undone.`,confirmText:"Delete",cancelText:"Cancel",variant:"danger",onConfirm:S,onCancel:()=>l(null)})]})}async function ade(t){if(navigator.clipboard&&window.isSecureContext)try{return await navigator.clipboard.writeText(t),!0}catch{}const e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e);try{return e.select(),document.execCommand("copy")}catch{return!1}finally{e.parentNode&&e.parentNode.removeChild(e)}}function eit(t,e,a="text/plain"){const r=new Blob([t],{type:a}),i=URL.createObjectURL(r),s=document.createElement("a");s.href=i,s.download=e,document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(i)}function tit({status:t}){return t==="pass"?n.jsx(no,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}):t==="fail"?n.jsx(Mn,{className:"w-5 h-5 text-red-400 flex-shrink-0"}):t==="warn"?n.jsx(ba,{className:"w-5 h-5 text-amber-400 flex-shrink-0"}):n.jsx(AO,{className:"w-5 h-5 text-bambu-gray flex-shrink-0"})}function ait({vpId:t,vpName:e,onClose:a}){const{t:r}=vt(),i=lt({mutationFn:()=>yg.diagnose(t)});y.useEffect(()=>{i.mutate()},[]),y.useEffect(()=>{const c=d=>{d.key==="Escape"&&a()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[a]);const s=i.data,o=s?.overall==="ok"?"bg-bambu-green/10 border-bambu-green/30 text-bambu-green":s?.overall==="warnings"?"bg-amber-500/10 border-amber-500/30 text-amber-300":"bg-red-500/10 border-red-500/30 text-red-300",l=c=>{const d=r(`vpDiagnostic.check.${c.id}.${c.status}`,{...c.params,defaultValue:""});return n.jsxs("li",{className:`flex items-start gap-3 bg-bambu-dark rounded-lg px-4 py-2.5 ${c.status==="skip"?"opacity-60":""}`,children:[n.jsx("div",{className:"mt-0.5",children:n.jsx(tit,{status:c.status})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("div",{className:"text-sm text-white",children:r(`vpDiagnostic.check.${c.id}.title`,c.params)}),d&&n.jsx("div",{className:"text-xs text-bambu-gray mt-0.5",children:d})]})]},c.id)};return n.jsx("div",{className:"fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4",onClick:a,children:n.jsxs("div",{className:"bg-bambu-dark-secondary rounded-xl border border-bambu-dark-tertiary w-full max-w-lg flex flex-col max-h-[85vh]",onClick:c=>c.stopPropagation(),children:[n.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(Dl,{className:"w-5 h-5 text-bambu-green flex-shrink-0"}),n.jsx("h2",{className:"text-lg font-semibold text-white truncate",children:r("vpDiagnostic.title",{name:e})})]}),n.jsx("button",{onClick:a,className:"text-bambu-gray hover:text-white transition-colors",title:r("common.close"),children:n.jsx($t,{className:"w-5 h-5"})})]}),n.jsxs("div",{className:"p-6 space-y-4 overflow-y-auto",children:[i.isPending&&n.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),n.jsx("span",{children:r("vpDiagnostic.running")})]}),i.isError&&n.jsx("div",{className:"rounded-lg bg-red-500/10 border border-red-500/30 px-4 py-3 text-sm text-red-300",children:r("vpDiagnostic.runFailed",{error:i.error.message})}),s&&n.jsxs("div",{className:"space-y-4",children:[n.jsx("ol",{className:"space-y-2",children:s.checks.map(l)}),n.jsx("div",{className:`rounded-lg border px-4 py-3 text-sm ${o}`,children:r(`vpDiagnostic.overall.${s.overall}`)})]})]}),n.jsxs("div",{className:"px-6 py-4 border-t border-bambu-dark-tertiary flex justify-end gap-2",children:[n.jsx("button",{onClick:()=>i.mutate(),disabled:i.isPending,className:"px-4 py-2 bg-bambu-dark hover:bg-bambu-dark-tertiary disabled:opacity-50 text-white text-sm rounded-lg transition-colors",children:r("vpDiagnostic.retry")}),n.jsx("button",{onClick:a,className:"px-4 py-2 bg-bambu-green hover:bg-bambu-green/90 text-white text-sm rounded-lg transition-colors",children:r("common.close")})]})]})})}const b3={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function nit({printer:t,models:e}){const{t:a}=vt(),r=ta(),{showToast:i}=ra(),[s,o]=y.useState(!0),[l,c]=y.useState(t.enabled),[d,u]=y.useState(t.name),[m,p]=y.useState(""),[f,g]=y.useState(t.mode==="queue"?"review":t.mode),[w,b]=y.useState(t.target_printer_id),[x,S]=y.useState(t.bind_ip||""),[N,C]=y.useState(t.remote_interface_ip||""),[P,T]=y.useState(t.model||""),[j,F]=y.useState(t.auto_dispatch??!0),[k,M]=y.useState(t.queue_force_color_match??!1),[q,I]=y.useState(t.tailscale_disabled??!0),[B,R]=y.useState(!1),[X,ee]=y.useState(null),[Q,le]=y.useState(!1),[de,ue]=y.useState(!1),[Z,oe]=y.useState(!1),{data:fe}=Qe({queryKey:["tailscale-status"],queryFn:yg.getTailscaleStatus,enabled:!q,staleTime:6e4}),me=fe?.available?fe.fqdn:"",be=fe?.available?fe.tailscale_ips?.[0]??"":"",H=async ce=>{ce.stopPropagation();const he=me;if(!he)return;await ade(he)?(oe(!0),i(a("printers.copied")),setTimeout(()=>oe(!1),2e3)):i(a("virtualPrinter.toast.copyFailed"),"error")};y.useEffect(()=>{X||(c(t.enabled),g(t.mode==="queue"?"review":t.mode),u(t.name),b(t.target_printer_id),S(t.bind_ip||""),C(t.remote_interface_ip||""),T(t.model||""),F(t.auto_dispatch??!0),M(t.queue_force_color_match??!1),I(t.tailscale_disabled??!0))},[t,X]);const{data:J}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),{data:A}=Qe({queryKey:["network-interfaces"],queryFn:()=>ne.getNetworkInterfaces().then(ce=>ce.interfaces)}),E=lt({mutationFn:ce=>yg.update(t.id,ce),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(a("virtualPrinter.toast.updated")),ee(null)},onError:ce=>{i(ce.message||a("virtualPrinter.toast.failedToUpdate"),"error"),c(t.enabled),g(t.mode==="queue"?"review":t.mode),b(t.target_printer_id),S(t.bind_ip||""),I(t.tailscale_disabled??!0),ee(null)}}),z=lt({mutationFn:()=>yg.remove(t.id),onSuccess:()=>{r.invalidateQueries({queryKey:["virtual-printers"]}),i(a("virtualPrinter.toast.deleted")),le(!1)},onError:ce=>{i(ce.message||a("virtualPrinter.toast.failedToDelete"),"error"),le(!1)}}),W=ce=>{ce.stopPropagation();const he=!l;if(he){if(!x){i(a("virtualPrinter.toast.bindIpRequired"),"error");return}if(f==="proxy"){if(!w){i(a("virtualPrinter.toast.targetPrinterRequired"),"error");return}}else if(!m&&!t.access_code_set){i(a("virtualPrinter.toast.accessCodeRequired"),"error");return}}c(he),ee("toggle"),E.mutate({enabled:he})},O=()=>{d.trim()&&(ee("name"),E.mutate({name:d.trim()}))},re=()=>{if(!m){i(a("virtualPrinter.toast.accessCodeEmpty"),"error");return}if(m.length!==8){i(a("virtualPrinter.toast.accessCodeLength"),"error");return}ee("accessCode"),E.mutate({access_code:m}),p("")},U=ce=>{g(ce),ee("mode"),E.mutate({mode:ce})},V=ce=>{T(ce),ee("model"),E.mutate({model:ce})},K=ce=>{b(ce),ee("targetPrinter"),E.mutate({target_printer_id:ce})},Y=ce=>{C(ce),ee("remoteInterface"),E.mutate({remote_interface_ip:ce})},ie=t.status?.running||!1,se=a(`virtualPrinter.mode.${b3[f]||"archive"}`),pe=J?.find(ce=>ce.id===w)?.name;return n.jsxs(n.Fragment,{children:[n.jsxs(Tt,{children:[n.jsxs("div",{className:"px-4 py-3 flex items-center gap-3 cursor-pointer select-none",onClick:()=>o(!s),children:[n.jsx("button",{className:"text-bambu-gray flex-shrink-0",children:s?n.jsx(Da,{className:"w-4 h-4"}):n.jsx(Hr,{className:"w-4 h-4"})}),n.jsx("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${ie?"bg-green-400 animate-pulse":"bg-gray-500"}`}),n.jsx("span",{className:"text-white font-medium truncate",children:t.name}),n.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:se}),t.model_name&&n.jsx("span",{className:"text-xs text-bambu-gray flex-shrink-0",children:t.model_name}),pe&&n.jsxs("span",{className:"text-xs text-bambu-gray flex-shrink-0 truncate",children:[f==="proxy"&&n.jsx(X3,{className:"w-3 h-3 inline mr-1"}),pe]}),x&&n.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:x}),N&&n.jsx("span",{className:"text-[10px] text-bambu-gray flex-shrink-0 font-mono",children:N}),n.jsx("div",{className:"ml-auto flex items-center gap-2 flex-shrink-0",onClick:ce=>ce.stopPropagation(),children:n.jsx("button",{onClick:W,disabled:X==="toggle",className:`relative w-10 h-5 rounded-full transition-colors ${l?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${X==="toggle"?"opacity-50":""}`,children:n.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${l?"translate-x-5":""}`})})})]}),s&&n.jsxs(Mt,{className:"pt-0 space-y-4",children:[n.jsx("div",{className:"border-t border-bambu-dark-tertiary"}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("input",{type:"text",value:d,onChange:ce=>u(ce.target.value),onBlur:O,onKeyDown:ce=>ce.key==="Enter"&&O(),className:"flex-1 text-sm text-white bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 focus:border-bambu-green focus:outline-none"}),n.jsx("button",{onClick:()=>ue(!0),className:"p-1.5 text-bambu-gray hover:text-bambu-green transition-colors flex-shrink-0",title:a("vpDiagnostic.runButton"),children:n.jsx(Dl,{className:"w-4 h-4"})}),n.jsx("button",{onClick:()=>le(!0),className:"p-1.5 text-bambu-gray hover:text-red-400 transition-colors flex-shrink-0",title:a("common.delete"),children:n.jsx(ea,{className:"w-4 h-4"})})]}),n.jsxs("div",{className:"flex items-center gap-2 -mt-2",children:[me&&n.jsxs("span",{className:"flex items-center gap-1 text-green-400/70 min-w-0",children:[n.jsx(wy,{className:"w-3.5 h-3.5 flex-shrink-0"}),n.jsx("span",{className:"font-mono text-xs truncate",children:be?`${be} (${me})`:me}),n.jsx("button",{onClick:H,className:"p-0.5 rounded hover:bg-bambu-dark-tertiary text-bambu-gray hover:text-white transition-colors flex-shrink-0",title:a(Z?"printers.copied":"printers.copyToClipboard"),children:Z?n.jsx(_n,{className:"w-3.5 h-3.5 text-bambu-green"}):n.jsx(xi,{className:"w-3.5 h-3.5"})})]}),n.jsx("span",{className:"text-xs text-bambu-gray font-mono ml-auto flex-shrink-0",children:t.serial})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-white text-sm font-medium mb-2",children:a("virtualPrinter.mode.title")}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(ce=>n.jsxs("button",{onClick:()=>U(ce),disabled:X==="mode",className:`p-2 rounded-lg border text-left transition-colors ${f===ce?ce==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[ce==="proxy"&&n.jsx(X3,{className:"w-3 h-3"}),a(`virtualPrinter.mode.${b3[ce]}`)]}),n.jsx("div",{className:"text-[10px] text-bambu-gray",children:a(`virtualPrinter.mode.${b3[ce]}Desc`)})]},ce))})]}),f==="print_queue"&&n.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-white text-sm font-medium",children:a("virtualPrinter.autoDispatch.title")}),n.jsx("div",{className:"text-[10px] text-bambu-gray",children:a("virtualPrinter.autoDispatch.description")})]}),n.jsx("button",{onClick:()=>{const ce=!j;F(ce),ee("autoDispatch"),E.mutate({auto_dispatch:ce})},disabled:X==="autoDispatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${j?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${X==="autoDispatch"?"opacity-50":""}`,children:n.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${j?"translate-x-5":""}`})})]})}),f==="print_queue"&&n.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-white text-sm font-medium",children:a("virtualPrinter.queueForceColorMatch.title")}),n.jsx("div",{className:"text-[10px] text-bambu-gray",children:a("virtualPrinter.queueForceColorMatch.description")})]}),n.jsx("button",{onClick:()=>{const ce=!k;M(ce),ee("queueForceColorMatch"),E.mutate({queue_force_color_match:ce})},disabled:X==="queueForceColorMatch",className:`relative w-10 h-5 rounded-full transition-colors flex-shrink-0 ${k?"bg-bambu-green":"bg-bambu-dark-tertiary"} ${X==="queueForceColorMatch"?"opacity-50":""}`,children:n.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${k?"translate-x-5":""}`})})]})}),n.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-white text-sm font-medium",children:a("virtualPrinter.tailscaleDisabled.title")}),n.jsx("div",{className:"text-[10px] text-bambu-gray",children:a("virtualPrinter.tailscaleDisabled.description")})]}),n.jsx("button",{onClick:()=>{const ce=!q;I(ce),ee("tailscaleDisabled"),E.mutate({tailscale_disabled:ce})},disabled:X==="tailscaleDisabled",className:`relative w-10 h-5 rounded-full transition-colors shrink-0 ${q?"bg-bambu-dark-tertiary":"bg-bambu-green"} ${X==="tailscaleDisabled"?"opacity-50":""}`,children:n.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 bg-white rounded-full transition-transform ${q?"":"translate-x-5"}`})})]})}),f!=="proxy"&&n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsx("div",{className:"text-white text-sm font-medium mb-1",children:a("virtualPrinter.model.title")}),n.jsx("p",{className:"text-xs text-bambu-gray mb-2",children:a("virtualPrinter.model.description")}),n.jsxs("div",{className:"relative",children:[n.jsx("select",{value:P,onChange:ce=>V(ce.target.value),disabled:X==="model",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:Object.entries(e).map(([ce,he])=>n.jsxs("option",{value:ce,children:[he," (",ce,")"]},ce))}),n.jsx(Da,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),f==="proxy"&&n.jsx("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:n.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-blue-500/10 border border-blue-500/30",children:[n.jsx(Ei,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("virtualPrinter.proxy.accessCodeHint")})]})}),f!=="proxy"&&n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[n.jsx("div",{className:"text-white text-sm font-medium",children:a("virtualPrinter.accessCode.title")}),t.access_code_set?n.jsxs("span",{className:"flex items-center gap-1 text-xs text-green-400",children:[n.jsx(_n,{className:"w-3 h-3"}),a("virtualPrinter.accessCode.isSet")]}):n.jsxs("span",{className:"flex items-center gap-1 text-xs text-yellow-400",children:[n.jsx(ba,{className:"w-3 h-3"}),a("virtualPrinter.accessCode.notSet")]})]}),n.jsxs("div",{className:"flex gap-2",children:[n.jsxs("div",{className:"relative flex-1",children:[n.jsx("input",{type:B?"text":"password",value:m,onChange:ce=>p(ce.target.value),placeholder:t.access_code_set?a("virtualPrinter.accessCode.placeholderChange"):a("virtualPrinter.accessCode.placeholder"),maxLength:8,className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm placeholder-bambu-gray pr-10 font-mono"}),n.jsx("button",{onClick:()=>R(!B),className:"absolute right-2 top-1/2 -translate-y-1/2 text-bambu-gray hover:text-white",children:B?n.jsx(db,{className:"w-4 h-4"}):n.jsx(Ml,{className:"w-4 h-4"})})]}),n.jsx(Me,{onClick:re,disabled:!m||X==="accessCode",variant:"primary",children:X==="accessCode"?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):a("common.save")})]}),m&&n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:n.jsx("span",{className:m.length===8?"text-green-400":"text-yellow-400",children:a("virtualPrinter.accessCode.charCount",{count:m.length})})})]}),n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsx("div",{className:"text-white text-sm font-medium mb-2",children:a("virtualPrinter.targetPrinter.title")}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{value:w??"",onChange:ce=>{const he=parseInt(ce.target.value,10);isNaN(he)||K(he)},disabled:X==="targetPrinter",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[n.jsx("option",{value:"",children:a("virtualPrinter.targetPrinter.placeholder")}),J?.map(ce=>n.jsxs("option",{value:ce.id,children:[ce.name," (",ce.ip_address,")"]},ce.id))]}),n.jsx(Da,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsx("div",{className:"text-white text-sm font-medium mb-1",children:a("virtualPrinter.bindIp.title")}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{value:x,onChange:ce=>{S(ce.target.value),ee("bindIp"),E.mutate({bind_ip:ce.target.value})},disabled:X==="bindIp",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[n.jsx("option",{value:"",children:a("virtualPrinter.bindIp.placeholder")}),A?.map(ce=>n.jsxs("option",{value:ce.ip,children:[ce.name," (",ce.ip,")",ce.is_alias?" [alias]":""," - ",ce.subnet]},ce.ip))]}),n.jsx(Da,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("virtualPrinter.bindIp.hint")})]}),n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("div",{className:"text-white text-sm font-medium",children:a("virtualPrinter.remoteInterface.title")}),N?n.jsx("span",{className:"flex items-center gap-1 text-xs text-green-400",children:n.jsx(_n,{className:"w-3 h-3"})}):n.jsx("span",{className:"flex items-center gap-1 text-xs text-bambu-gray",title:a("virtualPrinter.remoteInterface.optional"),children:n.jsx(Ei,{className:"w-3 h-3"})})]}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{value:N,onChange:ce=>Y(ce.target.value),disabled:X==="remoteInterface",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-white text-sm appearance-none cursor-pointer disabled:opacity-50 pr-10",children:[n.jsx("option",{value:"",children:a("virtualPrinter.remoteInterface.placeholder")}),A?.map(ce=>n.jsxs("option",{value:ce.ip,children:[ce.name," (",ce.ip,") - ",ce.subnet]},ce.ip))]}),n.jsx(Da,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]})]})]}),Q&&n.jsx(ya,{title:a("virtualPrinter.deleteConfirm.title"),message:a("virtualPrinter.deleteConfirm.message",{name:t.name}),variant:"danger",confirmText:a("common.delete"),isLoading:z.isPending,onConfirm:()=>z.mutate(),onCancel:()=>le(!1)}),de&&n.jsx(ait,{vpId:t.id,vpName:t.name,onClose:()=>ue(!1)})]})}const _X={immediate:"archive",review:"review",print_queue:"queue",proxy:"proxy"};function rit({onClose:t}){const{t:e}=vt(),a=ta(),{showToast:r}=ra(),[i,s]=y.useState(""),[o,l]=y.useState("immediate"),[c,d]=y.useState(null),{data:u}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),m=lt({mutationFn:()=>yg.create({name:i.trim()||"Bambuddy",mode:o,target_printer_id:o==="proxy"?c??void 0:void 0}),onSuccess:()=>{a.invalidateQueries({queryKey:["virtual-printers"]}),r(e("virtualPrinter.toast.created")),t()},onError:p=>{r(p.message||e("virtualPrinter.toast.failedToCreate"),"error")}});return n.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",onClick:t,children:n.jsx(Tt,{className:"w-full max-w-md",onClick:p=>p.stopPropagation(),children:n.jsxs(Mt,{className:"p-6 space-y-4",children:[n.jsx("h3",{className:"text-lg font-semibold text-white",children:e("virtualPrinter.addDialog.title")}),n.jsxs("div",{children:[n.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.addDialog.name")}),n.jsx("input",{type:"text",value:i,onChange:p=>s(p.target.value),placeholder:"Bambuddy",className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm placeholder-bambu-gray",autoFocus:!0})]}),n.jsxs("div",{children:[n.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.mode.title")}),n.jsx("div",{className:"grid grid-cols-2 gap-2",children:["immediate","review","print_queue","proxy"].map(p=>n.jsxs("button",{onClick:()=>l(p),className:`p-2 rounded-lg border text-left transition-colors ${o===p?p==="proxy"?"border-blue-500 bg-blue-500/10":"border-bambu-green bg-bambu-green/10":"border-bambu-dark-tertiary hover:border-bambu-gray"}`,children:[n.jsxs("div",{className:"flex items-center gap-1.5 text-white text-xs font-medium",children:[p==="proxy"&&n.jsx(X3,{className:"w-3 h-3"}),e(`virtualPrinter.mode.${_X[p]}`)]}),n.jsx("div",{className:"text-[10px] text-bambu-gray",children:e(`virtualPrinter.mode.${_X[p]}Desc`)})]},p))})]}),o==="proxy"&&n.jsxs("div",{children:[n.jsx("label",{className:"text-sm text-white font-medium block mb-1",children:e("virtualPrinter.targetPrinter.title")}),n.jsxs("div",{className:"relative",children:[n.jsxs("select",{value:c??"",onChange:p=>{const f=parseInt(p.target.value,10);d(isNaN(f)?null:f)},className:"w-full bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-md px-3 py-2 text-white text-sm appearance-none cursor-pointer pr-10",children:[n.jsx("option",{value:"",children:e("virtualPrinter.targetPrinter.placeholder")}),u?.map(p=>n.jsxs("option",{value:p.id,children:[p.name," (",p.ip_address,")"]},p.id))]}),n.jsx(Da,{className:"absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-bambu-gray pointer-events-none"})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:e("virtualPrinter.addDialog.hint")}),n.jsxs("div",{className:"flex gap-3 pt-2",children:[n.jsx(Me,{variant:"secondary",onClick:t,className:"flex-1",disabled:m.isPending,children:e("common.cancel")}),n.jsx(Me,{variant:"primary",onClick:()=>m.mutate(),className:"flex-1",disabled:m.isPending,children:m.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):e("virtualPrinter.addDialog.create")})]})]})})})}function iit(){const{t}=vt(),e=ta(),{showToast:a}=ra(),[r,i]=y.useState(!1),{data:s,isLoading:o}=Qe({queryKey:["virtual-printers"],queryFn:yg.list,refetchInterval:1e4}),{data:l}=Qe({queryKey:["virtual-printer-settings"],queryFn:iL.getSettings}),c=lt({mutationFn:x=>iL.updateSettings({archive_name_source:x}),onSuccess:()=>{e.invalidateQueries({queryKey:["virtual-printer-settings"]}),a(t("virtualPrinter.toast.updated"))},onError:x=>{a(x.message||t("virtualPrinter.toast.failedToUpdate"),"error")}}),d=l?.archive_name_source==="filename",{data:u}=Qe({queryKey:["vp-ca-certificate"],queryFn:yg.getCaCertificate,staleTime:1/0}),[m,p]=y.useState(!1),f=async()=>{if(!u)return;await ade(u.pem)?(p(!0),a(t("virtualPrinter.caCert.copied")),setTimeout(()=>p(!1),2e3)):a(t("virtualPrinter.toast.copyFailed"),"error")},g=()=>{u&&eit(u.pem,"bambuddy-virtual-printer-ca.crt","application/x-pem-file")};if(o)return n.jsx(Tt,{children:n.jsx(Mt,{className:"py-8 flex justify-center",children:n.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const w=s?.printers||[],b=s?.models||{};return n.jsxs("div",{className:"space-y-4",children:[n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 items-stretch",children:[n.jsx(Tt,{className:"border-l-4 border-l-yellow-500",children:n.jsx(Mt,{className:"py-3 px-4",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(ba,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),n.jsxs("div",{className:"text-xs",children:[n.jsx("p",{className:"text-white font-medium",children:t("virtualPrinter.setupRequired.title")}),n.jsx("p",{className:"text-bambu-gray mt-1",children:t("virtualPrinter.setupRequired.description")}),n.jsxs("a",{href:"https://wiki.bambuddy.cool/features/virtual-printer/",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 mt-2 px-3 py-1.5 bg-yellow-500/20 border border-yellow-500/50 rounded text-yellow-400 hover:bg-yellow-500/30 transition-colors text-xs",children:[n.jsx(En,{className:"w-3 h-3"}),t("virtualPrinter.setupRequired.readGuide")]})]})]})})}),n.jsx(Tt,{className:"lg:col-span-2",children:n.jsx(Mt,{className:"py-3 px-4",children:n.jsxs("div",{className:"flex items-start gap-2",children:[n.jsx(Ei,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{className:"text-xs text-bambu-gray",children:[n.jsx("p",{className:"text-white font-medium mb-1",children:t("virtualPrinter.howItWorks.title")}),n.jsxs("ul",{className:"space-y-1 list-disc list-inside",children:[n.jsx("li",{children:t("virtualPrinter.howItWorks.step1")}),n.jsx("li",{children:t("virtualPrinter.howItWorks.step2")}),n.jsx("li",{children:t("virtualPrinter.howItWorks.step3")})]})]})]})})})]}),n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4 items-stretch",children:[n.jsx(Tt,{children:n.jsx(Mt,{className:"py-3 px-4",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(wy,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-1"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("p",{className:"text-sm text-white font-medium",children:t("virtualPrinter.caCert.title")}),n.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[n.jsxs("button",{onClick:f,disabled:!u,className:"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs rounded bg-bambu-dark-secondary border border-bambu-dark-tertiary text-white hover:border-bambu-gray disabled:opacity-50 transition-colors",children:[m?n.jsx(_n,{className:"w-3.5 h-3.5 text-bambu-green"}):n.jsx(xi,{className:"w-3.5 h-3.5"}),t(m?"virtualPrinter.caCert.copied":"virtualPrinter.caCert.copy")]}),n.jsxs("button",{onClick:g,disabled:!u,className:"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs rounded bg-bambu-dark-secondary border border-bambu-dark-tertiary text-white hover:border-bambu-gray disabled:opacity-50 transition-colors",children:[n.jsx(Bn,{className:"w-3.5 h-3.5"}),t("virtualPrinter.caCert.download")]})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("virtualPrinter.caCert.description")}),u&&n.jsxs("p",{className:"text-[10px] text-bambu-gray font-mono mt-1 truncate",title:u.fingerprint_sha256,children:[t("virtualPrinter.caCert.fingerprint"),": ",u.fingerprint_sha256]})]})]})})}),n.jsx(Tt,{children:n.jsx(Mt,{className:"py-3 px-4",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(Bs,{className:"w-4 h-4 text-bambu-green flex-shrink-0 mt-1"}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center justify-between gap-3",children:[n.jsx("p",{className:"text-sm text-white font-medium",children:t("virtualPrinter.archiveNameSource.title")}),n.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[n.jsx("span",{className:`text-xs ${d?"text-bambu-gray":"text-white"}`,children:t("virtualPrinter.archiveNameSource.metadata")}),n.jsx(ja,{checked:d,onChange:x=>c.mutate(x?"filename":"metadata"),disabled:c.isPending}),n.jsx("span",{className:`text-xs ${d?"text-white":"text-bambu-gray"}`,children:t("virtualPrinter.archiveNameSource.filename")})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("virtualPrinter.archiveNameSource.description")})]})]})})})]}),n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(bn,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("virtualPrinter.list.title")}),n.jsxs("span",{className:"text-sm text-bambu-gray",children:["(",w.length,")"]})]}),n.jsxs(Me,{variant:"primary",onClick:()=>i(!0),children:[n.jsx(en,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.add")]})]}),w.length===0?n.jsx(Tt,{children:n.jsxs(Mt,{className:"py-8 text-center",children:[n.jsx(bn,{className:"w-12 h-12 text-bambu-gray mx-auto mb-3"}),n.jsx("p",{className:"text-bambu-gray mb-4",children:t("virtualPrinter.list.empty")}),n.jsxs(Me,{variant:"primary",onClick:()=>i(!0),children:[n.jsx(en,{className:"w-4 h-4 mr-1"}),t("virtualPrinter.list.addFirst")]})]})}):n.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 items-start",children:w.map(x=>n.jsx(nit,{printer:x,models:b},x.id))}),r&&n.jsx(rit,{onClose:()=>i(!1)})]})}function NX(t){if(t<60)return`${t}s`;const e=Math.floor(t/60);if(e<60)return`${e}m`;const a=Math.floor(e/60),r=e%60;if(a<24)return r?`${a}h ${r}m`:`${a}h`;const i=Math.floor(a/24),s=a%24;return s?`${i}d ${s}h`:`${i}d`}function CX(t){return t==null?"—":t>=1024?`${(t/1024).toFixed(1)} GB`:`${Math.round(t)} MB`}function sit({device:t,onUnregister:e,isDeleting:a}){const{t:r}=vt(),{showToast:i}=ra(),s=t.system_stats,o=s?.memory,l=s?.disk,c=t.online,[d,u]=y.useState(null),[m,p]=y.useState(null),f=async x=>{p(x);try{x==="update"?await Xn.triggerUpdate(t.device_id):await Xn.systemCommand(t.device_id,x),i(r("settings.spoolbuddy.commandQueued"),"success")}catch(S){const N=S instanceof Error?S.message:r("settings.spoolbuddy.commandError");i(N,"error")}finally{p(null),u(null)}},g=[{key:"update",label:r("settings.spoolbuddy.update"),icon:Bn},{key:"restart_browser",label:r("settings.spoolbuddy.restartBrowser"),icon:DO},{key:"restart_daemon",label:r("settings.spoolbuddy.restartDaemon"),icon:Xa},{key:"reboot",label:r("settings.spoolbuddy.reboot"),icon:Iw},{key:"shutdown",label:r("settings.spoolbuddy.shutdown"),icon:Su,variant:"danger"}],w={update:r("settings.spoolbuddy.updateConfirmTitle"),restart_browser:r("settings.spoolbuddy.restartBrowserConfirmTitle"),restart_daemon:r("settings.spoolbuddy.restartDaemonConfirmTitle"),reboot:r("settings.spoolbuddy.rebootConfirmTitle"),shutdown:r("settings.spoolbuddy.shutdownConfirmTitle")},b={update:r("settings.spoolbuddy.updateConfirmBody",{hostname:t.hostname}),restart_browser:r("settings.spoolbuddy.restartBrowserConfirmBody",{hostname:t.hostname}),restart_daemon:r("settings.spoolbuddy.restartDaemonConfirmBody",{hostname:t.hostname}),reboot:r("settings.spoolbuddy.rebootConfirmBody",{hostname:t.hostname}),shutdown:r("settings.spoolbuddy.shutdownConfirmBody",{hostname:t.hostname})};return n.jsxs(Tt,{children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("h3",{className:"text-base font-semibold text-white truncate",children:t.hostname}),n.jsxs("span",{className:`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium ${c?"bg-green-500/15 text-green-400 border border-green-500/40":"bg-gray-500/15 text-gray-400 border border-gray-500/40"}`,children:[c?n.jsx(Dh,{className:"w-3 h-3"}):n.jsx(pu,{className:"w-3 h-3"}),r(c?"settings.spoolbuddy.online":"settings.spoolbuddy.offline")]})]}),n.jsx("p",{className:"text-xs text-bambu-gray font-mono mt-1 truncate",children:t.device_id})]}),n.jsxs(Me,{variant:"danger",size:"sm",onClick:()=>e(t),disabled:a,"aria-label":r("settings.spoolbuddy.unregister"),children:[n.jsx(ea,{className:"w-3.5 h-3.5"}),n.jsx("span",{className:"hidden sm:inline",children:r("settings.spoolbuddy.unregister")})]})]})}),n.jsxs(Mt,{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs",children:[n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.ipAddress")}),n.jsx("div",{className:"text-white font-mono",children:t.ip_address})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.firmware")}),n.jsx("div",{className:"text-white",children:t.firmware_version??"—"})]}),n.jsxs("div",{children:[n.jsxs("div",{className:"text-bambu-gray flex items-center gap-1",children:[n.jsx(Za,{className:"w-3 h-3"}),r("settings.spoolbuddy.lastSeen")]}),n.jsx("div",{className:"text-white",children:t.last_seen?Fh(t.last_seen):r("settings.spoolbuddy.never")})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.daemonUptime")}),n.jsx("div",{className:"text-white",children:NX(t.uptime_s)})]})]}),n.jsx("div",{className:"flex flex-wrap gap-2",children:g.map(({key:x,label:S,icon:N,variant:C})=>n.jsxs(Me,{variant:C??"secondary",size:"sm",onClick:()=>u(x),disabled:!c||m!==null,"aria-label":S,children:[m===x?n.jsx(pt,{className:"w-3.5 h-3.5 animate-spin"}):n.jsx(N,{className:"w-3.5 h-3.5"}),n.jsx("span",{children:S})]},x))}),n.jsxs("div",{className:"flex items-center gap-3 text-xs flex-wrap",children:[n.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.nfc_ok?n.jsx(no,{className:"w-3.5 h-3.5 text-green-400"}):n.jsx(Mn,{className:"w-3.5 h-3.5 text-red-400"}),r("settings.spoolbuddy.nfc"),t.nfc_reader_type&&n.jsxs("span",{className:"text-bambu-gray/70",children:["(",t.nfc_reader_type,")"]})]}),n.jsxs("span",{className:"flex items-center gap-1 text-bambu-gray",children:[t.scale_ok?n.jsx(no,{className:"w-3.5 h-3.5 text-green-400"}):n.jsx(Mn,{className:"w-3.5 h-3.5 text-red-400"}),r("settings.spoolbuddy.scale")]})]}),s&&n.jsxs("div",{className:"pt-2 border-t border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 text-xs",children:[s.cpu_temp_c!==void 0&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(zS,{className:"w-3.5 h-3.5 text-bambu-gray"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.cpuTemp")}),n.jsxs("div",{className:"text-white",children:[s.cpu_temp_c.toFixed(1),"°C"]})]})]}),s.load_avg&&s.load_avg.length>0&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Rfe,{className:"w-3.5 h-3.5 text-bambu-gray"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.cpuLoad")}),n.jsxs("div",{className:"text-white",children:[s.load_avg[0].toFixed(2),s.cpu_count?` / ${s.cpu_count} (${Math.round(s.load_avg[0]/s.cpu_count*100)}%)`:""]})]})]}),o&&o.percent!==void 0&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(z0,{className:"w-3.5 h-3.5 text-bambu-gray"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.memory")}),n.jsxs("div",{className:"text-white",children:[o.percent.toFixed(0),"% (",CX(o.used_mb)," / ",CX(o.total_mb),")"]})]})]}),l&&l.percent!==void 0&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(ub,{className:"w-3.5 h-3.5 text-bambu-gray"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.disk")}),n.jsxs("div",{className:"text-white",children:[l.percent.toFixed(0),"% (",l.used_gb?.toFixed(1)," / ",l.total_gb?.toFixed(1)," GB)"]})]})]}),s.system_uptime_s!==void 0&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Za,{className:"w-3.5 h-3.5 text-bambu-gray"}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray",children:r("settings.spoolbuddy.systemUptime")}),n.jsx("div",{className:"text-white",children:NX(s.system_uptime_s)})]})]})]}),s.os&&n.jsx("div",{className:"mt-3 text-xs text-bambu-gray font-mono truncate",children:[s.os.os,s.os.kernel,s.os.arch,s.os.python&&`Python ${s.os.python}`].filter(Boolean).join(" · ")})]})]}),d&&n.jsx(ya,{variant:d==="shutdown"||d==="reboot"?"danger":"default",title:w[d],message:b[d],confirmText:r("settings.spoolbuddy.commandConfirm"),isLoading:m!==null,onConfirm:()=>f(d),onCancel:()=>u(null)})]})}function oit(){const{t}=vt(),e=ta(),{showToast:a}=ra(),[r,i]=y.useState(null),{data:s=[],isLoading:o}=Qe({queryKey:["spoolbuddy-devices"],queryFn:()=>Xn.getDevices(),refetchInterval:15e3}),l=lt({mutationFn:d=>Xn.deleteDevice(d),onSuccess:()=>{e.invalidateQueries({queryKey:["spoolbuddy-devices"]}),a(t("settings.spoolbuddy.unregisterSuccess"),"success"),i(null)},onError:d=>{a(d.message||t("settings.spoolbuddy.unregisterError"),"error")}});if(o)return n.jsx(Tt,{children:n.jsx(Mt,{className:"py-8 flex justify-center",children:n.jsx(pt,{className:"w-6 h-6 animate-spin text-bambu-green"})})});const c=s.length>1;return n.jsxs("div",{className:"space-y-4",children:[n.jsx(Tt,{children:n.jsx(Mt,{className:"py-3 px-4",children:n.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[n.jsx(Ei,{className:"w-4 h-4 text-blue-400 flex-shrink-0 mt-0.5"}),n.jsxs("div",{className:"text-bambu-gray",children:[n.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.infoTitle")}),n.jsx("p",{children:t("settings.spoolbuddy.infoBody")})]})]})})}),c&&n.jsx(Tt,{className:"border-l-4 border-l-yellow-500",children:n.jsx(Mt,{className:"py-3 px-4",children:n.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[n.jsx(ba,{className:"w-4 h-4 text-yellow-500 flex-shrink-0 mt-0.5"}),n.jsxs("div",{className:"text-bambu-gray",children:[n.jsx("p",{className:"text-white font-medium mb-1",children:t("settings.spoolbuddy.duplicatesTitle",{count:s.length})}),n.jsx("p",{children:t("settings.spoolbuddy.duplicatesBody")})]})]})})}),s.length===0?n.jsx(Tt,{children:n.jsx(Mt,{className:"py-8 text-center text-bambu-gray text-sm",children:t("settings.spoolbuddy.empty")})}):n.jsx("div",{className:"space-y-3",children:s.map(d=>n.jsx(sit,{device:d,onUnregister:i,isDeleting:l.isPending&&l.variables===d.device_id},d.id))}),r&&n.jsx(ya,{variant:"danger",title:t("settings.spoolbuddy.confirmTitle"),message:t("settings.spoolbuddy.confirmBody",{hostname:r.hostname,deviceId:r.device_id}),confirmText:t("settings.spoolbuddy.unregister"),isLoading:l.isPending,onConfirm:()=>l.mutate(r.device_id),onCancel:()=>i(null)})]})}function x3(t){if(!t)return"-";const e=Qa(t);return e?e.toLocaleString():"-"}function y3({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"},a={success:n.jsx(fn,{className:"w-3 h-3"}),failed:n.jsx(Mn,{className:"w-3 h-3"}),skipped:n.jsx(ET,{className:"w-3 h-3"}),running:n.jsx(pt,{className:"w-3 h-3 animate-spin"})};return n.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:[a[t],t.charAt(0).toUpperCase()+t.slice(1)]})}const lit={github:"backup.repoUrlPlaceholderGitHub",gitea:"backup.repoUrlPlaceholderGitea",forgejo:"backup.repoUrlPlaceholderForgejo",gitlab:"backup.repoUrlPlaceholderGitLab"},cit={github:"ghp_xxxxxxxxxxxx",gitea:"your_access_token",forgejo:"your_access_token",gitlab:"glpat-xxxxxxxxxxxx"};function PX(t){return JSON.stringify(t)}function dit(t,e){if(!e)return t;const a={};for(const r of Object.keys(t))t[r]!==e[r]&&(a[r]=t[r]);return a}function uit(){const t=ta(),{showToast:e}=ra(),{t:a}=vt(),[r,i]=y.useState(""),[s,o]=y.useState(""),[l,c]=y.useState("main"),[d,u]=y.useState("github"),[m,p]=y.useState(!1),[f,g]=y.useState("daily"),[w,b]=y.useState(!0),[x,S]=y.useState(!0),[N,C]=y.useState(!1),[P,T]=y.useState(!1),[j,F]=y.useState(!1),[k,M]=y.useState(!1),[q,I]=y.useState(!0),[B,R]=y.useState(!1),[X,ee]=y.useState(!1),[Q,le]=y.useState(""),[de,ue]=y.useState(!1),[Z,oe]=y.useState(null),[fe,me]=y.useState(null),be=y.useRef(null),[H,J]=y.useState(null),[A,E]=y.useState(null),[z,W]=y.useState(""),{data:O,refetch:re}=Qe({queryKey:["local-backup-status"],queryFn:ne.getLocalBackupStatus,refetchInterval:gt=>gt.state.data?.is_running?1e3:1e4}),{data:U,refetch:V}=Qe({queryKey:["local-backup-files"],queryFn:ne.getLocalBackups,refetchInterval:3e4});y.useEffect(()=>{O?.path!==void 0&&W(O.path)},[O?.path]);const K=lt({mutationFn:ne.triggerLocalBackup,onSuccess:gt=>{gt.success?e(a("backup.scheduledBackupComplete")):e(gt.message,"error"),re(),V()},onError:()=>e(a("backup.scheduledBackupFailed"),"error")}),Y=lt({mutationFn:gt=>ne.deleteLocalBackup(gt),onSuccess:()=>{V(),J(null)}}),ie=lt({mutationFn:async gt=>(E(null),ee(!0),me(null),le(a("backup.restoring")),ne.restoreLocalBackup(gt)),onSuccess:gt=>{ee(!1),le(""),gt.success?(me({success:!0,message:gt.message}),e(a("backup.backupRestoredRestart"),"success")):(me({success:!1,message:gt.message}),e(gt.message,"error"))},onError:gt=>{ee(!1),le("");const Qt=gt instanceof Error?gt.message:a("backup.failedToRestore");me({success:!1,message:Qt}),e(Qt,"error")}});y.useEffect(()=>{if(B||X){const Qt=Xt=>(Xt.preventDefault(),Xt.returnValue="A backup operation is in progress. Are you sure you want to leave?",Xt.returnValue);return window.addEventListener("beforeunload",Qt),()=>window.removeEventListener("beforeunload",Qt)}},[B,X]);const[se,pe]=y.useState(!1),[ce,he]=y.useState(null),[$,L]=y.useState(null),ae=y.useRef(null),ge=y.useRef(null),xe=y.useRef(null),Se=y.useRef(null),Te=y.useRef(""),[ve,we]=y.useState(!1),ze=y.useMemo(()=>({repository_url:r,branch:l,provider:d,allow_insecure_http:k,schedule_enabled:m,schedule_type:f,backup_kprofiles:w,backup_cloud_profiles:x,backup_settings:N,backup_spools:P,backup_archives:j,enabled:q}),[r,l,d,k,m,f,w,x,N,P,j,q]),De=y.useMemo(()=>PX(ze),[ze]),{data:Le,isLoading:Re}=Qe({queryKey:["github-backup-config"],queryFn:ne.getGitHubBackupConfig}),{data:We}=Qe({queryKey:["github-backup-status"],queryFn:ne.getGitHubBackupStatus,refetchInterval:gt=>gt.state.data?.is_running?500:1e4}),{data:Be}=Qe({queryKey:["github-backup-logs"],queryFn:()=>ne.getGitHubBackupLogs(20)}),{data:ot}=Qe({queryKey:["cloud-status"],queryFn:ne.getCloudStatus}),{data:Ee}=Qe({queryKey:["printers"],queryFn:ne.getPrinters}),it=rf({queries:(Ee??[]).map(gt=>({queryKey:["printerStatus",gt.id],queryFn:()=>ne.getPrinterStatus(gt.id),staleTime:1e4,refetchInterval:3e4}))}),Ne=(Ee??[]).map((gt,Qt)=>({printer:gt,connected:it[Qt]?.data?.connected??!1})),Ze=Ne.length,Ye=Ne.filter(gt=>gt.connected).length,Ae=Ze>0&&Ye===0,Ie=Ye>0&&Ye(xe.current&&clearTimeout(xe.current),Le?(we(!1),Se.current={repository_url:Le.repository_url,branch:Le.branch,provider:Le.provider??"github",allow_insecure_http:Le.allow_insecure_http??!1,schedule_enabled:Le.schedule_enabled,schedule_type:Le.schedule_type,backup_kprofiles:Le.backup_kprofiles,backup_cloud_profiles:Le.backup_cloud_profiles,backup_settings:Le.backup_settings,backup_spools:Le.backup_spools,backup_archives:Le.backup_archives,enabled:Le.enabled},i(Le.repository_url),c(Le.branch),u(Le.provider??"github"),p(Le.schedule_enabled),g(Le.schedule_type),b(Le.backup_kprofiles),S(Le.backup_cloud_profiles),C(Le.backup_settings),T(Le.backup_spools),F(Le.backup_archives),M(Le.allow_insecure_http??!1),I(Le.enabled),o(""),xe.current=setTimeout(()=>{we(!0)},100)):(we(!1),Se.current=null,o("")),()=>{xe.current&&clearTimeout(xe.current)}),[Le]);const et=y.useCallback(async(gt=!1)=>{if(Le)try{gt&&s?(await ne.saveGitHubBackupConfig({...ze,access_token:s}),o(""),L(null),e(a("backup.tokenUpdated")),Te.current=""):(await ne.updateGitHubBackupConfig(dit(ze,Se.current)),L(null),e(a("backup.settingsSaved"))),Se.current=ze,t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]})}catch(Qt){L(Qt.message)}},[Le,s,ze,t,e,a]),Ke=y.useRef(et);y.useEffect(()=>{Ke.current=et},[et]),y.useEffect(()=>{if(!(!ve||!Le)&&!(Se.current&&De===PX(Se.current)))return ae.current&&clearTimeout(ae.current),ae.current=setTimeout(()=>{et(!1)},500),()=>{ae.current&&clearTimeout(ae.current)}},[ve,Le,De,et]),y.useEffect(()=>{if(!(!ve||!Le||!s)&&s!==Te.current)return Te.current=s,ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{Ke.current(!0)},1e3),()=>{ge.current&&clearTimeout(ge.current)}},[ve,s,Le]);const Pe=lt({mutationFn:gt=>ne.saveGitHubBackupConfig(gt),onMutate:()=>{L(null)},onSuccess:()=>{t.invalidateQueries({queryKey:["github-backup-config"]}),t.invalidateQueries({queryKey:["github-backup-status"]}),e(a("backup.githubBackupEnabled")),o(""),we(!0)},onError:gt=>{L(gt.message)}}),at=lt({mutationFn:ne.triggerGitHubBackup,onSuccess:gt=>{t.invalidateQueries({queryKey:["github-backup-status"]}),t.invalidateQueries({queryKey:["github-backup-logs"]}),gt.success?gt.files_changed>0?e(a("backup.backupCompleteFiles",{count:gt.files_changed})):e(a("backup.backupSkippedNoChanges")):e(a("backup.backupFailed2",{message:gt.message}),"error")},onError:gt=>{e(a("backup.backupFailed2",{message:gt.message}),"error")}}),rt=lt({mutationFn:()=>ne.clearGitHubBackupLogs(0),onSuccess:gt=>{t.invalidateQueries({queryKey:["github-backup-logs"]}),e(a("backup.clearedLogs",{count:gt.deleted}))},onError:gt=>{e(a("backup.failedToClearLogs",{message:gt.message}),"error")}}),At=async()=>{pe(!0),he(null);try{let gt;if(s){if(!r){e(a("backup.enterRepoUrl"),"error"),pe(!1);return}gt=await ne.testGitHubConnection(r,s,d)}else if(Le?.has_token)gt=await ne.testGitHubStoredConnection();else{e(a("backup.enterRepoAndToken"),"error"),pe(!1);return}he({success:gt.success,message:gt.message,isPrivate:gt.is_private})}catch(gt){he({success:!1,message:gt.message,isPrivate:null})}finally{pe(!1)}},Bt=()=>{if(!r){e(a("backup.repoRequired"),"error");return}if(!s){e(a("backup.tokenRequired"),"error");return}Pe.mutate({repository_url:r,access_token:s,branch:l,provider:d,allow_insecure_http:k,schedule_enabled:m,schedule_type:f,backup_kprofiles:w,backup_cloud_profiles:x,backup_settings:N,backup_spools:P,backup_archives:j,enabled:q})};return Re?n.jsx("div",{className:"flex items-center justify-center py-12",children:n.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})}):n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[n.jsxs("div",{className:"space-y-6",children:[n.jsxs(Tt,{id:"card-backup-github",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(J3,{className:"w-5 h-5 text-gray-400"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("backup.githubBackup")})]}),Le&&n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"text-sm text-bambu-gray",children:a("backup.enabled")}),n.jsx(ja,{checked:q,onChange:I})]})]})}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:a("backup.githubDescription")}),n.jsxs("div",{children:[n.jsx("label",{htmlFor:"git-provider-select",className:"block text-sm text-bambu-gray mb-1",children:a("backup.provider")}),n.jsxs("select",{id:"git-provider-select",value:d,onChange:gt=>{u(gt.target.value),he(null),L(null)},className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:"github",children:a("backup.providerGitHub")}),n.jsx("option",{value:"gitlab",children:a("backup.providerGitLab")}),n.jsx("option",{value:"gitea",children:a("backup.providerGitea")}),n.jsx("option",{value:"forgejo",children:a("backup.providerForgejo")})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("backup.repositoryUrl")}),n.jsx("input",{type:"text",value:r,onChange:gt=>{i(gt.target.value),he(null),L(null)},placeholder:a(lit[d]),className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),n.jsxs("label",{className:"flex items-start gap-2 mt-2 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:k,onChange:gt=>{M(gt.target.checked),he(null)},className:"w-4 h-4 mt-0.5 rounded border-bambu-dark-tertiary bg-bambu-dark text-bambu-green focus:ring-bambu-green"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-sm text-white",children:a("backup.allowInsecureHttp")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("backup.allowInsecureHttpHint")})]})]})]}),n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm text-bambu-gray mb-1",children:[a("backup.personalAccessToken")," ",Le?.has_token&&n.jsx("span",{className:"text-green-400",children:a("backup.tokenSaved")})]}),n.jsx("input",{type:"password",value:s,onChange:gt=>{o(gt.target.value),he(null),L(null)},placeholder:Le?.has_token?a("backup.enterNewToken"):cit[d],className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:a("backup.tokenHint")})]}),n.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("backup.branch")}),n.jsx("input",{type:"text",value:l,onChange:gt=>c(gt.target.value),placeholder:"main",className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("backup.autoBackup")}),n.jsxs("select",{value:m?f:"disabled",onChange:gt=>{gt.target.value==="disabled"?p(!1):(p(!0),g(gt.target.value))},className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",children:[n.jsx("option",{value:"disabled",children:a("backup.manualOnly")}),n.jsx("option",{value:"hourly",children:a("backup.hourly")}),n.jsx("option",{value:"daily",children:a("backup.daily")}),n.jsx("option",{value:"weekly",children:a("backup.weekly")})]})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-2",children:a("backup.includeInBackup")}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs("label",{className:`flex items-start gap-2 ${Ae?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:[n.jsx("input",{type:"checkbox",checked:w,onChange:gt=>b(gt.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:Ae}),n.jsxs("div",{className:"flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`text-sm ${Ae?"text-bambu-gray":"text-white"}`,children:a("backup.kProfiles")}),Ae&&n.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:[n.jsx(ba,{className:"w-3 h-3"}),a("backup.noPrintersConnected")]}),Ie&&n.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:[n.jsx(ba,{className:"w-3 h-3"}),a("backup.printersConnected",{connected:Ye,total:Ze})]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("backup.kProfilesDescription")})]})]}),n.jsxs("label",{className:`flex items-start gap-2 ${ot?.is_authenticated?"cursor-pointer":"cursor-not-allowed opacity-60"}`,children:[n.jsx("input",{type:"checkbox",checked:x,onChange:gt=>S(gt.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:!ot?.is_authenticated}),n.jsxs("div",{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`text-sm ${ot?.is_authenticated?"text-white":"text-bambu-gray"}`,children:a("backup.cloudProfiles")}),!ot?.is_authenticated&&n.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:[n.jsx(ba,{className:"w-3 h-3"}),a("backup.cloudLoginRequiredShort")]})]}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("backup.cloudProfilesDescription")})]})]}),n.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:N,onChange:gt=>C(gt.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"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-white text-sm",children:a("backup.appSettings")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("backup.appSettingsDescription")})]})]}),n.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:P,onChange:gt=>T(gt.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"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-white text-sm",children:a("backup.spoolInventory")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("backup.spoolInventoryDescription")})]})]}),n.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:j,onChange:gt=>F(gt.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"}),n.jsxs("div",{children:[n.jsx("span",{className:"text-white text-sm",children:a("backup.printArchives")}),n.jsx("p",{className:"text-xs text-bambu-gray",children:a("backup.printArchivesDescription")})]})]})]})]}),n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-4 space-y-3",children:[We?.configured&&n.jsxs("div",{className:"flex items-center justify-between text-sm",children:[n.jsx("div",{className:"flex items-center gap-2 text-bambu-gray",children:We.last_backup_at?n.jsxs(n.Fragment,{children:[n.jsxs("span",{children:[a("backup.lastBackupAt")," ",Fh(We.last_backup_at,"system",a)]}),n.jsx(y3,{status:We.last_backup_status})]}):n.jsx("span",{children:a("backup.noBackupsYet")})}),We.next_scheduled_run&&n.jsxs("span",{className:"text-bambu-gray",children:[n.jsx(Za,{className:"w-3 h-3 inline mr-1"}),a("backup.next")," ",Fh(We.next_scheduled_run,"system",a)]})]}),$&&n.jsxs("div",{className:"text-sm text-red-400 bg-red-500/10 border border-red-500/30 rounded p-3 flex items-start gap-2",children:[n.jsx(Mn,{className:"w-4 h-4 mt-0.5 shrink-0"}),n.jsx("div",{className:"flex-1 leading-relaxed whitespace-pre-wrap break-words",children:$}),n.jsx("button",{type:"button",onClick:()=>L(null),className:"text-bambu-gray hover:text-white shrink-0","aria-label":a("common.dismiss","Dismiss"),children:n.jsx(Mn,{className:"w-4 h-4"})})]}),ce&&n.jsxs("div",{className:"space-y-1.5",children:[n.jsxs("div",{className:`text-sm flex items-center gap-1 ${ce.success?"text-green-400":"text-red-400"}`,children:[ce.success?n.jsx(fn,{className:"w-4 h-4"}):n.jsx(Mn,{className:"w-4 h-4"}),ce.message]}),ce.success&&ce.isPrivate===!0&&n.jsxs("div",{className:"text-xs flex items-center gap-1 text-green-400",children:[n.jsx(fn,{className:"w-3.5 h-3.5"}),a("backup.repoIsPrivate","Repository is private — safe to back up to.")]}),ce.success&&ce.isPrivate===!1&&n.jsxs("div",{className:"text-xs text-red-400 bg-red-500/10 border border-red-500/30 rounded p-2 flex items-start gap-1.5",children:[n.jsx(Mn,{className:"w-4 h-4 mt-0.5 shrink-0"}),n.jsx("span",{children:a("backup.repoIsPublicWarning","Repository is PUBLIC. Bambuddy backups include MQTT credentials, Home Assistant tokens, Prometheus tokens, your Bambu Cloud email, and printer access codes via K-profiles. Saving is blocked until you make the repository private in your provider's settings.")})]}),ce.success&&ce.isPrivate===null&&n.jsxs("div",{className:"text-xs text-yellow-400 bg-yellow-500/10 border border-yellow-500/30 rounded p-2 flex items-start gap-1.5",children:[n.jsx(Mn,{className:"w-4 h-4 mt-0.5 shrink-0"}),n.jsx("span",{children:a("backup.repoVisibilityUnknown","Could not determine repository visibility. Bambuddy refuses to back up to anything not confirmed private; saving will be blocked.")})]})]}),n.jsx("div",{className:"flex flex-wrap items-center gap-2",children:We?.configured?n.jsx(n.Fragment,{children:at.isPending||We.is_running?n.jsxs("div",{className:"flex items-center gap-2 text-bambu-green",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),n.jsx("span",{className:"text-sm",children:We.progress||a("backup.startingBackup")})]}):n.jsxs(n.Fragment,{children:[n.jsxs(Me,{variant:"primary",size:"sm",onClick:()=>at.mutate(),disabled:!Le?.enabled,children:[n.jsx(ys,{className:"w-4 h-4"}),a("backup.backupNow")]}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:At,disabled:se,children:[se?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),a("backup.test")]})]})}):n.jsxs(n.Fragment,{children:[n.jsxs(Me,{variant:"primary",size:"sm",onClick:Bt,disabled:Pe.isPending||!r||!s,children:[Pe.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(fn,{className:"w-4 h-4"}),a("backup.enableBackup")]}),n.jsxs(Me,{variant:"secondary",size:"sm",onClick:At,disabled:se||!r||!s,children:[se?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(Xa,{className:"w-4 h-4"}),a("backup.testConnection")]})]})})]})]})]}),Be&&Be.length>0&&n.jsxs(Tt,{id:"card-backup-history",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Wh,{className:"w-5 h-5 text-gray-400"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("backup.history")})]}),n.jsxs(Me,{variant:"ghost",size:"sm",onClick:()=>rt.mutate(),disabled:rt.isPending,children:[n.jsx(ea,{className:"w-4 h-4"}),a("backup.clear")]})]})}),n.jsx(Mt,{children:n.jsx("div",{className:"overflow-x-auto",children:n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"text-bambu-gray border-b border-bambu-dark-tertiary",children:[n.jsx("th",{className:"text-left py-2 px-2",children:a("backup.date")}),n.jsx("th",{className:"text-left py-2 px-2",children:a("backup.status")}),n.jsx("th",{className:"text-left py-2 px-2",children:a("backup.commit")})]})}),n.jsx("tbody",{children:Be.slice(0,10).map(gt=>n.jsxs("tr",{className:"border-b border-bambu-dark-tertiary/50 hover:bg-bambu-dark-secondary",children:[n.jsx("td",{className:"py-2 px-2 text-white",children:x3(gt.started_at)}),n.jsx("td",{className:"py-2 px-2",children:n.jsx(y3,{status:gt.status})}),n.jsx("td",{className:"py-2 px-2",children:gt.commit_sha?n.jsxs("a",{href:`${Le?.repository_url}/commit/${gt.commit_sha}`,target:"_blank",rel:"noopener noreferrer",className:"text-bambu-green hover:underline inline-flex items-center gap-1",children:[gt.commit_sha.substring(0,7),n.jsx(En,{className:"w-3 h-3"})]}):n.jsx("span",{className:"text-bambu-gray",children:"-"})})]},gt.id))})]})})})]})]}),n.jsxs("div",{className:"space-y-6",children:[n.jsxs(Tt,{id:"card-backup-local",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(hc,{className:"w-5 h-5 text-gray-400"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("backup.localBackup")})]})}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:a("backup.localBackupDescription")}),n.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white",children:a("backup.downloadBackupLabel")}),n.jsx("p",{className:"text-sm text-bambu-gray",children:a("backup.completeBackupZip")})]}),n.jsxs(Me,{variant:"secondary",size:"sm",disabled:B||X,onClick:async()=>{R(!0),le(a("backup.preparingBackup"));try{le(a("backup.creatingArchive"));const{blob:gt,filename:Qt}=await ne.exportBackup();le(a("backup.downloadingFile"));const Xt=URL.createObjectURL(gt),ia=document.createElement("a");ia.href=Xt,ia.download=Qt,ia.click(),URL.revokeObjectURL(Xt),e(a("backup.backupDownloaded"))}catch(gt){e(a("backup.failedToCreateBackup",{message:gt instanceof Error?gt.message:"Unknown error"}),"error")}finally{R(!1),le("")}},children:[n.jsx(Bn,{className:"w-4 h-4"}),a("backup.download")]})]}),n.jsxs("div",{className:"flex items-center justify-between py-3 border-b border-bambu-dark-tertiary",children:[n.jsxs("div",{children:[n.jsx("p",{className:"text-white",children:a("backup.restoreBackup")}),n.jsx("p",{className:"text-sm text-bambu-gray",children:a("backup.restoreDescription")}),n.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:a("backup.restoreNote")})]}),n.jsx("input",{ref:be,type:"file",accept:".zip",className:"hidden",onChange:gt=>{const Qt=gt.target.files?.[0];Qt&&(oe(Qt),ue(!0)),gt.target.value=""}}),n.jsxs(Me,{variant:"secondary",size:"sm",disabled:X||B,onClick:()=>be.current?.click(),children:[n.jsx(Sr,{className:"w-4 h-4"}),a("backup.restore")]})]}),fe&&n.jsx("div",{className:`p-3 rounded-lg ${fe.success?"bg-green-500/10 border border-green-500/30":"bg-red-500/10 border border-red-500/30"}`,children:n.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[fe.success?n.jsx(fn,{className:"w-4 h-4 text-green-400 mt-0.5 flex-shrink-0"}):n.jsx(Mn,{className:"w-4 h-4 text-red-400 mt-0.5 flex-shrink-0"}),n.jsxs("div",{className:fe.success?"text-green-200":"text-red-200",children:[fe.message,fe.success&&n.jsx("div",{className:"mt-2",children:n.jsxs(Me,{size:"sm",onClick:()=>window.location.reload(),children:[n.jsx(vs,{className:"w-3 h-3"}),a("backup.reloadNow")]})})]})]})}),n.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:n.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[n.jsx(ba,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),n.jsxs("div",{className:"text-yellow-200",children:[n.jsx("span",{className:"font-medium",children:a("backup.restoreReplacesAll")})," ",n.jsx("span",{className:"text-yellow-200/70",children:a("backup.restoreReplacesAllDetail")})]})]})})]})]}),n.jsxs(Tt,{id:"card-backup-scheduled",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(qbe,{className:"w-5 h-5 text-gray-400"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:a("backup.scheduledBackup")})]}),n.jsx(ja,{checked:O?.enabled??!1,onChange:async gt=>{try{await ne.updateSettings({local_backup_enabled:gt}),t.invalidateQueries({queryKey:["settings"]}),e(a("backup.settingsSaved"))}catch(Qt){e(a("backup.failedToSave",{message:Qt instanceof Error?Qt.message:"Unknown error"}),"error")}re()}})]})}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsx("p",{className:"text-sm text-bambu-gray",children:a("backup.scheduledBackupDescription")}),O?.enabled&&n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("backup.frequency")}),n.jsxs("select",{value:O?.schedule??"daily",className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",onChange:async gt=>{try{await ne.updateSettings({local_backup_schedule:gt.target.value}),e(a("backup.settingsSaved"))}catch(Qt){e(a("backup.failedToSave",{message:Qt instanceof Error?Qt.message:"Unknown error"}),"error")}re()},children:[n.jsx("option",{value:"hourly",children:a("backup.hourly")}),n.jsx("option",{value:"daily",children:a("backup.daily")}),n.jsx("option",{value:"weekly",children:a("backup.weekly")})]})]}),(O?.schedule??"daily")!=="hourly"&&n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("backup.backupTime")}),n.jsx("input",{type:"time",value:O?.time??"03:00",className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none [color-scheme:dark]",onChange:async gt=>{try{await ne.updateSettings({local_backup_time:gt.target.value}),e(a("backup.settingsSaved"))}catch(Qt){e(a("backup.failedToSave",{message:Qt instanceof Error?Qt.message:"Unknown error"}),"error")}re()}}),n.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:a("backup.utc")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("backup.retention")}),n.jsx("input",{type:"number",min:1,max:100,value:O?.retention??5,className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",onChange:async gt=>{const Qt=Math.max(1,Math.min(100,parseInt(gt.target.value)||5));try{await ne.updateSettings({local_backup_retention:Qt}),e(a("backup.settingsSaved"))}catch(Xt){e(a("backup.failedToSave",{message:Xt instanceof Error?Xt.message:"Unknown error"}),"error")}re()}}),n.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:a("backup.retentionDescription")})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:a("backup.outputPath")}),n.jsx("input",{type:"text",value:z,onChange:gt=>W(gt.target.value),className:"w-full h-10 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white focus:border-bambu-green focus:outline-none",onBlur:async()=>{try{await ne.updateSettings({local_backup_path:z}),e(a("backup.settingsSaved"))}catch(gt){e(a("backup.failedToSave",{message:gt instanceof Error?gt.message:"Unknown error"}),"error")}re(),V()},onKeyDown:gt=>{gt.key==="Enter"&>.target.blur()}}),n.jsx("p",{className:"text-xs text-bambu-gray-light mt-1",children:z?a("backup.outputPathDescription"):n.jsxs(n.Fragment,{children:[a("backup.defaultPathLabel")," ",n.jsx("code",{className:"text-bambu-gray",children:O?.default_path||"..."})]})})]}),n.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-bambu-dark-tertiary",children:[n.jsxs("div",{className:"text-sm",children:[O?.last_backup_at&&n.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[n.jsxs("span",{children:[a("backup.lastBackup"),":"]}),n.jsx(y3,{status:O.last_status}),n.jsx("span",{children:Fh(O.last_backup_at)})]}),O?.next_run&&n.jsxs("div",{className:"text-bambu-gray mt-1",children:[n.jsxs("span",{children:[a("backup.nextBackup"),": "]}),n.jsx("span",{children:x3(O.next_run)})]})]}),n.jsxs(Me,{variant:"secondary",size:"sm",disabled:O?.is_running||K.isPending,onClick:()=>K.mutate(),children:[O?.is_running||K.isPending?n.jsx(pt,{className:"w-4 h-4 animate-spin"}):n.jsx(ys,{className:"w-4 h-4"}),O?.is_running?a("backup.backupRunning"):a("backup.runNow")]})]}),U&&U.length>0&&n.jsxs("div",{className:"border-t border-bambu-dark-tertiary pt-3",children:[n.jsx("h3",{className:"text-sm font-medium text-white mb-2",children:a("backup.backupFiles")}),n.jsx("div",{className:"space-y-1",children:U.map(gt=>n.jsxs("div",{className:"flex items-center justify-between py-1.5 px-2 rounded hover:bg-bambu-dark-tertiary/50 text-sm",children:[n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsx("span",{className:"text-white truncate block",children:gt.filename}),n.jsxs("span",{className:"text-bambu-gray text-xs",children:[(gt.size/1024/1024).toFixed(1)," MB · ",x3(gt.created_at)]})]}),n.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[n.jsx("button",{className:"text-bambu-gray hover:text-bambu-green p-1",title:a("backup.download"),onClick:async()=>{try{const{blob:Qt,filename:Xt}=await ne.downloadLocalBackup(gt.filename),ia=URL.createObjectURL(Qt),da=document.createElement("a");da.href=ia,da.download=Xt,da.click(),URL.revokeObjectURL(ia)}catch{e(a("backup.scheduledBackupFailed"),"error")}},children:n.jsx(Bn,{className:"w-3.5 h-3.5"})}),n.jsx("button",{className:"text-bambu-gray hover:text-yellow-400 p-1",title:a("backup.restore"),onClick:()=>E(gt.filename),children:n.jsx(vs,{className:"w-3.5 h-3.5"})}),n.jsx("button",{className:"text-bambu-gray hover:text-red-400 p-1",onClick:()=>J(gt.filename),title:a("backup.deleteBackup"),children:n.jsx(ea,{className:"w-3.5 h-3.5"})})]})]},gt.filename))})]}),U&&U.length===0&&n.jsx("p",{className:"text-sm text-bambu-gray text-center py-3 border-t border-bambu-dark-tertiary",children:a("backup.noScheduledBackups")})]})]})]})]}),H&&n.jsx(ya,{title:a("backup.deleteBackup"),message:a("backup.deleteBackupConfirm"),confirmText:a("backup.deleteBackup"),variant:"danger",onConfirm:()=>Y.mutate(H),onCancel:()=>J(null)}),A&&n.jsx(ya,{title:a("backup.restoreConfirmTitle"),message:a("backup.restoreConfirmMessage",{filename:A}),confirmText:a("backup.restoreConfirmButton"),variant:"danger",onConfirm:()=>ie.mutate(A),onCancel:()=>E(null)}),de&&Z&&n.jsx(ya,{title:a("backup.restoreConfirmTitle"),message:a("backup.restoreConfirmMessage",{filename:Z.name}),confirmText:a("backup.restoreConfirmButton"),variant:"danger",onConfirm:async()=>{ue(!1),ee(!0),me(null);try{le(a("backup.uploadingFile"));const gt=await ne.importBackup(Z);me(gt),gt.success?e(a("backup.backupRestoredRestart"),"success"):e(gt.message,"error")}catch(gt){const Qt=gt instanceof Error?gt.message:a("backup.failedToRestore");me({success:!1,message:Qt}),e(Qt,"error")}finally{ee(!1),le(""),oe(null)}},onCancel:()=>{ue(!1),oe(null)}}),(B||X)&&n.jsx("div",{className:"fixed inset-0 bg-black/80 flex items-center justify-center z-[100]",children:n.jsxs("div",{className:"bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-xl p-8 max-w-md w-full mx-4 text-center",children:[n.jsx("div",{className:"flex justify-center mb-4",children:n.jsxs("div",{className:"relative",children:[n.jsx("div",{className:"w-16 h-16 border-4 border-bambu-dark-tertiary rounded-full"}),n.jsx("div",{className:"w-16 h-16 border-4 border-bambu-green border-t-transparent rounded-full absolute inset-0 animate-spin"})]})}),n.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:a(B?"backup.creatingBackup":"backup.restoringBackup")}),n.jsx("p",{className:"text-bambu-gray mb-4",children:Q||a(B?"backup.preparing":"backup.processing")}),n.jsx("div",{className:"p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30",children:n.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[n.jsx(ba,{className:"w-4 h-4 text-yellow-400 mt-0.5 flex-shrink-0"}),n.jsx("p",{className:"text-yellow-200 text-left",children:a("backup.doNotClosePage")})]})})]})})]})}function mit(){const{t}=vt(),e=ta(),{showToast:a}=ra(),[r,i]=y.useState(!1),[s,o]=y.useState(""),[l,c]=y.useState("medium"),[d,u]=y.useState("notify"),[m,p]=y.useState(10),[f,g]=y.useState(null),[w,b]=y.useState(null),[x,S]=y.useState(!1),{data:N}=Qe({queryKey:["settings"],queryFn:ne.getSettings}),{data:C,refetch:P}=Qe({queryKey:["obico-status"],queryFn:ne.getObicoStatus,refetchInterval:1e4}),{data:T}=Qe({queryKey:["printers"],queryFn:ne.getPrinters});y.useEffect(()=>{if(N){i(N.obico_enabled??!1),o(N.obico_ml_url??""),c(N.obico_sensitivity??"medium"),u(N.obico_action??"notify"),p(N.obico_poll_interval??10);try{const M=N.obico_enabled_printers?JSON.parse(N.obico_enabled_printers):null;g(Array.isArray(M)?M:null)}catch{g(null)}S(!0)}},[N]);const j=lt({mutationFn:()=>ne.updateSettings({obico_enabled:r,obico_ml_url:s,obico_sensitivity:l,obico_action:d,obico_poll_interval:m,obico_enabled_printers:f===null?"":JSON.stringify(f)}),onSuccess:()=>{e.invalidateQueries({queryKey:["settings"]}),e.invalidateQueries({queryKey:["obico-status"]}),a(t("settings.toast.settingsSaved"))}});y.useEffect(()=>{if(!x||!N||!(N.obico_enabled!==r||N.obico_ml_url!==s||N.obico_sensitivity!==l||N.obico_action!==d||N.obico_poll_interval!==m||N.obico_enabled_printers!==(f===null?"":JSON.stringify(f))))return;const q=setTimeout(()=>j.mutate(),500);return()=>clearTimeout(q)},[r,s,l,d,m,f,x]);const F=async()=>{b(null);try{const M=await ne.testObicoConnection(s);M.ok?b({ok:!0,message:t("failureDetection.testSuccess")}):b({ok:!1,message:M.error||`HTTP ${M.status_code??"?"} — ${M.body??t("failureDetection.testFailed")}`})}catch(M){b({ok:!1,message:M instanceof Error?M.message:String(M)})}},k=(M,q)=>{if(f===null){const I=T?.map(R=>R.id)??[],B=q?I:I.filter(R=>R!==M);g(B);return}g(q?[...f,M]:f.filter(I=>I!==M))};return n.jsxs("div",{className:"flex flex-col lg:flex-row gap-4 lg:gap-6",children:[n.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[n.jsxs(Tt,{id:"card-fd-ml",children:[n.jsxs(fa,{children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(tJ,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.title")})]}),n.jsx(ja,{checked:r,onChange:i})]}),n.jsx("p",{className:"text-sm text-bambu-gray mt-2",children:t("failureDetection.description")})]}),n.jsxs(Mt,{className:"space-y-4",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.mlUrl")}),n.jsxs("div",{className:"flex gap-2",children:[n.jsx("input",{type:"text",value:s,onChange:M=>o(M.target.value),placeholder:"http://192.168.1.10:3333",className:"flex-1 bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",disabled:!r}),n.jsx(Me,{onClick:F,disabled:!s||j.isPending,variant:"secondary",children:t("failureDetection.test")})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.mlUrlHint")}),w&&n.jsxs("div",{className:`flex items-start gap-2 mt-2 text-sm ${w.ok?"text-green-400":"text-red-400"}`,children:[w.ok?n.jsx(_n,{className:"w-4 h-4 mt-0.5"}):n.jsx($t,{className:"w-4 h-4 mt-0.5"}),n.jsx("span",{children:w.message})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.sensitivity")}),n.jsxs("select",{value:l,onChange:M=>c(M.target.value),disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[n.jsx("option",{value:"low",children:t("failureDetection.sensitivityLow")}),n.jsx("option",{value:"medium",children:t("failureDetection.sensitivityMedium")}),n.jsx("option",{value:"high",children:t("failureDetection.sensitivityHigh")})]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.sensitivityHint")})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.action")}),n.jsxs("select",{value:d,onChange:M=>u(M.target.value),disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm",children:[n.jsx("option",{value:"notify",children:t("failureDetection.actionNotify")}),n.jsx("option",{value:"pause",children:t("failureDetection.actionPause")}),n.jsx("option",{value:"pause_and_off",children:t("failureDetection.actionPauseOff")})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm text-bambu-gray mb-1",children:t("failureDetection.pollInterval")}),n.jsx("input",{type:"number",value:m,onChange:M=>p(Math.max(5,Math.min(120,Number(M.target.value)||10))),min:5,max:120,disabled:!r,className:"w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-white text-sm"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("failureDetection.pollIntervalHint")})]}),C&&!C.external_url_configured&&r&&n.jsxs("div",{className:"flex items-start gap-2 p-3 bg-amber-900/30 border border-amber-700 rounded text-sm text-amber-200",children:[n.jsx(ba,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),n.jsxs("div",{children:[n.jsx("div",{className:"font-medium",children:t("failureDetection.externalUrlMissing")}),n.jsx("div",{className:"text-xs mt-1",children:t("failureDetection.externalUrlHint")})]})]})]})]}),n.jsxs(Tt,{id:"card-fd-perprinter",children:[n.jsxs(fa,{children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.perPrinterTitle")}),n.jsx("p",{className:"text-sm text-bambu-gray mt-1",children:t("failureDetection.perPrinterHint")})]}),n.jsxs(Mt,{className:"space-y-2",children:[n.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[n.jsx("input",{type:"checkbox",checked:f===null,onChange:M=>g(M.target.checked?null:T?.map(q=>q.id)??[]),disabled:!r}),n.jsx("span",{className:"text-white",children:t("failureDetection.monitorAll")})]}),f!==null&&T&&n.jsx("div",{className:"pl-5 space-y-1 border-l border-gray-700",children:T.map(M=>n.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[n.jsx("input",{type:"checkbox",checked:f.includes(M.id),onChange:q=>k(M.id,q.target.checked),disabled:!r}),n.jsx("span",{className:"text-white",children:M.name})]},M.id))})]})]})]}),n.jsxs("div",{className:"space-y-3 flex-1 lg:max-w-xl",children:[n.jsxs(Tt,{id:"card-fd-status",children:[n.jsx(fa,{children:n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.statusTitle")})}),n.jsx(Mt,{children:C?n.jsxs("div",{className:"space-y-3 text-sm",children:[n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.serviceRunning")}),n.jsx("span",{className:C.is_running?"text-green-400":"text-red-400",children:C.is_running?t("common.yes"):t("common.no")})]}),n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-bambu-gray",children:t("failureDetection.thresholds")}),n.jsxs("span",{className:"text-white font-mono",children:[C.thresholds.low.toFixed(2)," / ",C.thresholds.high.toFixed(2)]})]}),C.last_error&&n.jsxs("div",{className:"flex items-start gap-2 text-red-400",children:[n.jsx($t,{className:"w-4 h-4 mt-0.5 flex-shrink-0"}),n.jsx("span",{className:"break-words",children:C.last_error})]}),n.jsxs("div",{children:[n.jsx("div",{className:"text-bambu-gray mb-1",children:t("failureDetection.activePrinters")}),Object.keys(C.per_printer).length===0?n.jsx("div",{className:"text-bambu-gray italic text-xs",children:t("failureDetection.noActivePrints")}):n.jsx("div",{className:"space-y-1",children:Object.entries(C.per_printer).map(([M,q])=>{const I=T?.find(R=>String(R.id)===M),B=q.class==="failure"?"text-red-400":q.class==="warning"?"text-amber-400":"text-green-400";return n.jsxs("div",{className:"flex justify-between",children:[n.jsx("span",{className:"text-white",children:I?.name??`Printer ${M}`}),n.jsxs("span",{className:`font-mono ${B}`,children:[q.class," (",q.score.toFixed(3),", ",q.frame_count,"f)"]})]},M)})})]})]}):n.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray",children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),n.jsx("span",{children:t("common.loading")})]})})]}),n.jsxs(Tt,{id:"card-fd-history",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("failureDetection.historyTitle")}),n.jsx("button",{onClick:()=>P(),className:"text-xs text-bambu-gray hover:text-white",children:t("common.refresh")})]})}),n.jsx(Mt,{children:!C||C.history.length===0?n.jsxs("div",{className:"flex items-center gap-2 text-bambu-gray text-sm",children:[n.jsx(Ei,{className:"w-4 h-4"}),n.jsx("span",{children:t("failureDetection.noHistory")})]}):n.jsx("div",{className:"space-y-1 max-h-96 overflow-y-auto text-xs font-mono",children:C.history.map((M,q)=>{const I=T?.find(R=>R.id===M.printer_id),B=M.class==="failure"?"text-red-400":M.class==="warning"?"text-amber-400":"text-bambu-gray";return n.jsxs("div",{className:"flex justify-between gap-2 py-1 border-b border-gray-800",children:[n.jsx("span",{className:"text-bambu-gray",children:new Date(M.timestamp).toLocaleTimeString()}),n.jsx("span",{className:"text-white truncate",children:I?.name??`#${M.printer_id}`}),n.jsxs("span",{className:B,children:[M.class," ",M.score.toFixed(3)]})]},q)})})})]})]})]})}const pit={starttls:587,ssl:465,none:25},hit={587:"starttls",465:"ssl",25:"none"};function fit(){const{t}=vt(),{showToast:e}=ra(),a=ta(),[r,i]=y.useState({smtp_host:"",smtp_port:587,smtp_username:"",smtp_password:"",smtp_security:"starttls",smtp_auth_enabled:!0,smtp_from_email:"",smtp_from_name:"BamBuddy"}),[s,o]=y.useState(""),{data:l,isLoading:c}=Qe({queryKey:["smtpSettings"],queryFn:()=>ne.getSMTPSettings()}),{authEnabled:d}=un(),{data:u}=Qe({queryKey:["advancedAuthStatus"],queryFn:()=>ne.getAdvancedAuthStatus()});y.useEffect(()=>{l&&i({...l,smtp_password:""})},[l]);const m=j=>{i({...r,smtp_security:j,smtp_port:pit[j]})},p=j=>{const F=hit[j];i({...r,smtp_port:j,...F?{smtp_security:F}:{}})},f=j=>{i({...r,smtp_auth_enabled:j,...j?{}:{smtp_username:"",smtp_password:""}})},g=lt({mutationFn:j=>ne.saveSMTPSettings(j),onSuccess:()=>{a.invalidateQueries({queryKey:["smtpSettings"]}),a.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(t("settings.email.success.settingsSaved"),"success")},onError:j=>{e(j.message,"error")}}),w=lt({mutationFn:j=>ne.testSMTP(j),onSuccess:j=>{e(j.message,j.success?"success":"error")},onError:j=>{e(j.message,"error")}}),b=lt({mutationFn:j=>j?ne.enableAdvancedAuth():ne.disableAdvancedAuth(),onSuccess:j=>{a.invalidateQueries({queryKey:["advancedAuthStatus"]}),e(j.message,"success")},onError:j=>{e(j.message,"error")}}),x=()=>{if(!r.smtp_host||!r.smtp_from_email){e(t("settings.email.errors.requiredFields"),"error");return}if(r.smtp_auth_enabled&&!r.smtp_username){e(t("settings.email.errors.usernameRequired"),"error");return}g.mutate(r)},S=()=>{if(!s){e(t("settings.email.errors.enterTestEmail"),"error");return}w.mutate({test_recipient:s})},N=()=>{if(!d){e(t("settings.email.errors.enableAuthFirst"),"error");return}if(!u?.advanced_auth_enabled&&!u?.smtp_configured){e(t("settings.email.errors.configureSmtpFirst"),"error");return}b.mutate(!u?.advanced_auth_enabled)};if(c)return n.jsx("div",{className:"flex items-center justify-center p-12",children:n.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});const C=u?.advanced_auth_enabled??!1,P="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors",T="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";return n.jsxs("div",{className:"space-y-3",children:[n.jsxs(Tt,{id:"card-email-advanced-auth",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Qm,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.advancedAuth")||"Advanced Authentication"})]}),n.jsx(Me,{onClick:N,disabled:b.isPending,variant:C?"danger":"primary",children:C?n.jsxs(n.Fragment,{children:[n.jsx(aw,{className:"w-4 h-4"}),t("settings.email.disable")||"Disable"]}):n.jsxs(n.Fragment,{children:[n.jsx(oc,{className:"w-4 h-4"}),t("settings.email.enable")||"Enable"]})})]})}),n.jsx(Mt,{children:n.jsx("div",{className:"space-y-3",children:C?n.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(fn,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthEnabled")||"Advanced Authentication is enabled"}),n.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[n.jsx("li",{children:t("settings.email.feature1")||"Passwords are auto-generated and emailed to new users"}),n.jsx("li",{children:t("settings.email.feature2")||"Users can login with username or email"}),n.jsx("li",{children:t("settings.email.feature3")||"Forgot password feature is available"}),n.jsx("li",{children:t("settings.email.feature4")||"Admins can reset user passwords via email"})]})]})]})}):n.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(ba,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-white font-medium",children:t("settings.email.advancedAuthDisabled")||"Advanced Authentication is disabled"}),n.jsx("p",{className:"text-sm text-yellow-300",children:t("settings.email.advancedAuthDisabledDesc")||"Enable advanced authentication to activate email-based features for user management."})]})]})})})})]}),n.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[n.jsx("div",{className:"lg:col-span-2",children:n.jsxs(Tt,{id:"card-smtp-config",children:[n.jsx(fa,{children:n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.smtpSettings")||"SMTP Configuration"})}),n.jsx(Mt,{children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.authentication")||"Authentication"}),n.jsxs("select",{value:r.smtp_auth_enabled?"true":"false",onChange:j=>f(j.target.value==="true"),className:P,children:[n.jsx("option",{value:"true",children:t("settings.email.authOptions.enabled")}),n.jsx("option",{value:"false",children:t("settings.email.authOptions.disabled")})]})]}),n.jsxs("div",{className:`grid grid-cols-1 md:grid-cols-2 gap-4 transition-opacity ${r.smtp_auth_enabled?"":"opacity-40 pointer-events-none"}`,children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.username")||"Username"}),n.jsx("input",{type:"text",value:r.smtp_username||"",onChange:j=>i({...r,smtp_username:j.target.value}),placeholder:"your.email@gmail.com",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?P:T})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.password")||"Password"}),n.jsx("input",{type:"password",value:r.smtp_password||"",onChange:j=>i({...r,smtp_password:j.target.value}),placeholder:l?"••••••••":"App password",disabled:!r.smtp_auth_enabled,className:r.smtp_auth_enabled?P:T})]})]}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.smtpHost")||"SMTP Server"," *"]}),n.jsx("input",{type:"text",value:r.smtp_host,onChange:j=>i({...r,smtp_host:j.target.value}),placeholder:"smtp.gmail.com",className:P})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.smtpPort")||"SMTP Port"}),n.jsx("input",{type:"number",value:r.smtp_port,onChange:j=>p(parseInt(j.target.value)||587),placeholder:"587",className:P})]})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.security")||"Security"}),n.jsxs("select",{value:r.smtp_security,onChange:j=>m(j.target.value),className:P,children:[n.jsx("option",{value:"starttls",children:t("settings.email.securityOptions.starttls")}),n.jsx("option",{value:"ssl",children:t("settings.email.securityOptions.ssl")}),n.jsx("option",{value:"none",children:t("settings.email.securityOptions.none")})]})]}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[n.jsxs("div",{children:[n.jsxs("label",{className:"block text-sm font-medium text-white mb-1",children:[t("settings.email.fromEmail")||"From Email"," *"]}),n.jsx("input",{type:"email",value:r.smtp_from_email,onChange:j=>i({...r,smtp_from_email:j.target.value}),placeholder:"your@email.com",className:P})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.fromName")||"From Name"}),n.jsx("input",{type:"text",value:r.smtp_from_name,onChange:j=>i({...r,smtp_from_name:j.target.value}),placeholder:"BamBuddy",className:P})]})]}),n.jsx("div",{className:"flex gap-2",children:n.jsx(Me,{onClick:x,disabled:g.isPending,className:"flex-1",children:g.isPending?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),t("settings.email.saving")||"Saving..."]}):t("settings.email.save")||"Save Settings"})})]})})]})}),n.jsx("div",{children:n.jsxs(Tt,{id:"card-email-test",children:[n.jsx(fa,{children:n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.email.testConnection")||"Test SMTP Connection"})}),n.jsx(Mt,{children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white mb-1",children:t("settings.email.testRecipient")||"Test Recipient Email"}),n.jsx("input",{type:"email",value:s,onChange:j=>o(j.target.value),placeholder:"test@example.com",className:P})]}),n.jsx(Me,{onClick:S,disabled:w.isPending,variant:"secondary",children:w.isPending?n.jsxs(n.Fragment,{children:[n.jsx(pt,{className:"w-4 h-4 animate-spin"}),t("settings.email.sending")||"Sending..."]}):n.jsxs(n.Fragment,{children:[n.jsx(OS,{className:"w-4 h-4"}),t("settings.email.sendTest")||"Send Test Email"]})})]})})]})})]})]})}const git={starttls:"389",ldaps:"636"};function bit(){const{t}=vt(),{showToast:e}=ra(),a=ta(),{authEnabled:r}=un(),[i,s]=y.useState({ldap_server_url:"",ldap_bind_dn:"",ldap_bind_password:"",ldap_search_base:"",ldap_user_filter:"(sAMAccountName={username})",ldap_security:"starttls",ldap_group_mapping:"",ldap_auto_provision:!1,ldap_default_group:""}),{data:o,isLoading:l}=Qe({queryKey:["settings"],queryFn:()=>ne.getSettings()}),{data:c}=Qe({queryKey:["ldapStatus"],queryFn:()=>ne.getLDAPStatus()}),{data:d=[]}=Qe({queryKey:["groups"],queryFn:()=>ne.getGroups()});y.useEffect(()=>{o&&s({ldap_server_url:o.ldap_server_url||"",ldap_bind_dn:o.ldap_bind_dn||"",ldap_bind_password:"",ldap_search_base:o.ldap_search_base||"",ldap_user_filter:o.ldap_user_filter||"(sAMAccountName={username})",ldap_security:o.ldap_security||"starttls",ldap_group_mapping:o.ldap_group_mapping||"",ldap_auto_provision:o.ldap_auto_provision??!1,ldap_default_group:o.ldap_default_group||""})},[o]);const u=lt({mutationFn:x=>ne.updateSettings(x),onSuccess:()=>{a.invalidateQueries({queryKey:["settings"]}),a.invalidateQueries({queryKey:["ldapStatus"]}),e(t("settings.ldap.settingsSaved")||"LDAP settings saved","success")},onError:x=>{e(x.message,"error")}}),m=lt({mutationFn:x=>ne.updateSettings({ldap_enabled:x}),onSuccess:()=>{a.invalidateQueries({queryKey:["settings"]}),a.invalidateQueries({queryKey:["ldapStatus"]}),e(c?.ldap_enabled?t("settings.ldap.disabled")||"LDAP authentication disabled":t("settings.ldap.enabled")||"LDAP authentication enabled","success")},onError:x=>{e(x.message,"error")}}),p=lt({mutationFn:()=>ne.testLDAP(),onSuccess:x=>{e(x.message,x.success?"success":"error")},onError:x=>{e(x.message,"error")}}),f=()=>{if(!i.ldap_server_url){e(t("settings.ldap.errors.serverRequired")||"LDAP server URL is required","error");return}if(!i.ldap_search_base){e(t("settings.ldap.errors.searchBaseRequired")||"Search base DN is required","error");return}const x={ldap_server_url:i.ldap_server_url,ldap_bind_dn:i.ldap_bind_dn,ldap_search_base:i.ldap_search_base,ldap_user_filter:i.ldap_user_filter,ldap_security:i.ldap_security,ldap_group_mapping:i.ldap_group_mapping,ldap_auto_provision:i.ldap_auto_provision,ldap_default_group:i.ldap_default_group};i.ldap_bind_password&&(x.ldap_bind_password=i.ldap_bind_password),u.mutate(x)},g=()=>{if(!r){e(t("settings.ldap.errors.enableAuthFirst")||"Enable authentication first","error");return}if(!c?.ldap_enabled&&!c?.ldap_configured){e(t("settings.ldap.errors.configureLdapFirst")||"Save LDAP settings first","error");return}m.mutate(!c?.ldap_enabled)};if(l)return n.jsx("div",{className:"flex items-center justify-center p-12",children:n.jsx(pt,{className:"w-8 h-8 animate-spin text-bambu-green"})});const w=c?.ldap_enabled??!1,b="w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors";return n.jsxs("div",{className:"space-y-3",children:[n.jsxs(Tt,{id:"card-ldap-toggle",children:[n.jsx(fa,{children:n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(vl,{className:"w-5 h-5 text-bambu-green"}),n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.title")||"LDAP Authentication"})]}),n.jsx(Me,{onClick:g,disabled:m.isPending,variant:w?"danger":"primary",children:w?n.jsxs(n.Fragment,{children:[n.jsx(aw,{className:"w-4 h-4"}),t("common.disable")||"Disable"]}):n.jsxs(n.Fragment,{children:[n.jsx(oc,{className:"w-4 h-4"}),t("common.enable")||"Enable"]})})]})}),n.jsx(Mt,{children:w?n.jsx("div",{className:"bg-green-500/10 border border-green-500/30 rounded-lg p-4",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(fn,{className:"w-5 h-5 text-green-400 mt-0.5 flex-shrink-0"}),n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.enabledDesc")||"LDAP authentication is enabled"}),n.jsxs("ul",{className:"text-sm text-green-300 space-y-1 list-disc list-inside",children:[n.jsx("li",{children:t("settings.ldap.feature1")||"Users can login with LDAP credentials"}),n.jsx("li",{children:t("settings.ldap.feature2")||"Local admin account remains as fallback"}),n.jsx("li",{children:t("settings.ldap.feature3")||"LDAP groups are mapped to BamBuddy groups on login"})]})]})]})}):n.jsx("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4",children:n.jsxs("div",{className:"flex items-start gap-3",children:[n.jsx(ba,{className:"w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0"}),n.jsxs("div",{children:[n.jsx("p",{className:"text-white font-medium",children:t("settings.ldap.disabledDesc")||"LDAP authentication is disabled"}),n.jsx("p",{className:"text-sm text-yellow-300 mt-1",children:t("settings.ldap.disabledHint")||"Configure and save LDAP settings below, then enable."})]})]})})})]}),n.jsxs(Tt,{id:"card-ldap-server",children:[n.jsx(fa,{children:n.jsx("h2",{className:"text-lg font-semibold text-white",children:t("settings.ldap.serverConfig")||"LDAP Server Configuration"})}),n.jsx(Mt,{children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[n.jsxs("div",{className:"md:col-span-2",children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.serverUrl")||"Server URL"}),n.jsx("input",{type:"text",className:b,placeholder:"ldaps://ldap.example.com:636",value:i.ldap_server_url,onChange:x=>s({...i,ldap_server_url:x.target.value})}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.serverUrlHint")||"Use ldaps:// for SSL or ldap:// with StartTLS"})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.security")||"Security"}),n.jsx("div",{className:"flex gap-2",children:["starttls","ldaps"].map(x=>n.jsx("button",{onClick:()=>s({...i,ldap_security:x}),className:`flex-1 px-2 py-2 rounded-lg text-sm font-medium transition-colors ${i.ldap_security===x?"bg-bambu-green text-black":"bg-bambu-dark-secondary text-bambu-gray hover:text-white border border-bambu-dark-tertiary"}`,children:x==="starttls"?"StartTLS":"LDAPS"},x))}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.securityHint")||`Default port: ${git[i.ldap_security]}`})]})]}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindDn")||"Bind DN (Service Account)"}),n.jsx("input",{type:"text",className:b,placeholder:"cn=service-account,ou=service,dc=example,dc=com",value:i.ldap_bind_dn,onChange:x=>s({...i,ldap_bind_dn:x.target.value})})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.bindPassword")||"Bind Password"}),n.jsx("input",{type:"password",className:b,placeholder:o?.ldap_bind_dn?"••••••••":"",value:i.ldap_bind_password,onChange:x=>s({...i,ldap_bind_password:x.target.value})})]})]}),n.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.searchBase")||"Search Base DN"}),n.jsx("input",{type:"text",className:b,placeholder:"ou=users,dc=example,dc=com",value:i.ldap_search_base,onChange:x=>s({...i,ldap_search_base:x.target.value})})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.userFilter")||"User Search Filter"}),n.jsx("input",{type:"text",className:b,placeholder:"(sAMAccountName={username})",value:i.ldap_user_filter,onChange:x=>s({...i,ldap_user_filter:x.target.value})})]})]}),n.jsx(RT,{summary:n.jsx("span",{className:"text-sm font-medium text-bambu-gray",children:t("settings.ldap.advanced")||"Advanced"}),className:"border-t border-bambu-dark-tertiary pt-3",summaryClassName:"py-1",children:n.jsxs("div",{className:"space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-white",children:t("settings.ldap.autoProvision")||"Auto-provision users"}),n.jsx("p",{className:"text-xs text-bambu-gray mt-0.5",children:t("settings.ldap.autoProvisionHint")||"Automatically create a BamBuddy account on first LDAP login"})]}),n.jsx("button",{onClick:()=>s({...i,ldap_auto_provision:!i.ldap_auto_provision}),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors flex-shrink-0 ${i.ldap_auto_provision?"bg-bambu-green":"bg-bambu-dark-tertiary"}`,children:n.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${i.ldap_auto_provision?"translate-x-6":"translate-x-1"}`})})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.defaultGroup")||"Default group"}),n.jsxs("select",{className:b,value:i.ldap_default_group,onChange:x=>s({...i,ldap_default_group:x.target.value}),children:[n.jsx("option",{value:"",children:t("settings.ldap.defaultGroupNone")||"— None (reject login) —"}),d.map(x=>n.jsx("option",{value:x.name,children:x.name},x.id))]}),n.jsx("p",{className:"text-xs text-bambu-gray mt-1",children:t("settings.ldap.defaultGroupHint")||"Fallback group assigned when an LDAP user authenticates but is not listed in any mapped group. Leave empty to leave unmapped users without permissions."})]}),n.jsxs("div",{children:[n.jsx("label",{className:"block text-sm font-medium text-bambu-gray mb-1",children:t("settings.ldap.groupMapping")||"Group Mapping (JSON)"}),n.jsx("textarea",{className:`${b} font-mono text-sm`,rows:4,placeholder:`{ "CN=PrintFarm_Admins,OU=Groups,DC=example,DC=com": "Administrators", "CN=PrintFarm_Users,OU=Groups,DC=example,DC=com": "Operators" diff --git a/static/index.html b/static/index.html index a3815d1ff..167c3e4de 100644 --- a/static/index.html +++ b/static/index.html @@ -26,7 +26,7 @@ - +