@usex/mikrotik-mcp 5.21.0 → 5.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -235,9 +235,9 @@ mikrotik-mcp devices # site-a (default) · site-b
235
235
  #### Docker: one writable `devices.json` for all MCP settings
236
236
 
237
237
  Use the published **[alimaster/mikrotik-mcp](https://hub.docker.com/r/alimaster/mikrotik-mcp)**
238
- image (`5.20.0`, or the moving `latest` tag). Docker selects `linux/amd64` or
238
+ image (`5.21.0`, or the moving `latest` tag). Docker selects `linux/amd64` or
239
239
  `linux/arm64` automatically; no local build is needed. Compose defaults to
240
- `5.20.0`; set `MIKROTIK_IMAGE_TAG` explicitly to select a different release.
240
+ `5.21.0`; set `MIKROTIK_IMAGE_TAG` explicitly to select a different release.
241
241
 
242
242
  The Bun container reads **`/home/bun/.mikrotik-mcp/devices.json`** automatically.
243
243
  Despite its name, this is the **complete MCP configuration**, not just the router
@@ -268,13 +268,13 @@ Create a real JSON file on the host (no comments or trailing commas). For exampl
268
268
  ```
269
269
 
270
270
  ```bash
271
- docker pull alimaster/mikrotik-mcp:5.20.0
271
+ docker pull alimaster/mikrotik-mcp:5.21.0
272
272
  docker run -d --name mikrotik-mcp --restart unless-stopped \
273
273
  -p 127.0.0.1:8000:8000 -p 127.0.0.1:9090:9090 \
274
274
  --mount type=volume,src=mikrotik-state,dst=/home/bun/.mikrotik-mcp \
275
275
  --mount type=bind,src=/absolute/path/devices.json,dst=/home/bun/.mikrotik-mcp/devices.json \
276
276
  --mount type=bind,src=/absolute/path/mikrotik_ed25519,dst=/run/secrets/mikrotik_key,readonly \
277
- alimaster/mikrotik-mcp:5.20.0
277
+ alimaster/mikrotik-mcp:5.21.0
278
278
  ```
279
279
 
280
280
  Dashboard: **http://localhost:9090** · MCP: **http://localhost:8000/mcp**.
@@ -445,6 +445,13 @@ and last-seen.
445
445
 
446
446
  **RADIUS & User Manager.** Servers, sessions, profiles, limitations and vouchers.
447
447
 
448
+ In **Users → Edit → Service profile**, keep the current profile or choose another
449
+ profile on the selected router. Saving reuses an eligible assignment (or creates
450
+ one), activates it and verifies the result. Previous assignments and accounting
451
+ history are preserved; queued profiles can still take over after expiry. Existing
452
+ connections may need to reconnect to receive new limits. No session is forcibly
453
+ disconnected. If a save cannot be confirmed, check **Assignments** before retrying.
454
+
448
455
  Reports & insights collects accounting in the background and shows verified-session
449
456
  progress on the first visit. Complete snapshots are saved privately alongside the
450
457
  dashboard database in `<dashboard.dbPath>.um-reports/` and restored after restart
package/dist/cli.js CHANGED
@@ -21892,13 +21892,13 @@ async function undoMigration(id, confirm, selected) {
21892
21892
  throw new Error("Undo lost Safe Mode or exceeded its time budget.");
21893
21893
  await checkedRead(item.undo, createContext(undefined, device));
21894
21894
  }
21895
- const beforeTarget = (await import("./shared/cli-se3tgt7t.js")).openSnapshotStore;
21896
- const db = await beforeTarget((await import("./shared/cli-h065ap70.js")).DEFAULT_SNAPSHOT_DB);
21895
+ const beforeTarget = (await import("./shared/cli-v5brt13c.js")).openSnapshotStore;
21896
+ const db = await beforeTarget((await import("./shared/cli-8tmbrnm5.js")).DEFAULT_SNAPSHOT_DB);
21897
21897
  try {
21898
21898
  const original = db.get(p.snapshots.target);
21899
21899
  if (!original)
21900
21900
  throw new Error("Original target snapshot unavailable.");
21901
- const { normalizeExport } = await import("./shared/cli-wf9a7qjm.js");
21901
+ const { normalizeExport } = await import("./shared/cli-a5tef6t8.js");
21902
21902
  if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
21903
21903
  throw new Error("Target differs from its backup. Undo verification failed.");
21904
21904
  } finally {
@@ -34637,7 +34637,7 @@ var cache3 = null;
34637
34637
  async function gateway() {
34638
34638
  if (cache3)
34639
34639
  return cache3;
34640
- const { moduleCatalog } = await import("./shared/cli-t311px0m.js");
34640
+ const { moduleCatalog } = await import("./shared/cli-0v69rn38.js");
34641
34641
  const forIndex = [];
34642
34642
  const byName = new Map;
34643
34643
  for (const mod of moduleCatalog) {
@@ -49577,6 +49577,109 @@ ${details}`;
49577
49577
  })
49578
49578
  ];
49579
49579
 
49580
+ // src/tools/um-user-profile.ts
49581
+ var assignmentSchema = array(object({
49582
+ ".id": string2().regex(/^\*[0-9a-f]+$/i),
49583
+ user: string2(),
49584
+ profile: string2(),
49585
+ state: _enum(["running-active", "running active", "running", "used"])
49586
+ })).max(1000);
49587
+ var active3 = (row) => row.state.replaceAll(" ", "-") === "running-active";
49588
+ async function assignments(ctx, user) {
49589
+ const query = new Cmd("/user-manager user-profile print").raw("as-value where").set("user", user).build();
49590
+ const output = await executeMikrotikCommand(`:put [:serialize to=json value=[${query}] options=json.no-string-conversion]`, ctx);
49591
+ if (output.length > 1e6)
49592
+ throw new Error("Assignment response too large");
49593
+ const rows = assignmentSchema.parse(JSON.parse(output));
49594
+ if (rows.some((row) => row.user !== user) || new Set(rows.map((row) => row[".id"])).size !== rows.length)
49595
+ throw new Error("Invalid assignment identities");
49596
+ return rows;
49597
+ }
49598
+ async function updateUmUserWithProfile(ctx, user, profile, pairs) {
49599
+ if (typeof profile !== "string" || !profile.trim() || !user.trim())
49600
+ return { ok: false, message: "A user name and a valid profile name are required." };
49601
+ const renamed = pairs.find(([key]) => key === "name")?.[1] ?? user;
49602
+ if (typeof renamed !== "string" || !renamed.trim())
49603
+ return { ok: false, message: "A valid user name is required." };
49604
+ let writeAttempted = false;
49605
+ try {
49606
+ for (const [menu, name] of [
49607
+ ["user", user],
49608
+ ["profile", profile]
49609
+ ]) {
49610
+ const count = await executeMikrotikCommand(new Cmd(`/user-manager ${menu} print count-only where`).set("name", name).build(), ctx);
49611
+ if (count.trim() !== "1")
49612
+ return {
49613
+ ok: false,
49614
+ message: `The selected ${menu} could not be verified on this device. Refresh before saving.`
49615
+ };
49616
+ }
49617
+ let rows = await assignments(ctx, user);
49618
+ if (rows.filter(active3).length > 1)
49619
+ return {
49620
+ ok: false,
49621
+ message: "Multiple active profiles were returned. Review Assignments before saving."
49622
+ };
49623
+ const eligible = rows.filter((row) => row.profile === profile && row.state !== "used");
49624
+ let target = eligible.find(active3) ?? (eligible.length === 1 ? eligible[0] : undefined);
49625
+ if (!target && eligible.length > 1)
49626
+ return {
49627
+ ok: false,
49628
+ message: "Multiple pending assignments use this profile. Review Assignments before saving."
49629
+ };
49630
+ const write = async (command) => {
49631
+ writeAttempted = true;
49632
+ const output = await executeMikrotikCommand(command, ctx);
49633
+ if (commandUnsupported(output) || looksLikeError(output))
49634
+ throw new Error("Router rejected update");
49635
+ };
49636
+ if (pairs.length) {
49637
+ const selector = new Cmd("find where").set("name", user).build();
49638
+ const command = new Cmd("/user-manager user set").raw(`[${selector}]`);
49639
+ for (const [key, value] of pairs)
49640
+ command.set(key, value);
49641
+ await write(command.build());
49642
+ }
49643
+ rows = await assignments(ctx, renamed);
49644
+ if (target) {
49645
+ const targetId = target[".id"];
49646
+ target = rows.find((row) => row[".id"] === targetId && row.profile === profile && row.state !== "used");
49647
+ if (!target)
49648
+ throw new Error("Assignment changed during save");
49649
+ } else {
49650
+ if (rows.some((row) => row.profile === profile && row.state !== "used"))
49651
+ throw new Error("Assignments changed during save");
49652
+ const previousIds = new Set(rows.map((row) => row[".id"]));
49653
+ await write(new Cmd("/user-manager user-profile add").set("user", renamed).set("profile", profile).build());
49654
+ rows = await assignments(ctx, renamed);
49655
+ const added = rows.filter((row) => !previousIds.has(row[".id"]) && row.profile === profile && row.state !== "used");
49656
+ if (added.length !== 1)
49657
+ throw new Error("New assignment could not be verified");
49658
+ target = added[0];
49659
+ }
49660
+ if (!active3(target)) {
49661
+ const selector = new Cmd("find where").set(".id", target[".id"]).set("user", renamed).set("profile", profile).build();
49662
+ await write(new Cmd("/user-manager user-profile activate-user-profile").raw(`[${selector}]`).build());
49663
+ }
49664
+ const current = (await assignments(ctx, renamed)).filter(active3);
49665
+ if (current.length !== 1 || current[0][".id"] !== target[".id"] || current[0].profile !== profile)
49666
+ throw new Error("Activation could not be verified");
49667
+ return {
49668
+ ok: true,
49669
+ message: `User saved. Active profile: ${profile}. Existing connections may need to reconnect for new limits.`
49670
+ };
49671
+ } catch {
49672
+ return writeAttempted ? {
49673
+ ok: false,
49674
+ reviewRequired: true,
49675
+ message: "Save could not be fully confirmed. User settings or profile assignments may have changed. Refresh Users and check Assignments before trying again; no automatic retry was made."
49676
+ } : {
49677
+ ok: false,
49678
+ message: "Could not verify this user's profile assignments. No changes were made. Check connectivity and refresh before saving."
49679
+ };
49680
+ }
49681
+ }
49682
+
49580
49683
  // src/tools/aaa-data.ts
49581
49684
  var UM_NOT_AVAILABLE = "User Manager is not available on this device (the user-manager package is not installed).";
49582
49685
  var SECRET_KEYS = new Set(["secret", "password", "shared-secret", "otp-secret"]);
@@ -49776,6 +49879,8 @@ async function updateAaaEntity(ctx, slug, id, fields) {
49776
49879
  if (entity.readonly)
49777
49880
  return { ok: false, message: `${slug} is read-only.` };
49778
49881
  const pairs = pickFields(entity, fields);
49882
+ if (slug === "um-users" && fields.profile !== undefined && fields.profile !== "")
49883
+ return updateUmUserWithProfile(ctx, id, fields.profile, pairs);
49779
49884
  if (pairs.length === 0)
49780
49885
  return { ok: false, message: "No updates supplied." };
49781
49886
  const cmd = applyFields(new Cmd(`/${entity.menu} set ${findClause(entity, id)}`), pairs).build();
@@ -57111,7 +57216,7 @@ var riskByTool = null;
57111
57216
  async function riskIndex() {
57112
57217
  if (riskByTool)
57113
57218
  return riskByTool;
57114
- const { moduleCatalog } = await import("./shared/cli-t311px0m.js");
57219
+ const { moduleCatalog } = await import("./shared/cli-0v69rn38.js");
57115
57220
  const index = new Map;
57116
57221
  for (const mod of moduleCatalog) {
57117
57222
  for (const tool of mod.tools)
package/dist/index.js CHANGED
@@ -70,7 +70,7 @@ import {
70
70
  updateSummaryLine,
71
71
  allToolModules2,
72
72
  selectToolModules2
73
- } from "./shared/library-6tvh3gq1.js";
73
+ } from "./shared/library-hbxz5fg7.js";
74
74
 
75
75
  // node_modules/ajv/dist/compile/codegen/code.js
76
76
  var require_code = __commonJS(function(exports) {
@@ -3,7 +3,7 @@ import {
3
3
  moduleCatalog2,
4
4
  allToolModules2,
5
5
  selectToolModules2
6
- } from "./library-6tvh3gq1.js";
6
+ } from "./library-hbxz5fg7.js";
7
7
  export {
8
8
  allToolModules2 as allToolModules,
9
9
  moduleCatalog2 as moduleCatalog,
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import {
3
3
  openSnapshotStore2
4
- } from "./library-6tvh3gq1.js";
4
+ } from "./library-hbxz5fg7.js";
5
5
  export {
6
6
  openSnapshotStore2 as openSnapshotStore
7
7
  };
@@ -14845,13 +14845,13 @@ async function undoMigration(id, confirm, selected) {
14845
14845
  throw new Error("Undo lost Safe Mode or exceeded its time budget.");
14846
14846
  await checkedRead(item.undo, createContext(undefined, device));
14847
14847
  }
14848
- const beforeTarget = (await import("./library-588vnctn.js")).openSnapshotStore;
14849
- const db = await beforeTarget((await import("./library-k6m2bxjr.js")).DEFAULT_SNAPSHOT_DB);
14848
+ const beforeTarget = (await import("./library-8ve5x0t1.js")).openSnapshotStore;
14849
+ const db = await beforeTarget((await import("./library-swqk16r2.js")).DEFAULT_SNAPSHOT_DB);
14850
14850
  try {
14851
14851
  const original = db.get(p.snapshots.target);
14852
14852
  if (!original)
14853
14853
  throw new Error("Original target snapshot unavailable.");
14854
- const { normalizeExport } = await import("./library-g8far2nz.js");
14854
+ const { normalizeExport } = await import("./library-nxgjnp8e.js");
14855
14855
  if (normalizeExport((await migrationInventory(device)).export) !== normalizeExport(original.body))
14856
14856
  throw new Error("Target differs from its backup. Undo verification failed.");
14857
14857
  } finally {
@@ -27154,7 +27154,7 @@ var cache3 = null;
27154
27154
  async function gateway() {
27155
27155
  if (cache3)
27156
27156
  return cache3;
27157
- const { moduleCatalog } = await import("./library-wj2xfx8h.js");
27157
+ const { moduleCatalog } = await import("./library-0ej78km8.js");
27158
27158
  const forIndex = [];
27159
27159
  const byName = new Map;
27160
27160
  for (const mod of moduleCatalog) {
@@ -42094,6 +42094,109 @@ ${details}`;
42094
42094
  })
42095
42095
  ];
42096
42096
 
42097
+ // src/tools/um-user-profile.ts
42098
+ var assignmentSchema = array(object({
42099
+ ".id": string().regex(/^\*[0-9a-f]+$/i),
42100
+ user: string(),
42101
+ profile: string(),
42102
+ state: _enum(["running-active", "running active", "running", "used"])
42103
+ })).max(1000);
42104
+ var active3 = (row) => row.state.replaceAll(" ", "-") === "running-active";
42105
+ async function assignments(ctx, user) {
42106
+ const query = new Cmd("/user-manager user-profile print").raw("as-value where").set("user", user).build();
42107
+ const output = await executeMikrotikCommand2(`:put [:serialize to=json value=[${query}] options=json.no-string-conversion]`, ctx);
42108
+ if (output.length > 1e6)
42109
+ throw new Error("Assignment response too large");
42110
+ const rows = assignmentSchema.parse(JSON.parse(output));
42111
+ if (rows.some((row) => row.user !== user) || new Set(rows.map((row) => row[".id"])).size !== rows.length)
42112
+ throw new Error("Invalid assignment identities");
42113
+ return rows;
42114
+ }
42115
+ async function updateUmUserWithProfile(ctx, user, profile, pairs) {
42116
+ if (typeof profile !== "string" || !profile.trim() || !user.trim())
42117
+ return { ok: false, message: "A user name and a valid profile name are required." };
42118
+ const renamed = pairs.find(([key]) => key === "name")?.[1] ?? user;
42119
+ if (typeof renamed !== "string" || !renamed.trim())
42120
+ return { ok: false, message: "A valid user name is required." };
42121
+ let writeAttempted = false;
42122
+ try {
42123
+ for (const [menu, name] of [
42124
+ ["user", user],
42125
+ ["profile", profile]
42126
+ ]) {
42127
+ const count = await executeMikrotikCommand2(new Cmd(`/user-manager ${menu} print count-only where`).set("name", name).build(), ctx);
42128
+ if (count.trim() !== "1")
42129
+ return {
42130
+ ok: false,
42131
+ message: `The selected ${menu} could not be verified on this device. Refresh before saving.`
42132
+ };
42133
+ }
42134
+ let rows = await assignments(ctx, user);
42135
+ if (rows.filter(active3).length > 1)
42136
+ return {
42137
+ ok: false,
42138
+ message: "Multiple active profiles were returned. Review Assignments before saving."
42139
+ };
42140
+ const eligible = rows.filter((row) => row.profile === profile && row.state !== "used");
42141
+ let target = eligible.find(active3) ?? (eligible.length === 1 ? eligible[0] : undefined);
42142
+ if (!target && eligible.length > 1)
42143
+ return {
42144
+ ok: false,
42145
+ message: "Multiple pending assignments use this profile. Review Assignments before saving."
42146
+ };
42147
+ const write = async (command) => {
42148
+ writeAttempted = true;
42149
+ const output = await executeMikrotikCommand2(command, ctx);
42150
+ if (commandUnsupported(output) || looksLikeError(output))
42151
+ throw new Error("Router rejected update");
42152
+ };
42153
+ if (pairs.length) {
42154
+ const selector = new Cmd("find where").set("name", user).build();
42155
+ const command = new Cmd("/user-manager user set").raw(`[${selector}]`);
42156
+ for (const [key, value] of pairs)
42157
+ command.set(key, value);
42158
+ await write(command.build());
42159
+ }
42160
+ rows = await assignments(ctx, renamed);
42161
+ if (target) {
42162
+ const targetId = target[".id"];
42163
+ target = rows.find((row) => row[".id"] === targetId && row.profile === profile && row.state !== "used");
42164
+ if (!target)
42165
+ throw new Error("Assignment changed during save");
42166
+ } else {
42167
+ if (rows.some((row) => row.profile === profile && row.state !== "used"))
42168
+ throw new Error("Assignments changed during save");
42169
+ const previousIds = new Set(rows.map((row) => row[".id"]));
42170
+ await write(new Cmd("/user-manager user-profile add").set("user", renamed).set("profile", profile).build());
42171
+ rows = await assignments(ctx, renamed);
42172
+ const added = rows.filter((row) => !previousIds.has(row[".id"]) && row.profile === profile && row.state !== "used");
42173
+ if (added.length !== 1)
42174
+ throw new Error("New assignment could not be verified");
42175
+ target = added[0];
42176
+ }
42177
+ if (!active3(target)) {
42178
+ const selector = new Cmd("find where").set(".id", target[".id"]).set("user", renamed).set("profile", profile).build();
42179
+ await write(new Cmd("/user-manager user-profile activate-user-profile").raw(`[${selector}]`).build());
42180
+ }
42181
+ const current = (await assignments(ctx, renamed)).filter(active3);
42182
+ if (current.length !== 1 || current[0][".id"] !== target[".id"] || current[0].profile !== profile)
42183
+ throw new Error("Activation could not be verified");
42184
+ return {
42185
+ ok: true,
42186
+ message: `User saved. Active profile: ${profile}. Existing connections may need to reconnect for new limits.`
42187
+ };
42188
+ } catch {
42189
+ return writeAttempted ? {
42190
+ ok: false,
42191
+ reviewRequired: true,
42192
+ message: "Save could not be fully confirmed. User settings or profile assignments may have changed. Refresh Users and check Assignments before trying again; no automatic retry was made."
42193
+ } : {
42194
+ ok: false,
42195
+ message: "Could not verify this user's profile assignments. No changes were made. Check connectivity and refresh before saving."
42196
+ };
42197
+ }
42198
+ }
42199
+
42097
42200
  // src/tools/aaa-data.ts
42098
42201
  var UM_NOT_AVAILABLE = "User Manager is not available on this device (the user-manager package is not installed).";
42099
42202
  var SECRET_KEYS = new Set(["secret", "password", "shared-secret", "otp-secret"]);
@@ -42293,6 +42396,8 @@ async function updateAaaEntity(ctx, slug, id, fields) {
42293
42396
  if (entity.readonly)
42294
42397
  return { ok: false, message: `${slug} is read-only.` };
42295
42398
  const pairs = pickFields(entity, fields);
42399
+ if (slug === "um-users" && fields.profile !== undefined && fields.profile !== "")
42400
+ return updateUmUserWithProfile(ctx, id, fields.profile, pairs);
42296
42401
  if (pairs.length === 0)
42297
42402
  return { ok: false, message: "No updates supplied." };
42298
42403
  const cmd = applyFields(new Cmd(`/${entity.menu} set ${findClause(entity, id)}`), pairs).build();
@@ -49380,7 +49485,7 @@ var riskByTool = null;
49380
49485
  async function riskIndex() {
49381
49486
  if (riskByTool)
49382
49487
  return riskByTool;
49383
- const { moduleCatalog } = await import("./library-wj2xfx8h.js");
49488
+ const { moduleCatalog } = await import("./library-0ej78km8.js");
49384
49489
  const index = new Map;
49385
49490
  for (const mod of moduleCatalog) {
49386
49491
  for (const tool of mod.tools)
@@ -4,7 +4,7 @@ import {
4
4
  normalizeExport2,
5
5
  contentSha2,
6
6
  countLines2
7
- } from "./library-6tvh3gq1.js";
7
+ } from "./library-hbxz5fg7.js";
8
8
  export {
9
9
  contentSha2 as contentSha,
10
10
  countLines2 as countLines,
@@ -11,7 +11,7 @@ import {
11
11
  MikrotikConfigSchema2,
12
12
  getConfigSource2,
13
13
  loadConfig2
14
- } from "./library-6tvh3gq1.js";
14
+ } from "./library-hbxz5fg7.js";
15
15
  export {
16
16
  DEFAULT_BACKUP_DIR2 as DEFAULT_BACKUP_DIR,
17
17
  DEFAULT_DASHBOARD_DB2 as DEFAULT_DASHBOARD_DB,
@@ -234,7 +234,7 @@ ${n.map(([e,n])=>{let r=n.theme?.[t]??n.color;return r?` --color-${e}: ${r};`:n
234
234
  `)}
235
235
  }
236
236
  `).join(`
237
- `)}}):null}var n2=dZ;function r2({active:e,payload:t,className:n,indicator:r=`dot`,hideLabel:i=!1,hideIndicator:a=!1,label:o,labelFormatter:s,labelClassName:c,formatter:l,color:u,nameKey:d,labelKey:f}){let{config:p}=gbe(),m=v.useMemo(()=>{if(i||!t?.length)return null;let[e]=t,n=e?.dataKey,r=String(f??(typeof n==`function`?void 0:n)??e?.name??`value`),a=i2(p,e,r),l=!f&&typeof o==`string`?p[o]?.label??o:a?.label;return s?(0,K.jsx)(`div`,{className:q(`font-medium`,c),children:s(l,t)}):l?(0,K.jsx)(`div`,{className:q(`font-medium`,c),children:l}):null},[o,s,t,i,c,p,f]);if(!e||!t?.length)return null;let h=t.length===1&&r!==`dot`;return(0,K.jsxs)(`div`,{className:q(`grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl`,n),children:[h?null:m,(0,K.jsx)(`div`,{className:`grid gap-1.5`,children:t.filter(e=>e.type!==`none`).map((e,t)=>{let n=String(d??e.name??(typeof e.dataKey==`function`?void 0:e.dataKey)??`value`),i=i2(p,e,n),o=u??e.payload?.fill??e.color;return(0,K.jsx)(`div`,{className:q(`flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground`,r===`dot`&&`items-center`),children:l&&e?.value!==void 0&&e.name?l(e.value,e.name,e,t,e.payload):(0,K.jsxs)(K.Fragment,{children:[i?.icon?(0,K.jsx)(i.icon,{}):!a&&(0,K.jsx)(`div`,{className:q(`shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)`,{"h-2.5 w-2.5":r===`dot`,"w-1":r===`line`,"w-0 border-[1.5px] border-dashed bg-transparent":r===`dashed`,"my-0.5":h&&r===`dashed`}),style:{"--color-bg":o,"--color-border":o}}),(0,K.jsxs)(`div`,{className:q(`flex flex-1 justify-between leading-none`,h?`items-end`:`items-center`),children:[(0,K.jsxs)(`div`,{className:`grid gap-1.5`,children:[h?m:null,(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:i?.label??e.name})]}),e.value!=null&&(0,K.jsx)(`span`,{className:`font-mono font-medium text-foreground tabular-nums`,children:typeof e.value==`number`?e.value.toLocaleString():String(e.value)})]})]})},t)})})]})}function i2(e,t,n){if(typeof t!=`object`||!t)return;let r=`payload`in t&&typeof t.payload==`object`&&t.payload!==null?t.payload:void 0,i=n;return n in t&&typeof t[n]==`string`?i=t[n]:r&&n in r&&typeof r[n]==`string`&&(i=r[n]),i in e?e[i]:e[n]}function a2(){let[e,t]=(0,v.useState)(Date.now);return(0,v.useEffect)(()=>{let e=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(e)},[]),e}function o2({children:e,title:t,description:n,action:r,onConfirm:i}){return(0,K.jsxs)(JD,{children:[(0,K.jsx)(YD,{asChild:!0,children:e}),(0,K.jsxs)(XD,{children:[(0,K.jsxs)(ZD,{children:[(0,K.jsx)($D,{children:t}),(0,K.jsx)(eO,{children:n})]}),(0,K.jsxs)(QD,{children:[(0,K.jsx)(nO,{children:`Cancel`}),(0,K.jsx)(tO,{onClick:i,children:r})]})]})]})}var s2=`min-w-0 rounded-2xl border border-border bg-card p-5 sm:p-6`,c2=`text-xs leading-relaxed text-muted-foreground`;function l2({title:e,description:t,eyebrow:n,children:r}){let[i,a]=(0,v.useState)([]),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let e=new AbortController;return W(`/api/devices`,e.signal).then(e=>{let t=e.devices.filter(e=>!e.disabled).map(e=>e.name);a(t),s(t.includes(e.defaultDevice)?e.defaultDevice:t[0]??``)}).catch(t=>{e.signal.aborted||l(t.message)}),()=>e.abort()},[]),(0,K.jsxs)(`div`,{className:`grid min-w-0 gap-6`,children:[(0,K.jsxs)(`header`,{className:`flex flex-wrap items-end justify-between gap-5 border-b border-border pb-6`,children:[(0,K.jsxs)(`div`,{className:`max-w-2xl`,children:[(0,K.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 font-mono text-[10px] uppercase tracking-[.18em] text-brand`,children:[(0,K.jsx)(rf,{size:14}),n]}),(0,K.jsx)(`h2`,{className:`text-2xl font-semibold tracking-tight sm:text-3xl`,children:e}),(0,K.jsx)(`p`,{className:`mt-3 max-w-xl text-sm leading-relaxed text-muted-foreground`,children:t})]}),(0,K.jsxs)(`div`,{className:`grid w-full gap-2 text-xs sm:w-60`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Vd,{size:14}),`Workspace router`]}),(0,K.jsx)(LA,{"aria-label":`Workspace router`,value:o,onValueChange:s,options:i.map(e=>({value:e,label:e}))})]})]}),c&&(0,K.jsx)(u2,{error:!0,children:c}),o?(0,K.jsx)(`div`,{className:`min-w-0`,children:r(o,i)},o):(0,K.jsx)(u2,{children:`Select a configured router to start.`})]})}function u2({children:e,error:t=!1}){return(0,K.jsx)(`div`,{role:t?`alert`:`note`,className:`rounded-xl border p-4 text-xs leading-relaxed ${t?`border-destructive/40 bg-destructive/5 text-destructive`:`border-border bg-background text-muted-foreground`}`,children:e})}function d2({labels:e,active:t}){return(0,K.jsx)(`ol`,{"aria-label":`Workflow steps`,className:`mb-5 flex flex-wrap gap-3 text-xs`,children:e.map((n,r)=>(0,K.jsxs)(`li`,{"aria-current":t===r?`step`:void 0,className:`flex items-center gap-2 ${r<=t?`text-brand`:`text-muted-foreground`}`,children:[(0,K.jsx)(`span`,{className:`flex size-6 items-center justify-center rounded-full border border-current font-mono text-[10px]`,children:r+1}),n,r<e.length-1&&(0,K.jsx)(Yc,{size:12})]},n))})}async function f2(e,t,n){let r=await vc(`${e}?device=${encodeURIComponent(t)}`,n);if(r.error)throw Error(r.error);return r}function p2(e,t,n){let r=URL.createObjectURL(new Blob([t],{type:n})),i=document.createElement(`a`);i.href=r,i.download=e,i.click(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}function m2({label:e,value:t,unit:n}){return(0,K.jsxs)(`div`,{className:`rounded-xl border border-border bg-background p-4`,children:[(0,K.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e}),(0,K.jsxs)(`p`,{className:`mt-2 flex items-baseline gap-2 font-mono text-2xl tabular-nums`,children:[t===null?`—`:t.toFixed(1),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:n})]})]})}function vbe({progress:e}){return(0,K.jsxs)(`div`,{className:`um-loading`,role:`status`,"aria-live":`polite`,children:[(0,K.jsxs)(`div`,{className:`um-loading-bars`,"aria-hidden":`true`,children:[(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{})]}),(0,K.jsx)(`h3`,{children:`Preparing your first saved report`}),(0,K.jsx)(`p`,{children:`Building the first cached snapshot in the background. You can leave this page; collection continues and the saved report survives server restarts.`}),e?.source===`sessions`&&e.total!=null?(0,K.jsxs)(`div`,{className:`grid w-full max-w-sm gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-sm tabular-nums`,children:[e.completed.toLocaleString(),` / `,e.total.toLocaleString(),` sessions verified`]}),(0,K.jsx)(`progress`,{className:`h-2 w-full accent-primary`,"aria-label":`Accounting collection`,max:Math.max(1,e.total),value:e.completed})]}):e?(0,K.jsxs)(`span`,{className:`text-sm text-muted-foreground`,children:[`Reading `,e.source,`…`]}):null,(0,K.jsx)(`small`,{children:`Only complete reports are shown. Slow or failed reads are reported, not counted as zero.`})]})}var h2={download:{label:`Download`,color:`var(--chart-1)`},upload:{label:`Upload`,color:`var(--chart-2)`},cumulativeDownload:{label:`Cumulative download`,color:`var(--chart-1)`},cumulativeUpload:{label:`Cumulative upload`,color:`var(--chart-2)`},sessions:{label:`Session starts`,color:`var(--chart-1)`}},g2=e=>e>=86400?`${(e/86400).toFixed(1)} days`:e>=3600?`${(e/3600).toFixed(1)} hrs`:`${Math.round(e/60)} min`,_2={users:`Users`,sessions:`Accounting sessions`,totals:`Live user counters`,profiles:`Profiles`,limitations:`Limitations`,assignments:`Profile assignments`,profileLimits:`Profile schedules`,routers:`NAS clients`,groups:`User groups`,settings:`Server settings`};function v2({title:e,eyebrow:t,children:n,className:r=``,extra:i}){return(0,K.jsxs)(`section`,{className:`um-card ${r}`,children:[(0,K.jsxs)(`header`,{className:`um-card-heading`,children:[(0,K.jsxs)(`div`,{children:[t&&(0,K.jsx)(`p`,{className:`um-kicker`,children:t}),(0,K.jsx)(`h3`,{children:e})]}),i]}),n]})}function ybe({device:e}){let[t,n]=(0,v.useState)(`30`),[r,i]=(0,v.useState)(``),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(0),[d,f]=(0,v.useState)(`daily`),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(null),_=h?.device===e&&h.status===`collecting`,y=p?.device===e?p:null,b=(0,v.useRef)(0),[x,S]=(0,v.useState)(``),[C,w]=(0,v.useState)(!0),T=!!r&&!!a&&r>a,E=JSON.stringify([e,t,s,r,a,l]),[D,O]=(0,v.useState)(E);D!==E&&(O(E),w(!0),S(``),g(null)),(0,v.useEffect)(()=>{if(!e||T)return;let n=new AbortController,i,o=new URLSearchParams({device:e,days:t,user:s,from:r,to:a}),c=async(t=!1)=>{let r=3e4,a=new AbortController,s=setTimeout(()=>a.abort(),15e3);try{let i=await W(`/api/aaa/reports?${o}${t?`&refresh=true`:``}`,AbortSignal.any([n.signal,a.signal]));if(!n.signal.aborted){if(i.device!==e)throw Error(`Report belongs to a different device.`);`status`in i?(g(i),S(i.status===`error`?i.error||`Report collection failed.`:``)):(m(i),g(null),S(``)),r=Math.max(1e3,i.refreshAfterMs)}}catch(e){n.signal.aborted||S(a.signal.aborted?`The dashboard did not respond within 15 seconds. Retrying shortly.`:e instanceof Error?e.message:`Report could not be loaded.`)}finally{clearTimeout(s),n.signal.aborted||(w(!1),i=setTimeout(()=>void c(),r))}};return c(l!==b.current),b.current=l,()=>{n.abort(),clearTimeout(i)}},[e,t,s,r,a,l,T]);let k=e=>{c(e)},A=y?.users.find(e=>e.name===s),j=y?.sources.sessions.available,M=y?.summary,N=y?Object.entries(y.sources).filter(([,e])=>!e.available):[],P=y?.users.reduce((e,t)=>Math.max(e,t.download+t.upload),1)??1,F=y?.series.reduce((e,t)=>Math.max(e,t.sessions),1)??1;return(0,K.jsxs)(`div`,{className:`um-reports`,children:[(0,K.jsxs)(`div`,{className:`um-intro`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`p`,{className:`um-kicker`,children:[(0,K.jsx)(rf,{size:13}),` ACCOUNTING INTELLIGENCE`]}),(0,K.jsxs)(`h2`,{children:[`Every connection.`,(0,K.jsx)(`br`,{}),(0,K.jsx)(`span`,{children:`A clearer picture.`})]}),(0,K.jsx)(`p`,{children:`From the whole network to one user. Explore traffic, connection statistics and the policies behind them.`})]}),(0,K.jsxs)(`div`,{className:`um-stamp`,children:[(0,K.jsx)(jd,{size:20}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:`Read-only reporting`}),(0,K.jsx)(`span`,{children:x||y?.cache?.error?`Router data unavailable`:y?`${y.cache?.refreshing?`Refreshing cached report`:y.cache?.stale?`Stale snapshot`:`Cached snapshot`} · ${new Date(y.collectedAt).toLocaleTimeString()}`:`Reading router accounting`}),(0,K.jsxs)(`small`,{children:[y?.cache?.persisted?`Saved snapshots`:`Cached snapshots`,` · adaptive background refresh · read-only`]})]})]})]}),(0,K.jsxs)(`div`,{className:`um-controls`,children:[(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`Report scope`}),(0,K.jsx)(LA,{"aria-label":`Report user`,value:s,onValueChange:k,options:[{value:``,label:`All users · network overview`},...(y?.users??(s?[{name:s}]:[])).map(e=>({value:e.name,label:e.name}))]})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`Period · session start date`}),(0,K.jsx)(LA,{"aria-label":`Report period`,value:t,onValueChange:e=>{n(e),i(``),o(``)},options:[{value:`7`,label:`Last 7 days`},{value:`30`,label:`Last 30 days`},{value:`90`,label:`Last 90 days`},{value:`365`,label:`Last year`},{value:`0`,label:`All retained history`}]})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`From`}),(0,K.jsx)(NA,{type:`date`,"aria-label":`From date`,value:r,max:a||void 0,onChange:e=>{i(e.target.value)}})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`Through`}),(0,K.jsx)(NA,{type:`date`,"aria-label":`Through date`,value:a,min:r||void 0,onChange:e=>{o(e.target.value)}})]}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(Nd,{}),loading:C&&!!e,disabled:T||!e||_,onClick:()=>u(e=>e+1),children:`Refresh`}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(tu,{}),disabled:!y||!j||T||!!x||C,onClick:()=>y&&p2(`user-manager-report.json`,JSON.stringify({...y,sessions:void 0,exportNote:`Statistics cover the full selected period. Individual session records are not included.`},null,2),`application/json`),children:`Export report`})]}),T&&(0,K.jsx)(EA,{type:`error`,children:`The start date must be on or before the end date.`}),(C||_||y?.cache?.refreshing)&&y&&(0,K.jsx)(`p`,{className:`um-caption`,role:`status`,children:C?`Updating report… The previous snapshot remains visible until the new filters have loaded.`:`Refreshing in the background… Showing the cached snapshot until collection completes.`}),y?.cache?.stale&&!x&&(0,K.jsxs)(EA,{type:`warning`,label:`Cached report`,children:[y.cache.error||`This snapshot is due for a background refresh.`,` Last collected:`,` `,new Date(y.collectedAt).toLocaleString(),`. Counters are not live.`]}),y?.cache?.persisted===!1&&(0,K.jsx)(EA,{type:`warning`,label:`Memory-only cache`,children:`This report could not be saved to disk. Check the dashboard storage path and permissions; an in-memory dashboard does not retain reports after restart.`}),x&&(0,K.jsxs)(EA,{type:`error`,label:`Report unavailable`,children:[x,`. Check router connectivity and retry. `,y&&`The snapshot below is stale.`]}),!e&&(0,K.jsx)(EA,{children:`Select a configured router to inspect User Manager.`}),(C||_)&&!x&&!y&&e&&(0,K.jsx)(vbe,{progress:h?.device===e?h.progress:void 0}),y&&!y.available&&(0,K.jsxs)(EA,{type:`warning`,label:`User Manager is unavailable`,children:[y.sources.users.error||`This router did not expose the User Manager menu. Check that the package is installed and your account can read it.`,` `,`RADIUS client management is still available in the other tabs.`]}),y?.available&&(0,K.jsxs)(K.Fragment,{children:[N.length>0&&(0,K.jsxs)(EA,{type:`warning`,label:`Partial report`,children:[N.map(([e])=>_2[e]).join(`, `),` could not be read. Missing sources are not zero usage; inspect source health below.`]}),(0,K.jsxs)(`div`,{className:`um-metrics`,children:[(0,K.jsxs)(`div`,{className:`um-metric um-download`,children:[(0,K.jsx)(zc,{}),(0,K.jsx)(`span`,{children:`Download accounted`}),(0,K.jsx)(`strong`,{children:j?ZO(M.download):`—`}),(0,K.jsx)(`small`,{children:`Sessions started in the selected period`})]}),(0,K.jsxs)(`div`,{className:`um-metric um-upload`,children:[(0,K.jsx)(Zc,{}),(0,K.jsx)(`span`,{children:`Upload accounted`}),(0,K.jsx)(`strong`,{children:j?ZO(M.upload):`—`}),(0,K.jsx)(`small`,{children:`From the user’s perspective`})]}),(0,K.jsxs)(`div`,{className:`um-metric`,children:[(0,K.jsx)(Fc,{}),(0,K.jsx)(`span`,{children:`Active now`}),(0,K.jsxs)(`strong`,{children:[M.active==null?`—`:$O(M.active),(0,K.jsx)(`em`,{children:`sessions`})]}),(0,K.jsx)(`small`,{children:`Monitor snapshot · independent of date filter`})]}),(0,K.jsxs)(`div`,{className:`um-metric`,children:[(0,K.jsx)(zl,{}),(0,K.jsx)(`span`,{children:`Connected time`}),(0,K.jsx)(`strong`,{children:j?g2(M.seconds):`—`}),(0,K.jsx)(`small`,{children:j?`${$O(M.sessions)} sessions · ${$O(M.users)} users in period`:`Accounting source unavailable`})]})]}),A&&(0,K.jsxs)(v2,{title:A.name,eyebrow:`INDIVIDUAL USER`,className:`um-focus`,extra:(0,K.jsx)(Z,{size:`sm`,ghost:!0,onClick:()=>k(``),children:`Back to all users`}),children:[(0,K.jsxs)(`div`,{className:`um-user-facts`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Account`}),(0,K.jsx)(`strong`,{children:A.configured?A.disabled?`Disabled`:`Enabled`:`Historical user`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Active profile`}),(0,K.jsx)(`strong`,{children:A.profile||`Not reported`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Group`}),(0,K.jsx)(`strong`,{children:A.group||`—`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Total download counter`}),(0,K.jsx)(`strong`,{children:A.totalDownload==null?`—`:ZO(A.totalDownload)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Total upload counter`}),(0,K.jsx)(`strong`,{children:A.totalUpload==null?`—`:ZO(A.totalUpload)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Total uptime counter`}),(0,K.jsx)(`strong`,{children:A.totalSeconds==null?`—`:g2(A.totalSeconds)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Shared users / sub-sessions`}),(0,K.jsxs)(`strong`,{children:[A.sharedUsers||`—`,` / `,A.subSessions??`—`]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Latest session start`}),(0,K.jsx)(`strong`,{children:A.latest||`—`})]})]}),A.comment&&(0,K.jsx)(`p`,{className:`um-caption`,children:A.comment}),(0,K.jsx)(`p`,{className:`um-caption`,children:`Live counters follow the router’s reset policy; they may differ from retained session totals. Neither is a billing ledger.`})]}),j?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`um-main-grid`,children:[(0,K.jsxs)(v2,{title:s?`${s} · traffic story`:`The traffic story`,eyebrow:`DOWNLOAD / UPLOAD`,extra:(0,K.jsx)(`div`,{className:`um-segment`,"aria-label":`Chart display`,children:[`daily`,`cumulative`].map(e=>(0,K.jsx)(`button`,{type:`button`,"aria-pressed":d===e,onClick:()=>f(e),children:e===`daily`?`By start day`:`Cumulative`},e))}),children:[(0,K.jsxs)(`div`,{className:`um-chart-legend`,children:[(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{className:`um-blue`}),`Download`]}),(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{className:`um-teal`}),`Upload`]}),(0,K.jsxs)(`span`,{children:[y.coverage.from,` — `,y.coverage.to]})]}),y.summary.sessions?(0,K.jsx)(t2,{config:h2,className:`um-traffic-chart`,children:(0,K.jsxs)($0,{accessibilityLayer:!0,data:y.series,margin:{left:6,right:12,top:12,bottom:0},children:[(0,K.jsx)($$,{vertical:!1}),(0,K.jsx)(W1,{dataKey:`day`,tickFormatter:e=>e.slice(5),minTickGap:32,tickLine:!1,axisLine:!1}),(0,K.jsx)(Y1,{tickFormatter:ZO,width:70,tickLine:!1,axisLine:!1}),(0,K.jsx)(n2,{content:(0,K.jsx)(r2,{formatter:(e,t)=>(0,K.jsxs)(`span`,{children:[h2[t]?.label||t,`:`,` `,ZO(Number(e))]})})}),(0,K.jsx)(x1,{type:`monotone`,dataKey:d===`daily`?`download`:`cumulativeDownload`,stroke:`var(--chart-1)`,fill:`var(--chart-1)`,fillOpacity:.15,strokeWidth:2,isAnimationActive:!1}),(0,K.jsx)(x1,{type:`monotone`,dataKey:d===`daily`?`upload`:`cumulativeUpload`,stroke:`var(--chart-2)`,fill:`var(--chart-2)`,fillOpacity:.12,strokeWidth:2,isAnimationActive:!1})]})}):(0,K.jsxs)(`div`,{className:`um-empty`,children:[(0,K.jsx)($l,{}),(0,K.jsx)(`h4`,{children:`No sessions in this period`}),(0,K.jsx)(`p`,{children:`Choose a wider period or another user. Accounting must be enabled on the NAS for sessions to be recorded.`})]}),(0,K.jsxs)(`p`,{className:`um-caption`,children:[`Session byte totals are grouped by the day the session `,(0,K.jsx)(`b`,{children:`started`}),` (`,y.clock.zone,`). A multi-day session is not split into daily consumption. These are bytes, not real-time speeds.`]})]}),(0,K.jsxs)(v2,{title:`Who’s using the network`,eyebrow:`USER BREAKDOWN`,className:`um-users-card`,extra:(0,K.jsx)(Wf,{size:17}),children:[(0,K.jsx)(`p`,{className:`um-caption`,children:`Select a user to focus every report.`}),(0,K.jsx)(`div`,{className:`um-user-list`,children:y.users.length?y.users.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`um-user-button`,"aria-pressed":s===e.name,onClick:()=>k(e.name),children:[(0,K.jsx)(`span`,{className:`um-user-rank`,children:String(t+1).padStart(2,`0`)}),(0,K.jsxs)(`span`,{className:`um-user-name`,children:[(0,K.jsx)(`strong`,{children:e.name}),(0,K.jsxs)(`small`,{children:[e.active==null?`Monitor unavailable`:e.active?`${e.active} active`:`No active sessions`,` `,`· `,$O(e.sessions),` in period`]}),(0,K.jsx)(`span`,{className:`um-user-meter`,children:(0,K.jsx)(`i`,{style:{width:`${Math.max(0,(e.download+e.upload)/P*100)}%`}})})]}),(0,K.jsxs)(`span`,{className:`um-user-bytes`,children:[ZO(e.download+e.upload),(0,K.jsx)(Yc,{size:12})]})]},e.name)):(0,K.jsx)(`p`,{className:`um-caption`,children:`No configured or historical users.`})})]})]}),(0,K.jsxs)(`div`,{className:`um-secondary-grid`,children:[(0,K.jsxs)(v2,{title:`When connections happen`,eyebrow:`STARTS BY HOUR`,children:[(0,K.jsx)(t2,{config:h2,className:`um-hour-chart`,children:(0,K.jsxs)(q0,{accessibilityLayer:!0,data:y.hours,children:[(0,K.jsx)(W1,{dataKey:`hour`,interval:5,tickLine:!1,axisLine:!1}),(0,K.jsx)(Y1,{allowDecimals:!1,width:38,tickLine:!1,axisLine:!1}),(0,K.jsx)(n2,{content:(0,K.jsx)(r2,{})}),(0,K.jsx)(I1,{dataKey:`sessions`,fill:`var(--chart-1)`,radius:[3,3,0,0],isAnimationActive:!1})]})}),(0,K.jsxs)(`p`,{className:`um-caption`,children:[`Router time · `,y.clock.zone]})]}),(0,K.jsx)(v2,{title:`How sessions ended`,eyebrow:`TERMINATION REASONS`,children:(0,K.jsx)(`div`,{className:`um-breakdown`,children:y.causes.length?y.causes.map(e=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:e.name}),(0,K.jsx)(`strong`,{children:$O(e.value)}),(0,K.jsx)(`meter`,{min:0,max:Math.max(1,y.summary.sessions),value:e.value,"aria-label":`${e.name}: ${e.value} sessions`})]},e.name)):(0,K.jsx)(`p`,{className:`um-caption`,children:`No closed sessions in the selected period.`})})}),(0,K.jsx)(v2,{title:`Access points of entry`,eyebrow:`NAS BREAKDOWN`,children:(0,K.jsx)(`div`,{className:`um-breakdown`,children:y.nas.length?y.nas.map(e=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:e.name}),(0,K.jsx)(`strong`,{children:$O(e.sessions)}),(0,K.jsxs)(`small`,{children:[`↓ `,ZO(e.download),` · ↑ `,ZO(e.upload)]})]},e.name)):(0,K.jsx)(`p`,{className:`um-caption`,children:`No NAS accounting in this period.`})})})]}),(0,K.jsxs)(v2,{title:`Connection calendar`,eyebrow:s||`ALL USERS`,extra:(0,K.jsxs)(`span`,{className:`um-caption`,children:[$O(y.summary.sessions),` starts`]}),children:[(0,K.jsx)(`div`,{className:`um-calendar`,role:`img`,"aria-label":`Daily session starts for ${s||`all users`}; exact daily data is available below and in Export report.`,children:y.series.map(e=>(0,K.jsx)(`div`,{className:`um-calendar-day`,style:{opacity:e.sessions?.3+.7*e.sessions/F:1},"data-active":e.sessions>0,title:`${e.day}: ${$O(e.sessions)} session starts · ↓ ${ZO(e.download)} · ↑ ${ZO(e.upload)}`},e.day))}),(0,K.jsxs)(`div`,{className:`um-calendar-labels`,children:[(0,K.jsx)(`span`,{children:y.coverage.from}),(0,K.jsx)(`span`,{children:`Less ▫ ▪ More`}),(0,K.jsx)(`span`,{children:y.coverage.to})]}),(0,K.jsxs)(`details`,{className:`um-details`,children:[(0,K.jsx)(`summary`,{children:`Daily data · accessible table`}),(0,K.jsx)(`div`,{className:`um-table-scroll`,children:(0,K.jsxs)(`table`,{children:[(0,K.jsx)(`thead`,{children:(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`th`,{children:`Date`}),(0,K.jsx)(`th`,{children:`Starts`}),(0,K.jsx)(`th`,{children:`Download`}),(0,K.jsx)(`th`,{children:`Upload`}),(0,K.jsx)(`th`,{children:`Uptime`})]})}),(0,K.jsx)(`tbody`,{children:y.series.map(e=>(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`td`,{children:e.day}),(0,K.jsx)(`td`,{children:$O(e.sessions)}),(0,K.jsx)(`td`,{children:ZO(e.download)}),(0,K.jsx)(`td`,{children:ZO(e.upload)}),(0,K.jsx)(`td`,{children:g2(e.seconds)})]},e.day))})]})})]})]})]}):(0,K.jsx)(EA,{type:`warning`,label:`Accounting unavailable`,children:`No charts are calculated from a failed read. Retry after checking the accounting source.`}),(0,K.jsxs)(v2,{title:s?`${s} · policy context`:`The policies behind the numbers`,eyebrow:`PROFILES, LIMITS & CONFIGURATION`,children:[(0,K.jsx)(`p`,{className:`um-caption`,children:`Configured limits and reset schedules are shown as reported. Remaining quota is not inferred from lifetime counters. Financial transactions and credentials are intentionally excluded.`}),(0,K.jsx)(`div`,{className:`um-inventory`,children:Object.entries(y.inventory).map(([e,t])=>(0,K.jsxs)(`details`,{className:`um-details`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{children:_2[e]}),(0,K.jsx)(`span`,{className:`um-count`,children:y.sources[e]?.available?t.length:`Unavailable`})]}),t.length?(0,K.jsx)(`div`,{className:`um-table-scroll`,children:(0,K.jsxs)(`table`,{children:[(0,K.jsx)(`thead`,{children:(0,K.jsx)(`tr`,{children:[...new Set(t.flatMap(e=>Object.keys(e)))].filter(e=>e!==`.id`).map(e=>(0,K.jsx)(`th`,{children:e.replaceAll(`-`,` `)},e))})}),(0,K.jsx)(`tbody`,{children:t.map((e,n)=>(0,K.jsx)(`tr`,{children:[...new Set(t.flatMap(e=>Object.keys(e)))].filter(e=>e!==`.id`).map(t=>(0,K.jsx)(`td`,{children:e[t]||`—`},t))},e[`.id`]||n))})]})}):(0,K.jsx)(`p`,{className:`um-empty-small`,children:y.sources[e]?.available?`No entries reported.`:y.sources[e]?.error||`Source not supported or not read.`})]},e))})]}),(0,K.jsxs)(`details`,{className:`um-source-health`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)($l,{size:14}),` Source health & accounting coverage`,` `,(0,K.jsxs)(`span`,{children:[$O(y.coverage.retained),` retained records`]})]}),(0,K.jsxs)(`p`,{children:[`Coverage begins `,y.coverage.first||`when accounting records arrive`,`. Deleted router sessions cannot be reconstructed.`,` `,y.coverage.undated>0&&`${$O(y.coverage.undated)} records have no valid start date and are excluded from period totals.`,` `,`This is a sequential snapshot, not an atomic capture. Collected in`,` `,(y.collectionMs/1e3).toFixed(1),`s; cached for 60 seconds, then refreshed in the background. Manual Refresh waits for a new collection.`]}),(0,K.jsx)(`div`,{className:`um-source-grid`,children:Object.entries(y.sources).map(([e,t])=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:_2[e]}),(0,K.jsx)(`span`,{children:t.available?`${$O(t.count)} records · read successfully${t.collectionMs==null?``:` · ${(t.collectionMs/1e3).toFixed(1)}s`}`:t.error||`Unsupported or not read`})]},e))})]})]})]})}function y2({...e}){return(0,K.jsx)(_g,{"data-slot":`dialog`,...e})}function bbe({...e}){return(0,K.jsx)(xg,{"data-slot":`dialog-portal`,...e})}function xbe({className:e,...t}){return(0,K.jsx)(Cg,{"data-slot":`dialog-overlay`,className:q(`fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0`,e),...t})}function b2({className:e,children:t,showCloseButton:n=!0,...r}){return(0,K.jsxs)(bbe,{"data-slot":`dialog-portal`,children:[(0,K.jsx)(xbe,{}),(0,K.jsxs)(Tg,{"data-slot":`dialog-content`,className:q(`fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg`,e),...r,children:[t,n&&(0,K.jsxs)(Pg,{"data-slot":`dialog-close`,className:`absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,K.jsx)(Qf,{}),(0,K.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function x2({className:e,...t}){return(0,K.jsx)(`div`,{"data-slot":`dialog-header`,className:q(`flex flex-col gap-2 text-center sm:text-left`,e),...t})}function S2({className:e,showCloseButton:t=!1,children:n,...r}){return(0,K.jsxs)(`div`,{"data-slot":`dialog-footer`,className:q(`flex flex-col-reverse gap-2 sm:flex-row sm:justify-end`,e),...r,children:[n,t&&(0,K.jsx)(Pg,{asChild:!0,children:(0,K.jsx)(Y,{variant:`outline`,children:`Close`})})]})}function C2({className:e,...t}){return(0,K.jsx)(Ag,{"data-slot":`dialog-title`,className:q(`text-lg leading-none font-semibold`,e),...t})}function w2({className:e,...t}){return(0,K.jsx)(Mg,{"data-slot":`dialog-description`,className:q(`text-sm text-muted-foreground`,e),...t})}function Sbe(){let e=new Uint8Array(16);for(;;){let t=``;for(;t.length<8;){crypto.getRandomValues(e);for(let n of e)if(n<201&&(t+=`ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%&*+-?`[n%67]),t.length===8)break}if(/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/[0-9]/.test(t)&&/[^A-Za-z0-9]/.test(t))return t}}function Cbe({user:e,onClose:t,onCloseAutoFocus:n}){return(0,K.jsx)(y2,{open:!0,onOpenChange:e=>{e||t()},children:(0,K.jsxs)(b2,{className:`max-h-[calc(100dvh-2rem)] gap-0 overflow-y-auto rounded-2xl p-0 sm:max-w-[540px] motion-reduce:animate-none`,onCloseAutoFocus:e=>{e.preventDefault(),n()},children:[(0,K.jsxs)(x2,{className:`gap-3 border-b border-border p-6 text-left sm:p-8`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(`span`,{className:`grid size-11 shrink-0 place-items-center rounded-xl border border-success/25 bg-success/10 text-success`,children:e.warning?(0,K.jsx)(If,{className:`size-5 text-warning`}):(0,K.jsx)(rf,{className:`size-5`})}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(`p`,{className:`mb-1 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground`,children:`User Manager · account receipt`}),(0,K.jsx)(C2,{className:`text-xl`,children:`User created`})]})]}),(0,K.jsx)(w2,{children:`Save the credentials below before closing this window.`}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,K.jsx)(kA,{children:e.device}),(0,K.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.warning?`Profile needs attention`:`Creation confirmed`})]})]}),(0,K.jsxs)(`div`,{className:`grid gap-5 p-6 sm:px-8`,children:[e.warning&&(0,K.jsx)(EA,{type:`warning`,label:`Check the profile`,children:e.warning}),(0,K.jsxs)(`div`,{className:`overflow-hidden rounded-xl border border-border bg-card`,children:[(0,K.jsxs)(`div`,{className:`border-b border-dashed border-border px-4 py-3`,children:[(0,K.jsx)(`p`,{className:`mb-1 text-xs text-muted-foreground`,children:`Username`}),(0,K.jsx)(`p`,{className:`select-text break-all font-mono text-lg font-semibold`,dir:`ltr`,children:e.name})]}),(0,K.jsxs)(`div`,{className:`grid gap-3 p-4`,children:[(0,K.jsxs)(`p`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,K.jsx)(Lu,{className:`size-3.5`}),`Password`]}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(`code`,{"aria-label":`Created user password`,dir:`ltr`,className:`select-text break-all text-2xl font-semibold tracking-wider text-brand`,children:e.password||`Not provided`}),e.password&&(0,K.jsx)(DO,{text:e.password,label:`Copy password`,title:`Copy password`,className:`shrink-0`})]}),(0,K.jsx)(`p`,{className:`text-xs leading-relaxed text-muted-foreground`,children:`This dashboard clears the password when you close this window. You cannot reveal it again here.`})]})]}),(0,K.jsx)(`dl`,{className:`grid grid-cols-2 gap-x-5 gap-y-4`,children:e.details.map(([e,t])=>(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(`dt`,{className:`mb-1 text-xs text-muted-foreground`,children:e}),(0,K.jsx)(`dd`,{className:`break-words text-sm font-medium`,children:t})]},e))})]}),(0,K.jsx)(S2,{className:`border-t border-border bg-card/50 px-6 py-4 sm:px-8`,children:(0,K.jsx)(Z,{type:`accent`,onClick:t,children:`Done`})})]})})}var T2=e=>(e.flags??``).includes(`X`)||e.disabled===`yes`;function wbe(e,t){return e[t.idKey]||e.name||e.address||e.user||`(row)`}var E2=`mb-3.5 rounded-md border border-border bg-card p-3.5`,D2=`mb-2.5 text-[13px] font-semibold`,O2=`grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-x-3.5 gap-y-2.5`,k2=`mt-3.5 flex items-center gap-2.5`,A2=`flex flex-col gap-1`,j2=`text-[11.5px] text-muted-foreground`;function Tbe(e,t){let[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(document.hidden),[c,l]=(0,v.useState)(Date.now),u=(0,v.useRef)(()=>{});(0,v.useEffect)(()=>{if(!t||!e)return;let n=new AbortController,i=!1,o=async()=>{if(l(Date.now()),!(i||document.hidden||n.signal.aborted)){i=!0;try{let t=await W(`/api/aaa/user-counters?device=${encodeURIComponent(e)}`,n.signal);if(n.signal.aborted)return;if(!t.available)throw Error(t.error||`User counters are unavailable.`);if(t.device!==e)throw Error(`Counters belong to a different device. Refresh to retry.`);r(t),a(null),l(Date.now())}catch(e){n.signal.aborted||a(e instanceof Error?e.message:`Unable to read user counters.`)}finally{i=!1}}};u.current=()=>{o()};let c=()=>{s(document.hidden),o()};document.addEventListener(`visibilitychange`,c);let d=setInterval(()=>{o()},5e3);return o(),()=>{n.abort(),clearInterval(d),document.removeEventListener(`visibilitychange`,c),u.current=()=>{}}},[e,t]);let d=n?.device===e?n:null;return{data:d,error:i,paused:o,rows:(0,v.useMemo)(()=>new Map(d?.rows.map(e=>[e.name,e])),[d]),stale:!!d&&(c-d.collectedAt>15e3||!!i),refresh:()=>u.current()}}function Ebe(e){let t=Math.floor(e),n=Math.floor(t/86400);return`${n?`${n}d `:``}${[Math.floor(t/3600)%24,Math.floor(t/60)%60,t%60].map(e=>String(e).padStart(2,`0`)).join(`:`)}`}function Dbe({device:e,value:t,onChange:n,disabled:r}){let[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(0);(0,v.useEffect)(()=>{let t=new AbortController;return W(`/api/aaa/list/um-profiles${e?`?device=${encodeURIComponent(e)}`:``}`,t.signal).then(e=>{if(!t.signal.aborted){if(!e.available)throw Error(`User Manager profiles are unavailable on this device.`);a(e.rows.filter(e=>e.name))}}).catch(e=>{t.signal.aborted||s(e instanceof Error?e.message:`Unable to load profiles.`)}),()=>t.abort()},[e,c]);let u=i?.find(e=>e.name===t);return(0,K.jsxs)(`div`,{className:`mb-3.5 grid gap-3 rounded-lg border border-brand/25 bg-brand/5 p-3.5 sm:grid-cols-2`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`div`,{className:`text-sm font-medium`,children:[`Initial profile `,(0,K.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`· optional`})]}),(0,K.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Assign a service profile as part of creating this user.`}),(0,K.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:`Profile rules apply when User Manager’s “Use profiles” setting is enabled.`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,K.jsx)(LA,{"aria-label":`Initial profile`,className:`w-full`,value:t,onValueChange:n,disabled:r||i===null||!!o,options:[{value:``,label:!i&&!o?`Loading profiles…`:`No profile — assign later`},...(i??[]).map(e=>({value:e.name,label:e.name}))]}),o?(0,K.jsxs)(`div`,{className:`text-xs text-destructive`,role:`alert`,children:[o,(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:r,onClick:()=>{a(null),s(null),l(e=>e+1)},className:`mt-2`,children:`Retry profiles`})]}):i?.length===0?(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No profiles yet. Create one in the Profiles tab, or continue without one.`}):u?(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[u.validity&&(0,K.jsxs)(K.Fragment,{children:[`Validity: `,u.validity,` · `]}),u[`starts-when`]===`first-auth`?`Starts on first authentication`:u[`starts-when`]===`assigned`?`Starts immediately when assigned`:`Uses the profile’s activation settings`]}):(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Existing users and profiles are not changed.`})]})]})}function M2({config:e,device:t}){let n=e.slug===`um-users`,r=Tbe(t,n),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(!1),[u,d]=(0,v.useState)(``),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)({}),[g,_]=(0,v.useState)(!1),[y,b]=(0,v.useState)(null),[x,S]=(0,v.useState)(``),C=(0,v.useRef)(null),w=(0,v.useRef)(null);(0,v.useEffect)(()=>()=>w.current?.abort(),[t]);let T=(0,v.useCallback)(()=>{let n=t?`?device=${encodeURIComponent(t)}`:``;return W(`/api/aaa/list/${e.slug}${n}`).then(e=>{a(e),s(null)}).catch(e=>{s(e instanceof Error?e.message:String(e))})},[e.slug,t]),E=`${e.slug}\0${t}`,[D,O]=(0,v.useState)(E);D!==E&&(O(E),a(null),s(null),p(null)),(0,v.useEffect)(()=>{T()},[T]);let k=(0,v.useCallback)(async(n,r)=>{l(!0),s(null);try{let i=await vc(`/api/aaa/${n}`,{device:t,slug:e.slug,...r}),a=n===`add`?`Entry added`:n===`update`?`Entry saved`:n===`remove`?`Entry removed`:n===`toggle`?r.enable?`Entry enabled`:`Entry disabled`:`Done`;if(n===`add`&&e.slug===`um-users`&&(i.ok||i.created)){let e=r.fields;b({device:t,name:e.name,password:e.password??``,warning:i.ok?void 0:i.message,details:[[`Initial profile`,e.profile?`${e.profile}${i.ok?``:` · unconfirmed`}`:`None assigned`],[`Group`,e.group||`Router default`],[`Shared users`,e[`shared-users`]||`Router default`],[`Status`,e.disabled===`yes`?`Disabled`:`Enabled`],...[`caller-id`,`attributes`,`comment`].filter(t=>e[t]).map(t=>[t===`caller-id`?`Caller ID`:t===`attributes`?`RADIUS attributes`:`Comment`,e[t]])]}),p(null),h({}),S(``)}return i.ok?(await T(),X.success(n===`add`&&e.slug===`um-users`?i.message:a),!0):(i.created&&(p(null),h({}),await T()),s(i.message),X.error(i.message||`${a} failed`),!1)}catch(e){return s(e instanceof Error?e.message:String(e)),X.error(e instanceof Error?e.message:`Action failed`),!1}finally{l(!1)}},[t,e.slug,T]),A=()=>{_(!1),p(`new`),h({}),S(``)},j=t=>{let n={};for(let r of e.fields)r.type!==`password`&&(r.key===`disabled`?n.disabled=T2(t)?`yes`:`no`:t[r.key]!=null&&(n[r.key]=t[r.key]));return n},M=t=>{_(!1),p(t[e.idKey]),h(j(t)),S(``)},N=async e=>{let n=new AbortController;w.current?.abort(),w.current=n,l(!0);let r=j(e),a=new Set((i?.rows??[]).map(e=>e.name)),o=1;for(r.name=`${e.name}-copy`;a.has(r.name);)r.name=`${e.name}-copy-${++o}`;let s=`Settings copied from ${e.name}. Choose a new name and password. Password, OTP and usage history are not copied.`;try{let i=await W(`/api/aaa/list/um-user-profiles?device=${encodeURIComponent(t)}`,n.signal);if(!i.available)throw Error(`Profiles unavailable`);let a=[...new Set(i.rows.filter(t=>t.user===e.name&&t.profile).map(e=>e.profile))];a.length===1?r.profile=a[0]:a.length>1&&(s+=` This user has multiple profiles; select one initial profile below.`)}catch{s+=` Profile assignments could not be read; select the initial profile yourself.`}finally{n.signal.aborted||(_(!1),h(r),S(s),p(`new`),l(!1))}},P=async()=>{if(n&&f===`new`&&(!m.name?.trim()||!m.password)){s(`Enter a name and password for the new user.`);return}(f===`new`?await k(`add`,{fields:m}):await k(`update`,{id:f,fields:m}))&&(p(null),h({}))},F=(0,v.useMemo)(()=>{let t=i?.rows??[],n=u.trim().toLowerCase();return n?t.filter(t=>e.columns.some(e=>(t[e.key]??``).toLowerCase().includes(n))):t},[i,u,e.columns]);return i&&!i.available?(0,K.jsxs)(EA,{type:`warning`,label:`User Manager not installed`,children:[`This device doesn't have the `,(0,K.jsx)(`code`,{children:`user-manager`}),` package. Install it (System → Packages) and reboot to manage the built-in RADIUS server here.`]}):(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2.5`,children:[(0,K.jsx)(NA,{className:`w-[200px]`,placeholder:`Filter…`,value:u,onChange:e=>d(e.target.value)}),(0,K.jsxs)(`span`,{className:`text-muted-foreground text-[11px]`,children:[F.length,` rows`]}),(0,K.jsx)(`span`,{className:`flex-1`}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(Nd,{}),onClick:()=>{T(),r.refresh()},children:`Refresh`}),(0,K.jsx)(Z,{ref:C,size:`sm`,type:`accent`,icon:(0,K.jsx)(Td,{}),disabled:c,onClick:A,children:`Add`})]}),n&&(0,K.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-border bg-card px-3 py-2 text-xs`,children:[(0,K.jsx)(`span`,{role:`status`,className:q(`font-medium`,r.stale||r.error?`text-warning`:`text-muted-foreground`),children:r.paused?`Updates paused`:r.error?`Counters unavailable`:r.stale?`Updates delayed`:r.data?`Live · 5s refresh`:`Reading counters…`}),r.data&&(0,K.jsxs)(`span`,{className:`text-muted-foreground`,children:[`Last read `,QO(r.data.collectedAt),r.stale?` · showing last known values`:``]}),(0,K.jsx)(`span`,{className:`basis-full text-muted-foreground`,children:`Cumulative User Manager totals, not the current connection only. Values update when the NAS sends RADIUS accounting; refresh does not reset counters.`}),r.error&&(0,K.jsx)(`span`,{role:`alert`,className:`basis-full text-warning`,children:r.error})]}),o&&(0,K.jsx)(EA,{type:`error`,className:`mb-2.5`,children:o}),f&&(0,K.jsxs)(`div`,{className:E2,children:[(0,K.jsx)(`div`,{className:D2,children:f===`new`?n?`New User Manager user`:`New ${e.slug}`:`Edit ${f}`}),x&&(0,K.jsx)(EA,{label:`Duplicate user`,className:`mb-3`,children:x}),f===`new`&&e.slug===`um-users`&&(0,K.jsx)(Dbe,{device:t,value:m.profile??``,onChange:e=>h(t=>({...t,profile:e})),disabled:c},t),(0,K.jsx)(`div`,{className:O2,children:e.fields.map(e=>n&&e.key===`password`?(0,K.jsx)(IO,{label:`Password${f===`new`?` *`:``}`,type:g?`text`:`password`,autoComplete:`new-password`,disabled:c,placeholder:f===`new`?`Enter or generate a password`:`(unchanged)`,value:m.password??``,onChange:e=>h(t=>({...t,password:e})),classNames:{label:j2,field:`h-9 rounded-xl`,input:`pr-20 text-[13px] leading-5`,rightIcon:`[&_button]:size-9`},rightIcon:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,disabled:c,"aria-label":g?`Hide password`:`Show password`,"aria-pressed":g,title:g?`Hide password`:`Show password`,className:`rounded-lg transition-colors hover:bg-brand/10 hover:text-brand focus-visible:outline-2 focus-visible:outline-ring focus-visible:-outline-offset-2 disabled:opacity-50`,onClick:()=>_(e=>!e),children:g?(0,K.jsx)(lu,{"aria-hidden":`true`}):(0,K.jsx)(du,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,disabled:c,"aria-label":`Generate 8-character password`,title:`Generate 8 characters: uppercase, lowercase, number and symbol`,className:`rounded-lg text-brand transition-colors hover:bg-brand/10 focus-visible:outline-2 focus-visible:outline-ring focus-visible:-outline-offset-2 disabled:opacity-50`,onClick:()=>{try{let e=Sbe();h(t=>({...t,password:e}))}catch{s(`Secure password generation is unavailable. Enter a password manually.`)}},children:(0,K.jsx)(ff,{"aria-hidden":`true`})})]})},e.key):(0,K.jsxs)(`label`,{className:A2,children:[(0,K.jsxs)(`span`,{className:j2,children:[e.label,e.required&&f===`new`?` *`:``]}),e.type===`bool`?(0,K.jsx)(LA,{disabled:c,value:m[e.key]??``,onValueChange:t=>h({...m,[e.key]:t}),options:[{value:``,label:`—`},{value:`no`,label:`no`},{value:`yes`,label:`yes`}]}):e.type===`select`?(0,K.jsx)(LA,{disabled:c,value:m[e.key]??``,onValueChange:t=>h({...m,[e.key]:t}),options:[{value:``,label:`—`},...(e.options??[]).map(e=>({value:e,label:e}))]}):(0,K.jsx)(NA,{disabled:c,type:e.type===`password`?`password`:e.type===`number`?`number`:`text`,placeholder:e.placeholder??(e.type===`password`?`(unchanged)`:``),value:m[e.key]??``,onChange:t=>h({...m,[e.key]:t.target.value})})]},e.key))}),(0,K.jsxs)(`div`,{className:k2,children:[(0,K.jsx)(Z,{size:`sm`,type:`accent`,loading:c,onClick:()=>void P(),children:f===`new`?`Create`:`Save`}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:c,onClick:()=>{p(null),h({}),S(``)},children:`Cancel`})]})]}),i?F.length===0?(0,K.jsx)(`div`,{className:`px-1 py-5 text-muted-foreground text-[11px]`,children:e.empty??`Nothing here yet.`}):(0,K.jsxs)(_O,{className:`text-[13px]`,children:[(0,K.jsx)(vO,{children:(0,K.jsxs)(bO,{children:[e.columns.map(e=>(0,K.jsx)(xO,{children:e.label},e.key)),n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(xO,{className:`text-right`,children:`Total connected time`}),(0,K.jsx)(xO,{className:`text-right text-chart-1`,children:`↓ Download`}),(0,K.jsx)(xO,{className:`text-right text-chart-2`,children:`↑ Upload`})]}),(0,K.jsx)(xO,{className:`text-right`,children:`Actions`})]})}),(0,K.jsx)(yO,{children:F.map(t=>{let i=t[e.idKey],a=T2(t),o=r.rows.get(t.name);return(0,K.jsxs)(bO,{children:[e.columns.map(e=>(0,K.jsx)(SO,{className:q(a&&`text-muted-foreground`),title:t[e.key]??``,children:e.key===`_status`?(0,K.jsx)(kA,{type:a?`secondary`:`success`,children:a?`disabled`:`enabled`}):n&&e.key===`name`?(0,K.jsxs)(`div`,{className:`grid gap-1`,children:[(0,K.jsx)(`span`,{className:`font-medium`,children:t.name}),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:o?.active==null?`Connection count unknown`:`${o.active} active connection${o.active===1?``:`s`}`})]}):t[e.key]??``},e.key)),n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(SO,{className:`text-right font-mono tabular-nums`,title:`Cumulative accounted connection time across this user's sessions`,children:o?.seconds==null?`—`:Ebe(o.seconds)}),(0,K.jsx)(SO,{className:`text-right font-mono tabular-nums text-chart-1`,title:`Total bytes downloaded by this user`,children:o?.download==null?`—`:ZO(o.download)}),(0,K.jsx)(SO,{className:`text-right font-mono tabular-nums text-chart-2`,title:`Total bytes uploaded by this user`,children:o?.upload==null?`—`:ZO(o.upload)})]}),(0,K.jsx)(SO,{className:`text-right`,children:(0,K.jsxs)(`span`,{className:`flex justify-end gap-1.5`,children:[n&&(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(ql,{}),disabled:c,"aria-label":`Duplicate ${t.name}`,title:`Copy settings into a new user`,onClick:()=>void N(t),children:`Duplicate`}),e.toggle&&(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:c,onClick:()=>void k(`toggle`,{id:i,enable:a}),children:a?`Enable`:`Disable`}),!e.addOnly&&(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:c,onClick:()=>M(t),children:`Edit`}),(0,K.jsx)(Z,{size:`sm`,type:`error`,ghost:!0,disabled:c,onClick:()=>void k(`remove`,{id:i}),children:`Remove`})]})})]},i||wbe(t,e))})})]}):!o&&(0,K.jsx)(`div`,{className:`text-muted-foreground text-[11px]`,role:`status`,children:`Loading…`}),y&&(0,K.jsx)(Cbe,{user:y,onClose:()=>b(null),onCloseAutoFocus:()=>C.current?.focus()})]})}function N2({device:e,getPath:t,setPath:n,fields:r,title:i,unwrap:a,extra:o}){let[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(!0),[p,m]=(0,v.useState)({}),[h,g]=(0,v.useState)(null),[_,y]=(0,v.useState)(!1),b=(0,v.useCallback)(()=>W(`${t}${e?`?device=${encodeURIComponent(e)}`:``}`).then(e=>{let{available:t,row:n}=a(e);f(t),c(n),m({}),u(``)}).catch(e=>{u(e instanceof Error?e.message:`Settings could not be read.`),c(null)}),[e,t,a]);(0,v.useEffect)(()=>{b()},[b]);let x=async()=>{y(!0),g(null);try{let t=await vc(n,{device:e,fields:p});g(t.message),t.ok?(await b(),X.success(`Settings saved`)):X.error(t.message||`Save failed`)}catch(e){X.error(e instanceof Error?e.message:`Save failed`)}finally{y(!1)}};return d?l?(0,K.jsxs)(EA,{type:`error`,label:i,children:[l,` `,(0,K.jsx)(Z,{size:`sm`,ghost:!0,onClick:()=>void b(),children:`Retry`})]}):s?(0,K.jsxs)(`div`,{className:E2,children:[(0,K.jsx)(`div`,{className:D2,children:i}),s&&(0,K.jsx)(`div`,{className:`mb-3 text-muted-foreground text-xs`,children:r.map(e=>`${e.label}: ${s[e.key]??`—`}`).join(` · `)}),(0,K.jsx)(`div`,{className:O2,children:r.map(e=>(0,K.jsxs)(`label`,{className:A2,children:[(0,K.jsx)(`span`,{className:j2,children:e.label}),e.type===`bool`?(0,K.jsx)(LA,{value:p[e.key]??``,onValueChange:t=>m({...p,[e.key]:t}),options:[{value:``,label:`(unchanged)`},{value:`no`,label:`no`},{value:`yes`,label:`yes`}]}):(0,K.jsx)(NA,{type:e.type===`number`?`number`:`text`,placeholder:e.placeholder??s?.[e.key]??``,value:p[e.key]??``,onChange:t=>m({...p,[e.key]:t.target.value})})]},e.key))}),(0,K.jsxs)(`div`,{className:k2,children:[(0,K.jsx)(Z,{size:`sm`,type:`accent`,loading:_,onClick:()=>void x(),children:`Save`}),o,h&&(0,K.jsx)(`span`,{className:`text-muted-foreground text-[11px]`,children:h})]})]}):(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:[`Loading `,i,`…`]}):(0,K.jsxs)(EA,{type:`warning`,label:`Not available`,children:[i,` is not available on this device.`]})}var Obe={slug:`radius`,idKey:`.id`,toggle:!0,columns:[{key:`address`,label:`Address`},{key:`service`,label:`Service`},{key:`authentication-port`,label:`Auth`},{key:`accounting-port`,label:`Acct`},{key:`protocol`,label:`Proto`},{key:`_status`,label:`Status`}],empty:`No RADIUS servers configured.`,fields:[{key:`address`,label:`Address`,required:!0,placeholder:`1.2.3.4 or host`},{key:`secret`,label:`Secret`,type:`password`,required:!0},{key:`service`,label:`Service`,required:!0,placeholder:`login,ppp,hotspot,wireless,dhcp,ipsec,dot1x`},{key:`authentication-port`,label:`Auth port`,type:`number`,placeholder:`1812`},{key:`accounting-port`,label:`Acct port`,type:`number`,placeholder:`1813`},{key:`timeout`,label:`Timeout`,placeholder:`300ms`},{key:`src-address`,label:`Src address`},{key:`realm`,label:`Realm`},{key:`called-id`,label:`Called ID`},{key:`domain`,label:`Domain`},{key:`protocol`,label:`Protocol`,type:`select`,options:[`udp`,`radsec`]},{key:`certificate`,label:`Certificate`},{key:`accounting-backup`,label:`Acct backup`,type:`bool`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},kbe={slug:`um-users`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared`},{key:`caller-id`,label:`Caller ID`},{key:`comment`,label:`Comment`},{key:`_status`,label:`Status`}],empty:`No RADIUS users.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`password`,label:`Password`,type:`password`,required:!0},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared users`,type:`number`,placeholder:`1`},{key:`attributes`,label:`RADIUS attributes`},{key:`caller-id`,label:`Caller ID (MAC)`},{key:`otp-secret`,label:`OTP secret`,type:`password`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},Abe={slug:`um-profiles`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`name-for-users`,label:`Display`},{key:`validity`,label:`Validity`},{key:`price`,label:`Price`},{key:`starts-when`,label:`Starts`}],empty:`No service profiles.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`name-for-users`,label:`Display name`},{key:`validity`,label:`Validity`,placeholder:`30d`},{key:`price`,label:`Price`,type:`number`},{key:`starts-when`,label:`Starts when`,type:`select`,options:[`assigned`,`first-auth`]},{key:`override-shared-users`,label:`Override shared-users`},{key:`comment`,label:`Comment`}]},jbe={slug:`um-limitations`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`rate-limit-rx`,label:`Rate ↓`},{key:`rate-limit-tx`,label:`Rate ↑`},{key:`transfer-limit`,label:`Transfer`},{key:`uptime-limit`,label:`Uptime`}],empty:`No limitation templates.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`rate-limit-rx`,label:`Download rate`,placeholder:`10M`},{key:`rate-limit-tx`,label:`Upload rate`,placeholder:`10M`},{key:`rate-limit-min-rx`,label:`Min download (CIR)`,placeholder:`2M`},{key:`rate-limit-min-tx`,label:`Min upload (CIR)`,placeholder:`2M`},{key:`rate-limit-burst-rx`,label:`Burst download`,placeholder:`20M`},{key:`rate-limit-burst-tx`,label:`Burst upload`,placeholder:`20M`},{key:`rate-limit-burst-threshold-rx`,label:`Burst thr. ↓`},{key:`rate-limit-burst-threshold-tx`,label:`Burst thr. ↑`},{key:`rate-limit-burst-time-rx`,label:`Burst time ↓`,placeholder:`10s`},{key:`rate-limit-burst-time-tx`,label:`Burst time ↑`,placeholder:`10s`},{key:`rate-limit-priority`,label:`Priority (1-8)`,type:`number`},{key:`download-limit`,label:`Download cap`,placeholder:`5G`},{key:`upload-limit`,label:`Upload cap`,placeholder:`5G`},{key:`transfer-limit`,label:`Total transfer cap`,placeholder:`10G`},{key:`uptime-limit`,label:`Uptime cap`,placeholder:`1d`},{key:`reset-counters-interval`,label:`Reset interval`},{key:`reset-counters-start-time`,label:`Reset start time`},{key:`comment`,label:`Comment`}]},Mbe={slug:`um-routers`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`address`,label:`Address`},{key:`coa-port`,label:`CoA port`},{key:`protocol`,label:`Proto`},{key:`comment`,label:`Comment`},{key:`_status`,label:`Status`}],empty:`No NAS clients registered.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`address`,label:`Address`,required:!0,placeholder:`192.168.88.1`},{key:`shared-secret`,label:`Shared secret`,type:`password`,required:!0},{key:`coa-port`,label:`CoA port`,type:`number`},{key:`protocol`,label:`Protocol`,placeholder:`radius`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},Nbe={slug:`um-user-profiles`,idKey:`.id`,addOnly:!0,columns:[{key:`user`,label:`User`},{key:`profile`,label:`Profile`},{key:`state`,label:`State`},{key:`end-time`,label:`Ends`}],empty:`No profile assignments.`,fields:[{key:`user`,label:`User`,required:!0},{key:`profile`,label:`Profile`,required:!0}]},Pbe=[{id:`reports`,label:`Reports & insights`},{id:`radius`,label:`RADIUS Servers`},{id:`users`,label:`Users`},{id:`profiles`,label:`Profiles`},{id:`limitations`,label:`Limitations`},{id:`nas`,label:`NAS Clients`},{id:`assignments`,label:`Assignments`},{id:`settings`,label:`Settings`}],Fbe=[{key:`accept`,label:`Accept CoA`,type:`bool`},{key:`port`,label:`CoA port`,type:`number`,placeholder:`3799`}],Ibe=[{key:`enabled`,label:`Enabled`,type:`bool`},{key:`use-profiles`,label:`Use profiles`,type:`bool`},{key:`certificate`,label:`Certificate`},{key:`authentication-port`,label:`Auth port`,type:`number`},{key:`accounting-port`,label:`Acct port`,type:`number`}];function Lbe(){let[e,t]=(0,v.useState)(``),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(!1),[o,s]=(0,v.useState)(null),c=(0,v.useCallback)(()=>W(`/api/usage/sampler`).then(e=>{r(e.intervalMs)}).catch(()=>{r(null)}),[]);(0,v.useEffect)(()=>{c()},[c]);let l=async()=>{let n=Number(e);if(!Number.isFinite(n)||n<=0){s(`Enter a positive number of minutes.`),X.error(`Enter a positive number of minutes`);return}a(!0),s(null);try{let e=await vc(`/api/usage/sampler`,{intervalMs:Math.round(n*6e4)});r(e.intervalMs),t(``),s(`Now sampling every ${P2(e.intervalMs)}.`),X.success(`Now sampling every ${P2(e.intervalMs)}`)}catch(e){s(e instanceof Error?e.message:String(e)),X.error(e instanceof Error?e.message:`Save failed`)}finally{a(!1)}};return(0,K.jsxs)(`div`,{className:`rounded-md border border-border bg-card p-3.5`,children:[(0,K.jsx)(`div`,{className:D2,children:`Usage sampling`}),(0,K.jsxs)(`div`,{className:`mb-3 text-muted-foreground text-xs`,children:[`How often client traffic + User Manager sessions are recorded into the usage history. Current: `,n==null?`…`:P2(n),` · default 1 minute · range 30s–6h.`]}),(0,K.jsx)(`div`,{className:O2,children:(0,K.jsxs)(`label`,{className:A2,children:[(0,K.jsx)(`span`,{className:j2,children:`Interval (minutes)`}),(0,K.jsx)(NA,{type:`number`,step:`0.5`,min:`0.5`,placeholder:n?String(n/6e4):`1`,value:e,onChange:e=>t(e.target.value)})]})}),(0,K.jsxs)(`div`,{className:k2,children:[(0,K.jsx)(Z,{size:`sm`,type:`accent`,loading:i,onClick:()=>void l(),children:`Save`}),[1,5,10,30].map(e=>(0,K.jsxs)(Z,{size:`sm`,ghost:!0,onClick:()=>{t(String(e))},children:[e,`m`]},e)),o&&(0,K.jsx)(`span`,{className:`text-muted-foreground text-[11px]`,children:o})]})]})}function P2(e){if(e<6e4)return`${Math.round(e/1e3)}s`;let t=e/6e4;return`${Number.isInteger(t)?t:t.toFixed(1)} min`}function Rbe(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(``),[i,a]=(0,v.useState)(`reports`);(0,v.useEffect)(()=>{W(`/api/devices`).then(e=>{t(e),r(t=>t||e.defaultDevice||e.devices[0]?.name||``)}).catch(()=>t({server:``,defaultDevice:``,devices:[]}))},[]);let o=e?.devices??[];return(0,K.jsxs)(`section`,{className:`grid content-start gap-[18px]`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`RADIUS & User Manager workspace`}),o.length>0?(0,K.jsx)(LA,{value:n,onValueChange:r,"aria-label":`Router`,options:o.map(e=>({value:e.name,label:`${e.name}${e.isDefault?` (default)`:``}`}))}):null]}),(0,K.jsxs)(Ok,{value:i,onValueChange:e=>a(e),children:[(0,K.jsx)(kk,{className:`mb-3.5 h-auto w-full flex-wrap justify-start border-b border-border`,children:Pbe.map(e=>(0,K.jsx)(Ak,{value:e.id,children:e.label},e.id))}),(0,K.jsx)(jk,{value:`radius`,children:(0,K.jsx)(M2,{config:Obe,device:n})}),(0,K.jsx)(jk,{value:`users`,children:(0,K.jsx)(M2,{config:kbe,device:n})}),(0,K.jsx)(jk,{value:`profiles`,children:(0,K.jsx)(M2,{config:Abe,device:n})}),(0,K.jsx)(jk,{value:`limitations`,children:(0,K.jsx)(M2,{config:jbe,device:n})}),(0,K.jsx)(jk,{value:`nas`,children:(0,K.jsx)(M2,{config:Mbe,device:n})}),(0,K.jsx)(jk,{value:`assignments`,children:(0,K.jsx)(M2,{config:Nbe,device:n})}),(0,K.jsx)(jk,{value:`reports`,children:(0,K.jsx)(ybe,{device:n},n)}),(0,K.jsx)(jk,{value:`settings`,children:(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(N2,{device:n,getPath:`/api/aaa/radius-incoming`,setPath:`/api/aaa/radius-incoming`,title:`RADIUS Incoming (CoA listener)`,fields:Fbe,unwrap:e=>({available:!0,row:e??{}}),extra:(0,K.jsx)(Z,{size:`sm`,ghost:!0,onClick:()=>void vc(`/api/aaa/radius-reset-counters`,{device:n}).then(()=>X.success(`Counters reset`)).catch(()=>X.error(`Reset counters failed`)),children:`Reset RADIUS counters`})}),(0,K.jsx)(N2,{device:n,getPath:`/api/aaa/um-settings`,setPath:`/api/aaa/um-settings`,title:`User Manager (built-in RADIUS server)`,fields:Ibe,unwrap:e=>{let t=e??{};return{available:t.available!==!1,row:t.settings??{}}}}),(0,K.jsx)(Lbe,{})]})})]},n)]})}function F2(e){let[t,n]=(0,v.useState)(``),[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(!0),[d,f]=(0,v.useState)(``),[p,m]=(0,v.useState)(Date.now),h=(0,v.useRef)(0),g=(0,v.useCallback)(()=>{h.current++},[]),_=e=>{g(),o(void 0),f(``),n(e)};(0,v.useEffect)(()=>{let e=!1;return W(`/api/devices`).then(t=>{e||(i(t.devices.map(e=>e.name)),n(t.devices.some(e=>e.name===t.defaultDevice)?t.defaultDevice:t.devices[0]?.name??``),u(!1))}).catch(()=>{e||(f(`Routers could not be loaded. Check the dashboard connection and retry.`),u(!1))}),()=>{e=!0,g()}},[g]);let y=(0,v.useCallback)(async()=>{if(!t)return;let n=++h.current;u(!0);try{let r=await W(`${e}?device=${encodeURIComponent(t)}`);n===h.current&&(o(r),m(Date.now()),f(``))}catch(e){n===h.current&&f(e instanceof Error?e.message:`Could not load this workspace.`)}finally{n===h.current&&u(!1)}},[t,e]);(0,v.useEffect)(()=>{let e=setTimeout(()=>void y(),0);return()=>{clearTimeout(e),g()}},[y,g]);async function b(n,r){if(!t||s)return;c(!0),f(``);let i=h.current;try{let a=await vc(`${e}${n}?device=${encodeURIComponent(t)}`,r);if(a.error)throw Error(a.error);if(i===h.current)return await y(),a}catch(e){i===h.current&&f(e instanceof Error?e.message:`Operation failed. Review the router state before retrying a write.`)}finally{c(!1)}}return{device:t,setDevice:_,devices:r,data:a,busy:s,loading:l,error:d,refresh:y,action:b,observedAt:p}}function I2({eyebrow:e,title:t,description:n,device:r,devices:i,onDevice:a,busy:o,onRefresh:s,children:c}){return(0,K.jsxs)(`header`,{className:`ops-header`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`ops-eyebrow`,children:e}),(0,K.jsx)(`h2`,{children:t}),(0,K.jsx)(`p`,{className:`ops-description`,children:n})]}),(0,K.jsxs)(`div`,{className:`ops-toolbar`,children:[(0,K.jsxs)(yA,{value:r,onValueChange:a,disabled:o||!i.length,children:[(0,K.jsxs)(bA,{"aria-label":`Workspace router`,children:[(0,K.jsx)(Vd,{size:16}),(0,K.jsx)(gA,{placeholder:`Select router`})]}),(0,K.jsx)(xA,{children:i.map(e=>(0,K.jsx)(vA,{value:e,children:e},e))})]}),(0,K.jsx)(Y,{variant:`outline`,onClick:s,disabled:o,"aria-label":`Refresh workspace`,children:(0,K.jsx)(Nd,{size:16})}),c]})]})}function L2({message:e}){return e?(0,K.jsxs)(`div`,{role:`alert`,className:`ops-notice ops-notice--error`,children:[(0,K.jsx)(If,{size:18}),(0,K.jsx)(`span`,{children:e})]}):null}function R2({children:e}){return(0,K.jsxs)(`div`,{className:`ops-notice`,children:[(0,K.jsx)(rf,{size:18}),(0,K.jsx)(`span`,{children:e})]})}function z2({state:e}){return(0,K.jsxs)(`span`,{className:`ops-state`,"data-state":e,children:[(0,K.jsx)(`i`,{"aria-hidden":`true`}),e.replaceAll(`-`,` `)]})}function B2(e){if(e===null)return`Unavailable`;let t=Math.max(0,Math.floor(e)),n=Math.floor(t/86400),r=[Math.floor(t/3600)%24,Math.floor(t/60)%60,t%60].map(e=>String(e).padStart(2,`0`)).join(`:`);return`${n?`${n}d `:``}${r}`}function zbe(){let[e,t]=(0,v.useState)([]),[n,r]=(0,v.useState)(``),[i,a]=(0,v.useState)(``),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0);return(0,v.useEffect)(()=>{let e=new AbortController;return W(`/api/devices`,e.signal).then(n=>{if(e.signal.aborted)return;let i=n.devices.filter(e=>!e.disabled).map(e=>e.name);t(i),r(i.includes(n.defaultDevice)?n.defaultDevice:i[0]??``),a(``),s(!0)}).catch(()=>{e.signal.aborted||(a(`Routers could not be loaded. Check the dashboard connection and retry.`),s(!0))}),()=>e.abort()},[c]),(0,K.jsxs)(`div`,{className:`ovpn-workspace`,children:[(0,K.jsxs)(`header`,{className:`ovpn-intro`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`span`,{className:`ovpn-eyebrow`,children:[(0,K.jsx)(Zu,{size:15}),` OPENVPN / LIVE CONNECTIONS`]}),(0,K.jsxs)(`h2`,{children:[`Who's connected`,(0,K.jsx)(`span`,{children:`to your network.`})]}),(0,K.jsx)(`p`,{children:`One connection per row. See who is here, how long they have stayed, and end a session when needed.`})]}),(0,K.jsxs)(`div`,{className:`ovpn-router`,children:[(0,K.jsx)(`label`,{htmlFor:`ovpn-router`,children:`Router`}),(0,K.jsxs)(yA,{value:n,onValueChange:r,disabled:!e.length,children:[(0,K.jsx)(bA,{id:`ovpn-router`,"aria-label":`OpenVPN router`,children:(0,K.jsx)(gA,{placeholder:`Select a router`})}),(0,K.jsx)(xA,{children:e.map(e=>(0,K.jsx)(vA,{value:e,children:e},e))})]}),(0,K.jsx)(`small`,{children:`Incoming OpenVPN connections only`})]})]}),i&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(L2,{message:i}),(0,K.jsx)(Y,{variant:`outline`,onClick:()=>l(e=>e+1),children:`Retry routers`})]}),n?(0,K.jsx)(Bbe,{device:n},n):!i&&(0,K.jsx)(`div`,{className:`ovpn-empty`,children:o?`No enabled routers. Add or enable a router in Devices to see its OpenVPN connections.`:`Loading routers…`})]})}function Bbe({device:e}){let[t,n]=(0,v.useState)(),[r,i]=(0,v.useState)(``),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(!0),[l,u]=(0,v.useState)(!1),[d,f]=(0,v.useState)(0),[p,m]=(0,v.useState)(Date.now),[h,g]=(0,v.useState)(``),[_,y]=(0,v.useState)(),[b,x]=(0,v.useState)(!1),S=(0,v.useRef)(!0),C=(0,v.useRef)(!1);(0,v.useEffect)(()=>{S.current=!0;let e=setInterval(()=>m(Date.now()),1e3);return()=>{S.current=!1,clearInterval(e)}},[]),(0,v.useEffect)(()=>{if(l||_)return;let t=new AbortController,r,a=async()=>{if(!document.hidden){c(!0);try{let r=await W(`/api/openvpn/sessions?device=${encodeURIComponent(e)}`,AbortSignal.any([t.signal,AbortSignal.timeout(15e3)]));t.signal.aborted||(n({data:r,receivedAt:Date.now()}),i(``),m(Date.now()))}catch(e){t.signal.aborted||i(e instanceof Error?e.message:`Router unavailable. Refresh to try again.`)}finally{t.signal.aborted||c(!1)}}t.signal.aborted||(r=setTimeout(()=>void a(),5e3))};return a(),()=>{t.abort(),clearTimeout(r)}},[e,d,l,_]);let w=t?.data,T=!!r||!t||p-t.receivedAt>15e3,E=!!_&&(!t||p-t.receivedAt>=55e3),D=T||!t?0:Math.max(0,Math.floor((p-t.receivedAt)/1e3)),O=w?.sessions??[],k=O.filter(e=>[e.name,e.address,e.callerId,e.sessionId].join(` `).toLowerCase().includes(h.trim().toLowerCase())),A=O.reduce((e,t)=>t.uptimeSeconds===null?e:Math.max(e??0,t.uptimeSeconds),null);function j(e){x(!1),o(``),y(e)}async function M(){if(_?.disconnectToken&&b&&!E&&!C.current){C.current=!0,u(!0),o(``);try{let t=await vc(`/api/openvpn/disconnect?device=${encodeURIComponent(e)}`,{token:_.disconnectToken,confirm:!0});S.current&&o(t.error??t.message??`No confirmation received. Refresh to check the current connection; do not retry automatically.`)}catch{S.current&&o(`Connection interrupted before confirmation. Refresh to check the router; the request will not be replayed.`)}finally{C.current=!1,S.current&&(u(!1),y(void 0),f(e=>e+1))}}}return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`section`,{className:`ovpn-summary`,"aria-label":`OpenVPN connection summary`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(Wf,{size:18}),(0,K.jsxs)(`span`,{children:[`Active connections`,(0,K.jsx)(`strong`,{children:w?O.length:`—`})]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(rf,{size:18}),(0,K.jsxs)(`span`,{children:[`Distinct users`,(0,K.jsx)(`strong`,{children:w?new Set(O.map(e=>e.name)).size:`—`})]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(zl,{size:18}),(0,K.jsxs)(`span`,{children:[`Longest connection`,(0,K.jsx)(`strong`,{children:A===null?`—`:B2(A+D)})]})]})]}),(0,K.jsxs)(`div`,{className:`ovpn-toolbar`,children:[(0,K.jsxs)(`div`,{className:`ovpn-search`,children:[(0,K.jsx)(qd,{size:16}),(0,K.jsx)(LO,{"aria-label":`Search OpenVPN connections`,placeholder:`Find a user, source or tunnel IP…`,value:h,onChange:e=>g(e.target.value)})]}),(0,K.jsxs)(`span`,{className:`ovpn-fresh`,"data-stale":T,children:[(0,K.jsx)(`i`,{}),t?T?`Last known connections · stale`:`Live · 5s refresh`:`Waiting for router`]}),(0,K.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:s||l||!!_,onClick:()=>f(e=>e+1),children:[(0,K.jsx)(Nd,{size:14,className:s?`animate-spin`:``}),` Refresh`]})]}),(0,K.jsx)(L2,{message:r}),a&&(0,K.jsx)(`div`,{className:`ovpn-notice`,role:`status`,children:a}),w&&(0,K.jsxs)(`p`,{className:`ovpn-caption`,children:[k.length,` of `,O.length,` connections · Router read`,` `,new Date(w.observedAt).toLocaleTimeString(),w.canDisconnect?``:` · Read-only access`,T?` · Times are frozen until the next successful read.`:` · Times advance between router reads.`]}),w?k.length===0?(0,K.jsxs)(`div`,{className:`ovpn-empty`,children:[(0,K.jsx)(Zu,{size:28}),(0,K.jsx)(`strong`,{children:O.length?`No matching connections`:`No active OpenVPN connections`}),(0,K.jsx)(`span`,{children:O.length?`Try another username or IP address.`:`No incoming OpenVPN sessions were reported by ${e} at the last read.`})]}):(0,K.jsx)(`section`,{className:`ovpn-list`,"aria-label":`Active OpenVPN connections`,children:k.map(e=>(0,K.jsxs)(`article`,{className:`ovpn-session`,children:[(0,K.jsxs)(`div`,{className:`ovpn-person`,children:[(0,K.jsx)(`span`,{className:`ovpn-avatar`,children:(0,K.jsx)(Zu,{size:20})}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:e.name}),(0,K.jsxs)(`small`,{children:[e.radius?`RADIUS authenticated`:`OpenVPN connection`,` · `,e.id]})]})]}),(0,K.jsxs)(`div`,{className:`ovpn-path`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`small`,{children:`Client source`}),(0,K.jsx)(`code`,{children:e.callerId||`Not reported`})]}),(0,K.jsx)(Yc,{size:16}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`small`,{children:`Tunnel IP`}),(0,K.jsx)(`code`,{children:e.address||`Not reported`})]})]}),(0,K.jsxs)(`div`,{className:`ovpn-duration`,children:[(0,K.jsxs)(`small`,{children:[(0,K.jsx)(zl,{size:13}),` Connected for`]}),(0,K.jsx)(`strong`,{children:B2(e.uptimeSeconds===null?null:e.uptimeSeconds+D)}),(0,K.jsx)(`span`,{children:e.encoding||`Encoding not reported`})]}),(0,K.jsxs)(Y,{variant:`outline`,size:`sm`,className:`ovpn-disconnect`,"aria-label":`Disconnect ${e.name} session ${e.id}`,title:e.disconnectToken?void 0:`Session identity or uptime is missing; disconnect is unavailable.`,disabled:T||l||!w.canDisconnect||!e.disconnectToken,onClick:()=>j(e),children:[(0,K.jsx)(Bf,{size:14}),` Disconnect`]})]},`${e.id}:${e.sessionId}`))}):(0,K.jsxs)(`div`,{className:`ovpn-empty`,children:[(0,K.jsx)(Fc,{size:26}),(0,K.jsx)(`strong`,{children:r?`Connection list unavailable`:`Reading active connections…`}),(0,K.jsx)(`span`,{children:r?`An unreachable router is not an empty connection list.`:`Reading runtime sessions, not user passwords or history.`})]}),(0,K.jsxs)(`p`,{className:`ovpn-footnote`,children:[(0,K.jsx)(rf,{size:15}),` Disconnect ends only the selected connection. It does not disable the account; the client may reconnect.`]}),(0,K.jsx)(y2,{open:!!_,onOpenChange:e=>{!e&&!l&&y(void 0)},children:(0,K.jsxs)(b2,{className:`ovpn-dialog`,showCloseButton:!l,children:[(0,K.jsxs)(x2,{children:[(0,K.jsx)(C2,{children:`Disconnect this connection?`}),(0,K.jsxs)(w2,{children:[`Only this OpenVPN session on `,e,` will be ended. Other connections for the same username are not selected.`]})]}),(0,K.jsx)(RO,{className:`ovpn-dialog-scroll`,children:_&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`dl`,{className:`ovpn-confirm-details`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`User`}),(0,K.jsx)(`dd`,{children:_.name})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Router`}),(0,K.jsx)(`dd`,{children:e})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Client source`}),(0,K.jsx)(`dd`,{children:_.callerId||`Not reported`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Tunnel IP`}),(0,K.jsx)(`dd`,{children:_.address||`Not reported`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Session`}),(0,K.jsxs)(`dd`,{children:[_.id,` · `,_.sessionId]})]})]}),(0,K.jsx)(`p`,{className:`ovpn-notice`,children:`If this is your management tunnel, you may lose access to this router. The client can reconnect with its existing credentials.`}),E&&(0,K.jsx)(`p`,{role:`alert`,className:`ovpn-notice`,children:`This selection expired. Close this dialog and select the current connection again.`}),(0,K.jsxs)(`label`,{className:`ovpn-consent`,children:[(0,K.jsx)(rO,{checked:b,onCheckedChange:e=>x(e===!0),disabled:l}),` `,`I want to disconnect this one connection.`]})]})}),(0,K.jsxs)(S2,{children:[(0,K.jsx)(Y,{variant:`outline`,disabled:l,onClick:()=>y(void 0),children:`Cancel`}),(0,K.jsx)(Y,{variant:`destructive`,disabled:!b||l||E,onClick:()=>void M(),children:l?`Disconnecting…`:`Disconnect connection`})]})]})})]})}var V2=new Set;function H2(e){return V2.add(e),()=>V2.delete(e)}function Vbe(e){for(let t of V2)t(e)}var U2=new Set;function W2(e){return U2.add(e),()=>U2.delete(e)}function Hbe(e){for(let t of U2)t(e)}function Ube(e,t){let n=(0,v.useRef)(e),r=(0,v.useRef)(t);(0,v.useLayoutEffect)(()=>{n.current=e,r.current=t},[e,t]),(0,v.useEffect)(()=>{let e=!1,t=null,i=null,a=()=>{t&&=(t.onopen=t.onerror=t.onmessage=t.onclose=null,t.close(),null),i&&=(i.close(),null)},o=()=>{e||(i=new EventSource(hc(`/api/sse`)),i.addEventListener(`hello`,()=>r.current(`sse`)),i.addEventListener(`tool`,e=>{try{n.current(JSON.parse(e.data))}catch{}}),i.onerror=()=>{i&&i.readyState===EventSource.CONNECTING&&r.current(`off`)})},s=()=>{if(e)return;let i=location.protocol===`https:`?`wss`:`ws`;t=new WebSocket(hc(`${i}://${location.host}/api/stream`));let a=!1;t.onopen=()=>{a=!0,r.current(`ws`)},t.onerror=()=>t?.close(),t.onmessage=e=>{try{let t=JSON.parse(e.data);t.type===`event`&&t.event&&n.current(t.event),t.type===`txn`&&t.update&&Vbe(t.update),t.type===`rollout`&&t.update&&Hbe(t.update)}catch{}},t.onclose=()=>{e||(r.current(`off`),a?setTimeout(s,2e3):o())}},c=()=>t?.readyState===WebSocket.OPEN||i?.readyState===EventSource.OPEN,l=()=>{e||c()||(a(),s())},u=()=>{document.visibilityState===`visible`&&l()};return s(),document.addEventListener(`visibilitychange`,u),window.addEventListener(`online`,l),()=>{e=!0,document.removeEventListener(`visibilitychange`,u),window.removeEventListener(`online`,l),a()}},[])}function Wbe(e){(0,v.useLayoutEffect)(()=>{let t=e.current;if(!t||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;document.documentElement.classList.add(`js-motion`);let n=new WeakSet,r=e=>{n.has(e)||(n.add(e),Ri.set(e,{opacity:0,y:26}),ic.create({trigger:e,start:`top 90%`,once:!0,onEnter:()=>Ri.to(e,{opacity:1,y:0,duration:.7,ease:`power3.out`})}))},i=e=>{for(let t of e.querySelectorAll(`.reveal`))r(t)};i(t);let a=new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&(e.matches(`.reveal`)&&r(e),i(e))});a.observe(t,{childList:!0,subtree:!0});let o=setInterval(()=>ic.refresh(),1200),s=setTimeout(()=>clearInterval(o),7e3);return()=>{a.disconnect(),clearInterval(o),clearTimeout(s);for(let e of ic.getAll())e.kill();document.documentElement.classList.remove(`js-motion`)}},[e])}var G2={completed:`success`,"completed-with-failures":`warning`,halted:`warning`,reverted:`secondary`,"needs-attention":`error`,aborted:`secondary`},Gbe={completed:`Every device applied the change.`,"completed-with-failures":`The rollout finished, but a gate failed along the way.`,halted:`Stopped at a failed gate. The devices already changed are still changed.`,reverted:`Stopped and put back — the fleet is where it started.`,"needs-attention":`A revert itself failed. Restore the flagged device(s) by hand from the snapshot named below.`,aborted:`A human stopped it; whatever had been applied was reverted.`},K2={pending:`bg-muted/30 text-muted-foreground`,applied:`bg-emerald-500/15 text-emerald-600 dark:text-emerald-400`,failed:`bg-red-500/15 text-red-600 dark:text-red-400`,reverted:`bg-amber-500/15 text-amber-600 dark:text-amber-400`,"revert-failed":`bg-red-500/25 text-red-600 dark:text-red-400 font-semibold`,skipped:`bg-muted/20 text-muted-foreground line-through`};function Kbe(e){let t=Date.now()-e;return t<6e4?`just now`:t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function qbe({rollout:e}){let t=t=>e.gates.find(e=>e.wave===t);return(0,K.jsx)(`div`,{className:`space-y-3`,children:e.waves.map(n=>{let r=t(n.index),i=n.devices.map(t=>e.devices.find(e=>e.device===t)).filter(e=>e!==void 0),a=e.outcome===void 0&&i.some(e=>e.stage===`pending`);return(0,K.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,K.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 text-sm`,children:[(0,K.jsxs)(`span`,{className:`font-medium`,children:[`Wave `,n.index+1,n.isCanary&&(0,K.jsx)(`span`,{className:`ml-2 rounded-sm bg-amber-500/15 px-1.5 py-0.5 text-xs text-amber-600 dark:text-amber-400`,children:`canary`})]}),(0,K.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.length,` device(s)`]}),a&&(0,K.jsx)(jA,{type:`warning`,pulse:!0}),r&&(0,K.jsxs)(kA,{type:r.ok?`success`:`error`,className:`ml-auto`,children:[`gate `,r.ok?`pass`:`fail`]})]}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:i.map(e=>(0,K.jsx)(`span`,{title:e.error??e.stage,className:q(`rounded-md px-2 py-1 font-mono text-xs`,K2[e.stage]??K2.pending),children:e.device},e.device))}),r&&!r.ok&&(0,K.jsxs)(`ul`,{className:`mt-2 space-y-1 text-xs text-red-600 dark:text-red-400`,children:[r.collateral&&(0,K.jsx)(`li`,{className:`font-medium`,children:`An UNTOUCHED device went dark — the change affected the wider fleet.`}),r.failures.map(e=>(0,K.jsxs)(`li`,{children:[e.device,`: `,e.reason]},e.device))]})]},n.index)})})}function Jbe({id:e,onClose:t}){let[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)([]),[o,s]=(0,v.useState)(!1),c=(0,v.useCallback)(()=>W(`/api/rollout/${encodeURIComponent(e)}`).then(e=>{r(e.rollout),a(e.events)}).catch(e=>{X.error(`Failed to load rollout: ${e instanceof Error?e.message:String(e)}`)}),[e]);(0,v.useEffect)(()=>(c(),W2(t=>{t.rolloutId===e&&c()})),[e,c]);let l=async t=>{s(!0);try{let n=await vc(`/api/rollout/${encodeURIComponent(e)}/${t}`,{});n.error?X.error(n.error):X.success(n.outcome??(t===`hold`?`Held`:`Done`)),await c()}finally{s(!1)}};if(!n)return(0,K.jsx)(wO,{title:`Rollout`,children:`Loading…`});let u=n.outcome===void 0,d=n.devices.filter(e=>e.stage===`failed`||e.stage===`revert-failed`);return(0,K.jsxs)(wO,{title:n.label?`${n.label} — ${n.id}`:n.id,extra:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[u&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z,{size:`sm`,type:`secondary`,disabled:o,onClick:()=>void l(`hold`),children:`Hold`}),(0,K.jsx)(Z,{size:`sm`,type:`secondary`,disabled:o,onClick:()=>void l(`resume`),children:`Resume`}),(0,K.jsx)(Z,{size:`sm`,type:`error`,disabled:o,onClick:()=>void l(`abort`),children:`Abort`})]}),(0,K.jsx)(Z,{size:`sm`,type:`secondary`,onClick:t,children:`Close`})]}),children:[(0,K.jsxs)(`div`,{className:q(`mb-4 rounded-md border p-3 text-sm`,n.outcome===`needs-attention`&&`border-red-500/40 bg-red-500/10`,n.outcome===`completed`&&`border-emerald-500/40 bg-emerald-500/10`,u&&`border-amber-500/40 bg-amber-500/10`),children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 font-medium`,children:[(0,K.jsx)(jA,{type:n.outcome?G2[n.outcome]:`warning`,pulse:u}),n.outcome??`IN FLIGHT — wave ${n.phase}`]}),(0,K.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:n.outcome?Gbe[n.outcome]:`Applying wave by wave; each wave is gated and soaked before the next.`})]}),(0,K.jsx)(qbe,{rollout:n}),d.length>0&&(0,K.jsxs)(`div`,{className:`mt-4 rounded-md border border-red-500/40 p-3 text-sm`,children:[(0,K.jsx)(`div`,{className:`font-medium`,children:`Failures`}),(0,K.jsx)(`ul`,{className:`mt-1 space-y-1 font-mono text-xs text-muted-foreground`,children:d.map(e=>(0,K.jsxs)(`li`,{children:[e.device,` · `,e.stage,e.error?` — ${e.error}`:``,e.stage===`revert-failed`&&e.snapshotId?` · restore with diff_config_snapshots ${e.snapshotId} live`:``]},e.device))})]}),n.notes.length>0&&(0,K.jsx)(`ul`,{className:`mt-4 space-y-1 text-sm text-amber-600 dark:text-amber-400`,children:n.notes.map(e=>(0,K.jsxs)(`li`,{children:[`• `,e]},e))}),(0,K.jsx)(`h4`,{className:`mt-6 mb-2 text-sm font-medium`,children:`Commands`}),(0,K.jsx)(`pre`,{className:`overflow-x-auto rounded-md bg-muted/30 p-2 font-mono text-xs`,children:n.commands.join(`
237
+ `)}}):null}var n2=dZ;function r2({active:e,payload:t,className:n,indicator:r=`dot`,hideLabel:i=!1,hideIndicator:a=!1,label:o,labelFormatter:s,labelClassName:c,formatter:l,color:u,nameKey:d,labelKey:f}){let{config:p}=gbe(),m=v.useMemo(()=>{if(i||!t?.length)return null;let[e]=t,n=e?.dataKey,r=String(f??(typeof n==`function`?void 0:n)??e?.name??`value`),a=i2(p,e,r),l=!f&&typeof o==`string`?p[o]?.label??o:a?.label;return s?(0,K.jsx)(`div`,{className:q(`font-medium`,c),children:s(l,t)}):l?(0,K.jsx)(`div`,{className:q(`font-medium`,c),children:l}):null},[o,s,t,i,c,p,f]);if(!e||!t?.length)return null;let h=t.length===1&&r!==`dot`;return(0,K.jsxs)(`div`,{className:q(`grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl`,n),children:[h?null:m,(0,K.jsx)(`div`,{className:`grid gap-1.5`,children:t.filter(e=>e.type!==`none`).map((e,t)=>{let n=String(d??e.name??(typeof e.dataKey==`function`?void 0:e.dataKey)??`value`),i=i2(p,e,n),o=u??e.payload?.fill??e.color;return(0,K.jsx)(`div`,{className:q(`flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground`,r===`dot`&&`items-center`),children:l&&e?.value!==void 0&&e.name?l(e.value,e.name,e,t,e.payload):(0,K.jsxs)(K.Fragment,{children:[i?.icon?(0,K.jsx)(i.icon,{}):!a&&(0,K.jsx)(`div`,{className:q(`shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)`,{"h-2.5 w-2.5":r===`dot`,"w-1":r===`line`,"w-0 border-[1.5px] border-dashed bg-transparent":r===`dashed`,"my-0.5":h&&r===`dashed`}),style:{"--color-bg":o,"--color-border":o}}),(0,K.jsxs)(`div`,{className:q(`flex flex-1 justify-between leading-none`,h?`items-end`:`items-center`),children:[(0,K.jsxs)(`div`,{className:`grid gap-1.5`,children:[h?m:null,(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:i?.label??e.name})]}),e.value!=null&&(0,K.jsx)(`span`,{className:`font-mono font-medium text-foreground tabular-nums`,children:typeof e.value==`number`?e.value.toLocaleString():String(e.value)})]})]})},t)})})]})}function i2(e,t,n){if(typeof t!=`object`||!t)return;let r=`payload`in t&&typeof t.payload==`object`&&t.payload!==null?t.payload:void 0,i=n;return n in t&&typeof t[n]==`string`?i=t[n]:r&&n in r&&typeof r[n]==`string`&&(i=r[n]),i in e?e[i]:e[n]}function a2(){let[e,t]=(0,v.useState)(Date.now);return(0,v.useEffect)(()=>{let e=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(e)},[]),e}function o2({children:e,title:t,description:n,action:r,onConfirm:i}){return(0,K.jsxs)(JD,{children:[(0,K.jsx)(YD,{asChild:!0,children:e}),(0,K.jsxs)(XD,{children:[(0,K.jsxs)(ZD,{children:[(0,K.jsx)($D,{children:t}),(0,K.jsx)(eO,{children:n})]}),(0,K.jsxs)(QD,{children:[(0,K.jsx)(nO,{children:`Cancel`}),(0,K.jsx)(tO,{onClick:i,children:r})]})]})]})}var s2=`min-w-0 rounded-2xl border border-border bg-card p-5 sm:p-6`,c2=`text-xs leading-relaxed text-muted-foreground`;function l2({title:e,description:t,eyebrow:n,children:r}){let[i,a]=(0,v.useState)([]),[o,s]=(0,v.useState)(``),[c,l]=(0,v.useState)(``);return(0,v.useEffect)(()=>{let e=new AbortController;return W(`/api/devices`,e.signal).then(e=>{let t=e.devices.filter(e=>!e.disabled).map(e=>e.name);a(t),s(t.includes(e.defaultDevice)?e.defaultDevice:t[0]??``)}).catch(t=>{e.signal.aborted||l(t.message)}),()=>e.abort()},[]),(0,K.jsxs)(`div`,{className:`grid min-w-0 gap-6`,children:[(0,K.jsxs)(`header`,{className:`flex flex-wrap items-end justify-between gap-5 border-b border-border pb-6`,children:[(0,K.jsxs)(`div`,{className:`max-w-2xl`,children:[(0,K.jsxs)(`p`,{className:`mb-2 flex items-center gap-2 font-mono text-[10px] uppercase tracking-[.18em] text-brand`,children:[(0,K.jsx)(rf,{size:14}),n]}),(0,K.jsx)(`h2`,{className:`text-2xl font-semibold tracking-tight sm:text-3xl`,children:e}),(0,K.jsx)(`p`,{className:`mt-3 max-w-xl text-sm leading-relaxed text-muted-foreground`,children:t})]}),(0,K.jsxs)(`div`,{className:`grid w-full gap-2 text-xs sm:w-60`,children:[(0,K.jsxs)(`span`,{className:`flex items-center gap-2`,children:[(0,K.jsx)(Vd,{size:14}),`Workspace router`]}),(0,K.jsx)(LA,{"aria-label":`Workspace router`,value:o,onValueChange:s,options:i.map(e=>({value:e,label:e}))})]})]}),c&&(0,K.jsx)(u2,{error:!0,children:c}),o?(0,K.jsx)(`div`,{className:`min-w-0`,children:r(o,i)},o):(0,K.jsx)(u2,{children:`Select a configured router to start.`})]})}function u2({children:e,error:t=!1}){return(0,K.jsx)(`div`,{role:t?`alert`:`note`,className:`rounded-xl border p-4 text-xs leading-relaxed ${t?`border-destructive/40 bg-destructive/5 text-destructive`:`border-border bg-background text-muted-foreground`}`,children:e})}function d2({labels:e,active:t}){return(0,K.jsx)(`ol`,{"aria-label":`Workflow steps`,className:`mb-5 flex flex-wrap gap-3 text-xs`,children:e.map((n,r)=>(0,K.jsxs)(`li`,{"aria-current":t===r?`step`:void 0,className:`flex items-center gap-2 ${r<=t?`text-brand`:`text-muted-foreground`}`,children:[(0,K.jsx)(`span`,{className:`flex size-6 items-center justify-center rounded-full border border-current font-mono text-[10px]`,children:r+1}),n,r<e.length-1&&(0,K.jsx)(Yc,{size:12})]},n))})}async function f2(e,t,n){let r=await vc(`${e}?device=${encodeURIComponent(t)}`,n);if(r.error)throw Error(r.error);return r}function p2(e,t,n){let r=URL.createObjectURL(new Blob([t],{type:n})),i=document.createElement(`a`);i.href=r,i.download=e,i.click(),setTimeout(()=>URL.revokeObjectURL(r),1e3)}function m2({label:e,value:t,unit:n}){return(0,K.jsxs)(`div`,{className:`rounded-xl border border-border bg-background p-4`,children:[(0,K.jsx)(`span`,{className:`text-[11px] text-muted-foreground`,children:e}),(0,K.jsxs)(`p`,{className:`mt-2 flex items-baseline gap-2 font-mono text-2xl tabular-nums`,children:[t===null?`—`:t.toFixed(1),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:n})]})]})}function vbe({progress:e}){return(0,K.jsxs)(`div`,{className:`um-loading`,role:`status`,"aria-live":`polite`,children:[(0,K.jsxs)(`div`,{className:`um-loading-bars`,"aria-hidden":`true`,children:[(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{}),(0,K.jsx)(`i`,{})]}),(0,K.jsx)(`h3`,{children:`Preparing your first saved report`}),(0,K.jsx)(`p`,{children:`Building the first cached snapshot in the background. You can leave this page; collection continues and the saved report survives server restarts.`}),e?.source===`sessions`&&e.total!=null?(0,K.jsxs)(`div`,{className:`grid w-full max-w-sm gap-2`,children:[(0,K.jsxs)(`span`,{className:`text-sm tabular-nums`,children:[e.completed.toLocaleString(),` / `,e.total.toLocaleString(),` sessions verified`]}),(0,K.jsx)(`progress`,{className:`h-2 w-full accent-primary`,"aria-label":`Accounting collection`,max:Math.max(1,e.total),value:e.completed})]}):e?(0,K.jsxs)(`span`,{className:`text-sm text-muted-foreground`,children:[`Reading `,e.source,`…`]}):null,(0,K.jsx)(`small`,{children:`Only complete reports are shown. Slow or failed reads are reported, not counted as zero.`})]})}var h2={download:{label:`Download`,color:`var(--chart-1)`},upload:{label:`Upload`,color:`var(--chart-2)`},cumulativeDownload:{label:`Cumulative download`,color:`var(--chart-1)`},cumulativeUpload:{label:`Cumulative upload`,color:`var(--chart-2)`},sessions:{label:`Session starts`,color:`var(--chart-1)`}},g2=e=>e>=86400?`${(e/86400).toFixed(1)} days`:e>=3600?`${(e/3600).toFixed(1)} hrs`:`${Math.round(e/60)} min`,_2={users:`Users`,sessions:`Accounting sessions`,totals:`Live user counters`,profiles:`Profiles`,limitations:`Limitations`,assignments:`Profile assignments`,profileLimits:`Profile schedules`,routers:`NAS clients`,groups:`User groups`,settings:`Server settings`};function v2({title:e,eyebrow:t,children:n,className:r=``,extra:i}){return(0,K.jsxs)(`section`,{className:`um-card ${r}`,children:[(0,K.jsxs)(`header`,{className:`um-card-heading`,children:[(0,K.jsxs)(`div`,{children:[t&&(0,K.jsx)(`p`,{className:`um-kicker`,children:t}),(0,K.jsx)(`h3`,{children:e})]}),i]}),n]})}function ybe({device:e}){let[t,n]=(0,v.useState)(`30`),[r,i]=(0,v.useState)(``),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(``),[l,u]=(0,v.useState)(0),[d,f]=(0,v.useState)(`daily`),[p,m]=(0,v.useState)(null),[h,g]=(0,v.useState)(null),_=h?.device===e&&h.status===`collecting`,y=p?.device===e?p:null,b=(0,v.useRef)(0),[x,S]=(0,v.useState)(``),[C,w]=(0,v.useState)(!0),T=!!r&&!!a&&r>a,E=JSON.stringify([e,t,s,r,a,l]),[D,O]=(0,v.useState)(E);D!==E&&(O(E),w(!0),S(``),g(null)),(0,v.useEffect)(()=>{if(!e||T)return;let n=new AbortController,i,o=new URLSearchParams({device:e,days:t,user:s,from:r,to:a}),c=async(t=!1)=>{let r=3e4,a=new AbortController,s=setTimeout(()=>a.abort(),15e3);try{let i=await W(`/api/aaa/reports?${o}${t?`&refresh=true`:``}`,AbortSignal.any([n.signal,a.signal]));if(!n.signal.aborted){if(i.device!==e)throw Error(`Report belongs to a different device.`);`status`in i?(g(i),S(i.status===`error`?i.error||`Report collection failed.`:``)):(m(i),g(null),S(``)),r=Math.max(1e3,i.refreshAfterMs)}}catch(e){n.signal.aborted||S(a.signal.aborted?`The dashboard did not respond within 15 seconds. Retrying shortly.`:e instanceof Error?e.message:`Report could not be loaded.`)}finally{clearTimeout(s),n.signal.aborted||(w(!1),i=setTimeout(()=>void c(),r))}};return c(l!==b.current),b.current=l,()=>{n.abort(),clearTimeout(i)}},[e,t,s,r,a,l,T]);let k=e=>{c(e)},A=y?.users.find(e=>e.name===s),j=y?.sources.sessions.available,M=y?.summary,N=y?Object.entries(y.sources).filter(([,e])=>!e.available):[],P=y?.users.reduce((e,t)=>Math.max(e,t.download+t.upload),1)??1,F=y?.series.reduce((e,t)=>Math.max(e,t.sessions),1)??1;return(0,K.jsxs)(`div`,{className:`um-reports`,children:[(0,K.jsxs)(`div`,{className:`um-intro`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`p`,{className:`um-kicker`,children:[(0,K.jsx)(rf,{size:13}),` ACCOUNTING INTELLIGENCE`]}),(0,K.jsxs)(`h2`,{children:[`Every connection.`,(0,K.jsx)(`br`,{}),(0,K.jsx)(`span`,{children:`A clearer picture.`})]}),(0,K.jsx)(`p`,{children:`From the whole network to one user. Explore traffic, connection statistics and the policies behind them.`})]}),(0,K.jsxs)(`div`,{className:`um-stamp`,children:[(0,K.jsx)(jd,{size:20}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:`Read-only reporting`}),(0,K.jsx)(`span`,{children:x||y?.cache?.error?`Router data unavailable`:y?`${y.cache?.refreshing?`Refreshing cached report`:y.cache?.stale?`Stale snapshot`:`Cached snapshot`} · ${new Date(y.collectedAt).toLocaleTimeString()}`:`Reading router accounting`}),(0,K.jsxs)(`small`,{children:[y?.cache?.persisted?`Saved snapshots`:`Cached snapshots`,` · adaptive background refresh · read-only`]})]})]})]}),(0,K.jsxs)(`div`,{className:`um-controls`,children:[(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`Report scope`}),(0,K.jsx)(LA,{"aria-label":`Report user`,value:s,onValueChange:k,options:[{value:``,label:`All users · network overview`},...(y?.users??(s?[{name:s}]:[])).map(e=>({value:e.name,label:e.name}))]})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`Period · session start date`}),(0,K.jsx)(LA,{"aria-label":`Report period`,value:t,onValueChange:e=>{n(e),i(``),o(``)},options:[{value:`7`,label:`Last 7 days`},{value:`30`,label:`Last 30 days`},{value:`90`,label:`Last 90 days`},{value:`365`,label:`Last year`},{value:`0`,label:`All retained history`}]})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`From`}),(0,K.jsx)(NA,{type:`date`,"aria-label":`From date`,value:r,max:a||void 0,onChange:e=>{i(e.target.value)}})]}),(0,K.jsxs)(`label`,{children:[(0,K.jsx)(`span`,{children:`Through`}),(0,K.jsx)(NA,{type:`date`,"aria-label":`Through date`,value:a,min:r||void 0,onChange:e=>{o(e.target.value)}})]}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(Nd,{}),loading:C&&!!e,disabled:T||!e||_,onClick:()=>u(e=>e+1),children:`Refresh`}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(tu,{}),disabled:!y||!j||T||!!x||C,onClick:()=>y&&p2(`user-manager-report.json`,JSON.stringify({...y,sessions:void 0,exportNote:`Statistics cover the full selected period. Individual session records are not included.`},null,2),`application/json`),children:`Export report`})]}),T&&(0,K.jsx)(EA,{type:`error`,children:`The start date must be on or before the end date.`}),(C||_||y?.cache?.refreshing)&&y&&(0,K.jsx)(`p`,{className:`um-caption`,role:`status`,children:C?`Updating report… The previous snapshot remains visible until the new filters have loaded.`:`Refreshing in the background… Showing the cached snapshot until collection completes.`}),y?.cache?.stale&&!x&&(0,K.jsxs)(EA,{type:`warning`,label:`Cached report`,children:[y.cache.error||`This snapshot is due for a background refresh.`,` Last collected:`,` `,new Date(y.collectedAt).toLocaleString(),`. Counters are not live.`]}),y?.cache?.persisted===!1&&(0,K.jsx)(EA,{type:`warning`,label:`Memory-only cache`,children:`This report could not be saved to disk. Check the dashboard storage path and permissions; an in-memory dashboard does not retain reports after restart.`}),x&&(0,K.jsxs)(EA,{type:`error`,label:`Report unavailable`,children:[x,`. Check router connectivity and retry. `,y&&`The snapshot below is stale.`]}),!e&&(0,K.jsx)(EA,{children:`Select a configured router to inspect User Manager.`}),(C||_)&&!x&&!y&&e&&(0,K.jsx)(vbe,{progress:h?.device===e?h.progress:void 0}),y&&!y.available&&(0,K.jsxs)(EA,{type:`warning`,label:`User Manager is unavailable`,children:[y.sources.users.error||`This router did not expose the User Manager menu. Check that the package is installed and your account can read it.`,` `,`RADIUS client management is still available in the other tabs.`]}),y?.available&&(0,K.jsxs)(K.Fragment,{children:[N.length>0&&(0,K.jsxs)(EA,{type:`warning`,label:`Partial report`,children:[N.map(([e])=>_2[e]).join(`, `),` could not be read. Missing sources are not zero usage; inspect source health below.`]}),(0,K.jsxs)(`div`,{className:`um-metrics`,children:[(0,K.jsxs)(`div`,{className:`um-metric um-download`,children:[(0,K.jsx)(zc,{}),(0,K.jsx)(`span`,{children:`Download accounted`}),(0,K.jsx)(`strong`,{children:j?ZO(M.download):`—`}),(0,K.jsx)(`small`,{children:`Sessions started in the selected period`})]}),(0,K.jsxs)(`div`,{className:`um-metric um-upload`,children:[(0,K.jsx)(Zc,{}),(0,K.jsx)(`span`,{children:`Upload accounted`}),(0,K.jsx)(`strong`,{children:j?ZO(M.upload):`—`}),(0,K.jsx)(`small`,{children:`From the user’s perspective`})]}),(0,K.jsxs)(`div`,{className:`um-metric`,children:[(0,K.jsx)(Fc,{}),(0,K.jsx)(`span`,{children:`Active now`}),(0,K.jsxs)(`strong`,{children:[M.active==null?`—`:$O(M.active),(0,K.jsx)(`em`,{children:`sessions`})]}),(0,K.jsx)(`small`,{children:`Monitor snapshot · independent of date filter`})]}),(0,K.jsxs)(`div`,{className:`um-metric`,children:[(0,K.jsx)(zl,{}),(0,K.jsx)(`span`,{children:`Connected time`}),(0,K.jsx)(`strong`,{children:j?g2(M.seconds):`—`}),(0,K.jsx)(`small`,{children:j?`${$O(M.sessions)} sessions · ${$O(M.users)} users in period`:`Accounting source unavailable`})]})]}),A&&(0,K.jsxs)(v2,{title:A.name,eyebrow:`INDIVIDUAL USER`,className:`um-focus`,extra:(0,K.jsx)(Z,{size:`sm`,ghost:!0,onClick:()=>k(``),children:`Back to all users`}),children:[(0,K.jsxs)(`div`,{className:`um-user-facts`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Account`}),(0,K.jsx)(`strong`,{children:A.configured?A.disabled?`Disabled`:`Enabled`:`Historical user`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Active profile`}),(0,K.jsx)(`strong`,{children:A.profile||`Not reported`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Group`}),(0,K.jsx)(`strong`,{children:A.group||`—`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Total download counter`}),(0,K.jsx)(`strong`,{children:A.totalDownload==null?`—`:ZO(A.totalDownload)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Total upload counter`}),(0,K.jsx)(`strong`,{children:A.totalUpload==null?`—`:ZO(A.totalUpload)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Total uptime counter`}),(0,K.jsx)(`strong`,{children:A.totalSeconds==null?`—`:g2(A.totalSeconds)})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Shared users / sub-sessions`}),(0,K.jsxs)(`strong`,{children:[A.sharedUsers||`—`,` / `,A.subSessions??`—`]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:`Latest session start`}),(0,K.jsx)(`strong`,{children:A.latest||`—`})]})]}),A.comment&&(0,K.jsx)(`p`,{className:`um-caption`,children:A.comment}),(0,K.jsx)(`p`,{className:`um-caption`,children:`Live counters follow the router’s reset policy; they may differ from retained session totals. Neither is a billing ledger.`})]}),j?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`div`,{className:`um-main-grid`,children:[(0,K.jsxs)(v2,{title:s?`${s} · traffic story`:`The traffic story`,eyebrow:`DOWNLOAD / UPLOAD`,extra:(0,K.jsx)(`div`,{className:`um-segment`,"aria-label":`Chart display`,children:[`daily`,`cumulative`].map(e=>(0,K.jsx)(`button`,{type:`button`,"aria-pressed":d===e,onClick:()=>f(e),children:e===`daily`?`By start day`:`Cumulative`},e))}),children:[(0,K.jsxs)(`div`,{className:`um-chart-legend`,children:[(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{className:`um-blue`}),`Download`]}),(0,K.jsxs)(`span`,{children:[(0,K.jsx)(`i`,{className:`um-teal`}),`Upload`]}),(0,K.jsxs)(`span`,{children:[y.coverage.from,` — `,y.coverage.to]})]}),y.summary.sessions?(0,K.jsx)(t2,{config:h2,className:`um-traffic-chart`,children:(0,K.jsxs)($0,{accessibilityLayer:!0,data:y.series,margin:{left:6,right:12,top:12,bottom:0},children:[(0,K.jsx)($$,{vertical:!1}),(0,K.jsx)(W1,{dataKey:`day`,tickFormatter:e=>e.slice(5),minTickGap:32,tickLine:!1,axisLine:!1}),(0,K.jsx)(Y1,{tickFormatter:ZO,width:70,tickLine:!1,axisLine:!1}),(0,K.jsx)(n2,{content:(0,K.jsx)(r2,{formatter:(e,t)=>(0,K.jsxs)(`span`,{children:[h2[t]?.label||t,`:`,` `,ZO(Number(e))]})})}),(0,K.jsx)(x1,{type:`monotone`,dataKey:d===`daily`?`download`:`cumulativeDownload`,stroke:`var(--chart-1)`,fill:`var(--chart-1)`,fillOpacity:.15,strokeWidth:2,isAnimationActive:!1}),(0,K.jsx)(x1,{type:`monotone`,dataKey:d===`daily`?`upload`:`cumulativeUpload`,stroke:`var(--chart-2)`,fill:`var(--chart-2)`,fillOpacity:.12,strokeWidth:2,isAnimationActive:!1})]})}):(0,K.jsxs)(`div`,{className:`um-empty`,children:[(0,K.jsx)($l,{}),(0,K.jsx)(`h4`,{children:`No sessions in this period`}),(0,K.jsx)(`p`,{children:`Choose a wider period or another user. Accounting must be enabled on the NAS for sessions to be recorded.`})]}),(0,K.jsxs)(`p`,{className:`um-caption`,children:[`Session byte totals are grouped by the day the session `,(0,K.jsx)(`b`,{children:`started`}),` (`,y.clock.zone,`). A multi-day session is not split into daily consumption. These are bytes, not real-time speeds.`]})]}),(0,K.jsxs)(v2,{title:`Who’s using the network`,eyebrow:`USER BREAKDOWN`,className:`um-users-card`,extra:(0,K.jsx)(Wf,{size:17}),children:[(0,K.jsx)(`p`,{className:`um-caption`,children:`Select a user to focus every report.`}),(0,K.jsx)(`div`,{className:`um-user-list`,children:y.users.length?y.users.map((e,t)=>(0,K.jsxs)(`button`,{type:`button`,className:`um-user-button`,"aria-pressed":s===e.name,onClick:()=>k(e.name),children:[(0,K.jsx)(`span`,{className:`um-user-rank`,children:String(t+1).padStart(2,`0`)}),(0,K.jsxs)(`span`,{className:`um-user-name`,children:[(0,K.jsx)(`strong`,{children:e.name}),(0,K.jsxs)(`small`,{children:[e.active==null?`Monitor unavailable`:e.active?`${e.active} active`:`No active sessions`,` `,`· `,$O(e.sessions),` in period`]}),(0,K.jsx)(`span`,{className:`um-user-meter`,children:(0,K.jsx)(`i`,{style:{width:`${Math.max(0,(e.download+e.upload)/P*100)}%`}})})]}),(0,K.jsxs)(`span`,{className:`um-user-bytes`,children:[ZO(e.download+e.upload),(0,K.jsx)(Yc,{size:12})]})]},e.name)):(0,K.jsx)(`p`,{className:`um-caption`,children:`No configured or historical users.`})})]})]}),(0,K.jsxs)(`div`,{className:`um-secondary-grid`,children:[(0,K.jsxs)(v2,{title:`When connections happen`,eyebrow:`STARTS BY HOUR`,children:[(0,K.jsx)(t2,{config:h2,className:`um-hour-chart`,children:(0,K.jsxs)(q0,{accessibilityLayer:!0,data:y.hours,children:[(0,K.jsx)(W1,{dataKey:`hour`,interval:5,tickLine:!1,axisLine:!1}),(0,K.jsx)(Y1,{allowDecimals:!1,width:38,tickLine:!1,axisLine:!1}),(0,K.jsx)(n2,{content:(0,K.jsx)(r2,{})}),(0,K.jsx)(I1,{dataKey:`sessions`,fill:`var(--chart-1)`,radius:[3,3,0,0],isAnimationActive:!1})]})}),(0,K.jsxs)(`p`,{className:`um-caption`,children:[`Router time · `,y.clock.zone]})]}),(0,K.jsx)(v2,{title:`How sessions ended`,eyebrow:`TERMINATION REASONS`,children:(0,K.jsx)(`div`,{className:`um-breakdown`,children:y.causes.length?y.causes.map(e=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:e.name}),(0,K.jsx)(`strong`,{children:$O(e.value)}),(0,K.jsx)(`meter`,{min:0,max:Math.max(1,y.summary.sessions),value:e.value,"aria-label":`${e.name}: ${e.value} sessions`})]},e.name)):(0,K.jsx)(`p`,{className:`um-caption`,children:`No closed sessions in the selected period.`})})}),(0,K.jsx)(v2,{title:`Access points of entry`,eyebrow:`NAS BREAKDOWN`,children:(0,K.jsx)(`div`,{className:`um-breakdown`,children:y.nas.length?y.nas.map(e=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`span`,{children:e.name}),(0,K.jsx)(`strong`,{children:$O(e.sessions)}),(0,K.jsxs)(`small`,{children:[`↓ `,ZO(e.download),` · ↑ `,ZO(e.upload)]})]},e.name)):(0,K.jsx)(`p`,{className:`um-caption`,children:`No NAS accounting in this period.`})})})]}),(0,K.jsxs)(v2,{title:`Connection calendar`,eyebrow:s||`ALL USERS`,extra:(0,K.jsxs)(`span`,{className:`um-caption`,children:[$O(y.summary.sessions),` starts`]}),children:[(0,K.jsx)(`div`,{className:`um-calendar`,role:`img`,"aria-label":`Daily session starts for ${s||`all users`}; exact daily data is available below and in Export report.`,children:y.series.map(e=>(0,K.jsx)(`div`,{className:`um-calendar-day`,style:{opacity:e.sessions?.3+.7*e.sessions/F:1},"data-active":e.sessions>0,title:`${e.day}: ${$O(e.sessions)} session starts · ↓ ${ZO(e.download)} · ↑ ${ZO(e.upload)}`},e.day))}),(0,K.jsxs)(`div`,{className:`um-calendar-labels`,children:[(0,K.jsx)(`span`,{children:y.coverage.from}),(0,K.jsx)(`span`,{children:`Less ▫ ▪ More`}),(0,K.jsx)(`span`,{children:y.coverage.to})]}),(0,K.jsxs)(`details`,{className:`um-details`,children:[(0,K.jsx)(`summary`,{children:`Daily data · accessible table`}),(0,K.jsx)(`div`,{className:`um-table-scroll`,children:(0,K.jsxs)(`table`,{children:[(0,K.jsx)(`thead`,{children:(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`th`,{children:`Date`}),(0,K.jsx)(`th`,{children:`Starts`}),(0,K.jsx)(`th`,{children:`Download`}),(0,K.jsx)(`th`,{children:`Upload`}),(0,K.jsx)(`th`,{children:`Uptime`})]})}),(0,K.jsx)(`tbody`,{children:y.series.map(e=>(0,K.jsxs)(`tr`,{children:[(0,K.jsx)(`td`,{children:e.day}),(0,K.jsx)(`td`,{children:$O(e.sessions)}),(0,K.jsx)(`td`,{children:ZO(e.download)}),(0,K.jsx)(`td`,{children:ZO(e.upload)}),(0,K.jsx)(`td`,{children:g2(e.seconds)})]},e.day))})]})})]})]})]}):(0,K.jsx)(EA,{type:`warning`,label:`Accounting unavailable`,children:`No charts are calculated from a failed read. Retry after checking the accounting source.`}),(0,K.jsxs)(v2,{title:s?`${s} · policy context`:`The policies behind the numbers`,eyebrow:`PROFILES, LIMITS & CONFIGURATION`,children:[(0,K.jsx)(`p`,{className:`um-caption`,children:`Configured limits and reset schedules are shown as reported. Remaining quota is not inferred from lifetime counters. Financial transactions and credentials are intentionally excluded.`}),(0,K.jsx)(`div`,{className:`um-inventory`,children:Object.entries(y.inventory).map(([e,t])=>(0,K.jsxs)(`details`,{className:`um-details`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)(`span`,{children:_2[e]}),(0,K.jsx)(`span`,{className:`um-count`,children:y.sources[e]?.available?t.length:`Unavailable`})]}),t.length?(0,K.jsx)(`div`,{className:`um-table-scroll`,children:(0,K.jsxs)(`table`,{children:[(0,K.jsx)(`thead`,{children:(0,K.jsx)(`tr`,{children:[...new Set(t.flatMap(e=>Object.keys(e)))].filter(e=>e!==`.id`).map(e=>(0,K.jsx)(`th`,{children:e.replaceAll(`-`,` `)},e))})}),(0,K.jsx)(`tbody`,{children:t.map((e,n)=>(0,K.jsx)(`tr`,{children:[...new Set(t.flatMap(e=>Object.keys(e)))].filter(e=>e!==`.id`).map(t=>(0,K.jsx)(`td`,{children:e[t]||`—`},t))},e[`.id`]||n))})]})}):(0,K.jsx)(`p`,{className:`um-empty-small`,children:y.sources[e]?.available?`No entries reported.`:y.sources[e]?.error||`Source not supported or not read.`})]},e))})]}),(0,K.jsxs)(`details`,{className:`um-source-health`,children:[(0,K.jsxs)(`summary`,{children:[(0,K.jsx)($l,{size:14}),` Source health & accounting coverage`,` `,(0,K.jsxs)(`span`,{children:[$O(y.coverage.retained),` retained records`]})]}),(0,K.jsxs)(`p`,{children:[`Coverage begins `,y.coverage.first||`when accounting records arrive`,`. Deleted router sessions cannot be reconstructed.`,` `,y.coverage.undated>0&&`${$O(y.coverage.undated)} records have no valid start date and are excluded from period totals.`,` `,`This is a sequential snapshot, not an atomic capture. Collected in`,` `,(y.collectionMs/1e3).toFixed(1),`s; cached for 60 seconds, then refreshed in the background. Manual Refresh waits for a new collection.`]}),(0,K.jsx)(`div`,{className:`um-source-grid`,children:Object.entries(y.sources).map(([e,t])=>(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`strong`,{children:_2[e]}),(0,K.jsx)(`span`,{children:t.available?`${$O(t.count)} records · read successfully${t.collectionMs==null?``:` · ${(t.collectionMs/1e3).toFixed(1)}s`}`:t.error||`Unsupported or not read`})]},e))})]})]})]})}function y2({...e}){return(0,K.jsx)(_g,{"data-slot":`dialog`,...e})}function bbe({...e}){return(0,K.jsx)(xg,{"data-slot":`dialog-portal`,...e})}function xbe({className:e,...t}){return(0,K.jsx)(Cg,{"data-slot":`dialog-overlay`,className:q(`fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0`,e),...t})}function b2({className:e,children:t,showCloseButton:n=!0,...r}){return(0,K.jsxs)(bbe,{"data-slot":`dialog-portal`,children:[(0,K.jsx)(xbe,{}),(0,K.jsxs)(Tg,{"data-slot":`dialog-content`,className:q(`fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg`,e),...r,children:[t,n&&(0,K.jsxs)(Pg,{"data-slot":`dialog-close`,className:`absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,children:[(0,K.jsx)(Qf,{}),(0,K.jsx)(`span`,{className:`sr-only`,children:`Close`})]})]})]})}function x2({className:e,...t}){return(0,K.jsx)(`div`,{"data-slot":`dialog-header`,className:q(`flex flex-col gap-2 text-center sm:text-left`,e),...t})}function S2({className:e,showCloseButton:t=!1,children:n,...r}){return(0,K.jsxs)(`div`,{"data-slot":`dialog-footer`,className:q(`flex flex-col-reverse gap-2 sm:flex-row sm:justify-end`,e),...r,children:[n,t&&(0,K.jsx)(Pg,{asChild:!0,children:(0,K.jsx)(Y,{variant:`outline`,children:`Close`})})]})}function C2({className:e,...t}){return(0,K.jsx)(Ag,{"data-slot":`dialog-title`,className:q(`text-lg leading-none font-semibold`,e),...t})}function w2({className:e,...t}){return(0,K.jsx)(Mg,{"data-slot":`dialog-description`,className:q(`text-sm text-muted-foreground`,e),...t})}function Sbe(){let e=new Uint8Array(16);for(;;){let t=``;for(;t.length<8;){crypto.getRandomValues(e);for(let n of e)if(n<201&&(t+=`ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%&*+-?`[n%67]),t.length===8)break}if(/[A-Z]/.test(t)&&/[a-z]/.test(t)&&/[0-9]/.test(t)&&/[^A-Za-z0-9]/.test(t))return t}}function Cbe({user:e,onClose:t,onCloseAutoFocus:n}){return(0,K.jsx)(y2,{open:!0,onOpenChange:e=>{e||t()},children:(0,K.jsxs)(b2,{className:`max-h-[calc(100dvh-2rem)] gap-0 overflow-y-auto rounded-2xl p-0 sm:max-w-[540px] motion-reduce:animate-none`,onCloseAutoFocus:e=>{e.preventDefault(),n()},children:[(0,K.jsxs)(x2,{className:`gap-3 border-b border-border p-6 text-left sm:p-8`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,K.jsx)(`span`,{className:`grid size-11 shrink-0 place-items-center rounded-xl border border-success/25 bg-success/10 text-success`,children:e.warning?(0,K.jsx)(If,{className:`size-5 text-warning`}):(0,K.jsx)(rf,{className:`size-5`})}),(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(`p`,{className:`mb-1 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground`,children:`User Manager · account receipt`}),(0,K.jsx)(C2,{className:`text-xl`,children:`User created`})]})]}),(0,K.jsx)(w2,{children:`Save the credentials below before closing this window.`}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,K.jsx)(kA,{children:e.device}),(0,K.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:e.warning?`Profile needs attention`:`Creation confirmed`})]})]}),(0,K.jsxs)(`div`,{className:`grid gap-5 p-6 sm:px-8`,children:[e.warning&&(0,K.jsx)(EA,{type:`warning`,label:`Check the profile`,children:e.warning}),(0,K.jsxs)(`div`,{className:`overflow-hidden rounded-xl border border-border bg-card`,children:[(0,K.jsxs)(`div`,{className:`border-b border-dashed border-border px-4 py-3`,children:[(0,K.jsx)(`p`,{className:`mb-1 text-xs text-muted-foreground`,children:`Username`}),(0,K.jsx)(`p`,{className:`select-text break-all font-mono text-lg font-semibold`,dir:`ltr`,children:e.name})]}),(0,K.jsxs)(`div`,{className:`grid gap-3 p-4`,children:[(0,K.jsxs)(`p`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,K.jsx)(Lu,{className:`size-3.5`}),`Password`]}),(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(`code`,{"aria-label":`Created user password`,dir:`ltr`,className:`select-text break-all text-2xl font-semibold tracking-wider text-brand`,children:e.password||`Not provided`}),e.password&&(0,K.jsx)(DO,{text:e.password,label:`Copy password`,title:`Copy password`,className:`shrink-0`})]}),(0,K.jsx)(`p`,{className:`text-xs leading-relaxed text-muted-foreground`,children:`This dashboard clears the password when you close this window. You cannot reveal it again here.`})]})]}),(0,K.jsx)(`dl`,{className:`grid grid-cols-2 gap-x-5 gap-y-4`,children:e.details.map(([e,t])=>(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsx)(`dt`,{className:`mb-1 text-xs text-muted-foreground`,children:e}),(0,K.jsx)(`dd`,{className:`break-words text-sm font-medium`,children:t})]},e))})]}),(0,K.jsx)(S2,{className:`border-t border-border bg-card/50 px-6 py-4 sm:px-8`,children:(0,K.jsx)(Z,{type:`accent`,onClick:t,children:`Done`})})]})})}function wbe({device:e,user:t,value:n,onChange:r,onReadyChange:i,disabled:a}){let[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(null),[u,d]=(0,v.useState)(0);(0,v.useEffect)(()=>{let n=new AbortController,r=`?device=${encodeURIComponent(e)}`;return Promise.all([W(`/api/aaa/list/um-profiles${r}`,n.signal),t?W(`/api/aaa/list/um-user-profiles${r}`,n.signal):Promise.resolve({available:!0,rows:[]})]).then(([e,r])=>{if(!n.signal.aborted){if(!e.available||!r.available)throw Error(`User Manager profiles are unavailable on this device.`);s({profiles:e.rows.filter(e=>e.name),assignments:r.rows.filter(e=>e.user===t)})}}).catch(e=>{n.signal.aborted||l(e instanceof Error?e.message:`Unable to load profiles.`)}),()=>n.abort()},[e,t,u]);let f=o?.profiles.find(e=>e.name===n),p=o?.assignments.filter(e=>e.state?.replaceAll(` `,`-`)===`running-active`)??[],m=p.length===1?p[0].profile:``,h=p.length>1;(0,v.useEffect)(()=>{i(!!o&&!c&&!h&&(!n||!!f))},[o,c,h,n,f,i]);let g=!!n&&n!==m,_=t?`Service profile`:`Initial profile`;return(0,K.jsxs)(`section`,{"aria-label":`${_} settings`,className:`mb-3.5 grid gap-4 rounded-lg border border-brand/25 bg-brand/5 p-3.5 sm:grid-cols-2`,children:[(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 text-sm font-medium`,children:[(0,K.jsx)(Vu,{className:`size-4 shrink-0 text-brand`,"aria-hidden":`true`}),_,(0,K.jsx)(`span`,{className:`font-normal text-muted-foreground`,children:`· optional`})]}),(0,K.jsx)(`p`,{className:`mt-1.5 text-xs text-muted-foreground`,children:t?`Choose the profile this user should use. Save to activate your selection.`:`Assign a service profile as part of creating this user.`}),t&&o&&(0,K.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2 text-xs`,"aria-live":`polite`,children:[(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:`Current`}),(0,K.jsx)(`span`,{className:`break-all rounded-md border border-border bg-background px-2 py-1 font-mono`,children:h?`Multiple active profiles`:m||`No active profile`}),g&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Yc,{className:`size-3.5 text-brand`,"aria-hidden":`true`}),(0,K.jsx)(`span`,{className:`break-all rounded-md border border-brand/30 bg-brand/10 px-2 py-1 font-mono text-brand`,children:n})]})]}),(0,K.jsx)(`p`,{className:`mt-2 text-xs text-muted-foreground`,children:`Profile rules apply when User Manager’s “Use profiles” setting is enabled.`})]}),(0,K.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,K.jsx)(LA,{"aria-label":_,className:`w-full`,value:n,onValueChange:e=>r(t&&e===m?``:e),disabled:a||!o||!!c||h,options:[{value:``,label:!o&&!c?`Loading profiles…`:t?m?`Keep current · ${m}`:`Keep existing assignments`:`No profile — assign later`},...(o?.profiles??[]).map(e=>({value:e.name,label:e.name}))]}),c?(0,K.jsxs)(`div`,{className:`text-xs text-destructive`,role:`alert`,children:[c,(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:a,className:`mt-2`,onClick:()=>{s(null),l(null),d(e=>e+1)},children:`Retry profiles`})]}):h?(0,K.jsx)(`p`,{role:`alert`,className:`text-xs text-warning`,children:`Review the Assignments tab before changing this profile. Other user settings can still be saved.`}):o?.profiles.length===0?(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`No profiles yet. Create one in the Profiles tab, or continue without changing assignments.`}):f?(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[f.validity&&(0,K.jsxs)(K.Fragment,{children:[`Validity: `,f.validity,` · `]}),t?`Activated when saved`:f[`starts-when`]===`first-auth`?`Starts on first authentication`:f[`starts-when`]===`assigned`?`Starts immediately when assigned`:`Uses the profile’s activation settings`]}):(0,K.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:t?`No profile change selected.`:`Existing users and profiles are not changed.`}),t&&g&&(0,K.jsx)(`p`,{className:`text-xs text-warning`,role:`status`,children:`Previous assignments and history are kept. A new assignment starts a new validity period; an existing eligible one keeps its expiry. Existing connections may need to reconnect for new limits.`}),t&&o&&o.assignments.length>1&&(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[o.assignments.length,` assignments retained. Queued profiles may take over when the active one expires; manage them in Assignments.`]})]})]})}var T2=e=>(e.flags??``).includes(`X`)||e.disabled===`yes`;function Tbe(e,t){return e[t.idKey]||e.name||e.address||e.user||`(row)`}var E2=`mb-3.5 rounded-md border border-border bg-card p-3.5`,D2=`mb-2.5 text-[13px] font-semibold`,O2=`grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-x-3.5 gap-y-2.5`,k2=`mt-3.5 flex items-center gap-2.5`,A2=`flex flex-col gap-1`,j2=`text-[11.5px] text-muted-foreground`;function Ebe(e,t){let[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(document.hidden),[c,l]=(0,v.useState)(Date.now),u=(0,v.useRef)(()=>{});(0,v.useEffect)(()=>{if(!t||!e)return;let n=new AbortController,i=!1,o=async()=>{if(l(Date.now()),!(i||document.hidden||n.signal.aborted)){i=!0;try{let t=await W(`/api/aaa/user-counters?device=${encodeURIComponent(e)}`,n.signal);if(n.signal.aborted)return;if(!t.available)throw Error(t.error||`User counters are unavailable.`);if(t.device!==e)throw Error(`Counters belong to a different device. Refresh to retry.`);r(t),a(null),l(Date.now())}catch(e){n.signal.aborted||a(e instanceof Error?e.message:`Unable to read user counters.`)}finally{i=!1}}};u.current=()=>{o()};let c=()=>{s(document.hidden),o()};document.addEventListener(`visibilitychange`,c);let d=setInterval(()=>{o()},5e3);return o(),()=>{n.abort(),clearInterval(d),document.removeEventListener(`visibilitychange`,c),u.current=()=>{}}},[e,t]);let d=n?.device===e?n:null;return{data:d,error:i,paused:o,rows:(0,v.useMemo)(()=>new Map(d?.rows.map(e=>[e.name,e])),[d]),stale:!!d&&(c-d.collectedAt>15e3||!!i),refresh:()=>u.current()}}function Dbe(e){let t=Math.floor(e),n=Math.floor(t/86400);return`${n?`${n}d `:``}${[Math.floor(t/3600)%24,Math.floor(t/60)%60,t%60].map(e=>String(e).padStart(2,`0`)).join(`:`)}`}function M2({config:e,device:t}){let n=e.slug===`um-users`,r=Ebe(t,n),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(!1),[u,d]=(0,v.useState)(``),[f,p]=(0,v.useState)(null),[m,h]=(0,v.useState)({}),[g,_]=(0,v.useState)(!1),[y,b]=(0,v.useState)(!1),[x,S]=(0,v.useState)(null),[C,w]=(0,v.useState)(``),T=(0,v.useRef)(null),E=(0,v.useRef)(null);(0,v.useEffect)(()=>()=>E.current?.abort(),[t]);let D=(0,v.useCallback)(()=>{let n=t?`?device=${encodeURIComponent(t)}`:``;return W(`/api/aaa/list/${e.slug}${n}`).then(e=>{a(e),s(null)}).catch(e=>{s(e instanceof Error?e.message:String(e))})},[e.slug,t]),O=`${e.slug}\0${t}`,[k,A]=(0,v.useState)(O);k!==O&&(A(O),a(null),s(null),p(null)),(0,v.useEffect)(()=>{D()},[D]);let j=(0,v.useCallback)(async(n,r)=>{l(!0),s(null);try{let i=await vc(`/api/aaa/${n}`,{device:t,slug:e.slug,...r}),a=n===`add`?`Entry added`:n===`update`?`Entry saved`:n===`remove`?`Entry removed`:n===`toggle`?r.enable?`Entry enabled`:`Entry disabled`:`Done`;if(n===`add`&&e.slug===`um-users`&&(i.ok||i.created)){let e=r.fields;S({device:t,name:e.name,password:e.password??``,warning:i.ok?void 0:i.message,details:[[`Initial profile`,e.profile?`${e.profile}${i.ok?``:` · unconfirmed`}`:`None assigned`],[`Group`,e.group||`Router default`],[`Shared users`,e[`shared-users`]||`Router default`],[`Status`,e.disabled===`yes`?`Disabled`:`Enabled`],...[`caller-id`,`attributes`,`comment`].filter(t=>e[t]).map(t=>[t===`caller-id`?`Caller ID`:t===`attributes`?`RADIUS attributes`:`Comment`,e[t]])]}),p(null),h({}),w(``)}return i.ok?(await D(),X.success((n===`add`||n===`update`)&&e.slug===`um-users`?i.message:a),!0):((i.created||i.reviewRequired)&&(p(null),h({}),await D()),s(i.message),X.error(i.message||`${a} failed`),!1)}catch(e){return s(e instanceof Error?e.message:String(e)),X.error(e instanceof Error?e.message:`Action failed`),!1}finally{l(!1)}},[t,e.slug,D]),M=()=>{_(!1),p(`new`),h({}),w(``)},N=t=>{let n={};for(let r of e.fields)r.type!==`password`&&(r.key===`disabled`?n.disabled=T2(t)?`yes`:`no`:t[r.key]!=null&&(n[r.key]=t[r.key]));return n},P=t=>{_(!1),p(t[e.idKey]),h(N(t)),w(``)},F=async e=>{let n=new AbortController;E.current?.abort(),E.current=n,l(!0);let r=N(e),a=new Set((i?.rows??[]).map(e=>e.name)),o=1;for(r.name=`${e.name}-copy`;a.has(r.name);)r.name=`${e.name}-copy-${++o}`;let s=`Settings copied from ${e.name}. Choose a new name and password. Password, OTP and usage history are not copied.`;try{let i=await W(`/api/aaa/list/um-user-profiles?device=${encodeURIComponent(t)}`,n.signal);if(!i.available)throw Error(`Profiles unavailable`);let a=[...new Set(i.rows.filter(t=>t.user===e.name&&t.profile).map(e=>e.profile))];a.length===1?r.profile=a[0]:a.length>1&&(s+=` This user has multiple profiles; select one initial profile below.`)}catch{s+=` Profile assignments could not be read; select the initial profile yourself.`}finally{n.signal.aborted||(_(!1),h(r),w(s),p(`new`),l(!1))}},I=async()=>{if(n&&m.profile&&!y){s(`Wait for profiles to load or retry before saving a profile change.`);return}if(n&&f===`new`&&(!m.name?.trim()||!m.password)){s(`Enter a name and password for the new user.`);return}(f===`new`?await j(`add`,{fields:m}):await j(`update`,{id:f,fields:m}))&&(p(null),h({}))},L=(0,v.useMemo)(()=>{let t=i?.rows??[],n=u.trim().toLowerCase();return n?t.filter(t=>e.columns.some(e=>(t[e.key]??``).toLowerCase().includes(n))):t},[i,u,e.columns]);return i&&!i.available?(0,K.jsxs)(EA,{type:`warning`,label:`User Manager not installed`,children:[`This device doesn't have the `,(0,K.jsx)(`code`,{children:`user-manager`}),` package. Install it (System → Packages) and reboot to manage the built-in RADIUS server here.`]}):(0,K.jsxs)(`div`,{className:`min-w-0`,children:[(0,K.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2.5`,children:[(0,K.jsx)(NA,{className:`w-[200px]`,placeholder:`Filter…`,value:u,onChange:e=>d(e.target.value)}),(0,K.jsxs)(`span`,{className:`text-muted-foreground text-[11px]`,children:[L.length,` rows`]}),(0,K.jsx)(`span`,{className:`flex-1`}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(Nd,{}),onClick:()=>{D(),r.refresh()},children:`Refresh`}),(0,K.jsx)(Z,{ref:T,size:`sm`,type:`accent`,icon:(0,K.jsx)(Td,{}),disabled:c,onClick:M,children:`Add`})]}),n&&(0,K.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border border-border bg-card px-3 py-2 text-xs`,children:[(0,K.jsx)(`span`,{role:`status`,className:q(`font-medium`,r.stale||r.error?`text-warning`:`text-muted-foreground`),children:r.paused?`Updates paused`:r.error?`Counters unavailable`:r.stale?`Updates delayed`:r.data?`Live · 5s refresh`:`Reading counters…`}),r.data&&(0,K.jsxs)(`span`,{className:`text-muted-foreground`,children:[`Last read `,QO(r.data.collectedAt),r.stale?` · showing last known values`:``]}),(0,K.jsx)(`span`,{className:`basis-full text-muted-foreground`,children:`Cumulative User Manager totals, not the current connection only. Values update when the NAS sends RADIUS accounting; refresh does not reset counters.`}),r.error&&(0,K.jsx)(`span`,{role:`alert`,className:`basis-full text-warning`,children:r.error})]}),o&&(0,K.jsx)(EA,{type:`error`,className:`mb-2.5`,children:o}),f&&(0,K.jsxs)(`div`,{className:E2,children:[(0,K.jsx)(`div`,{className:D2,children:f===`new`?n?`New User Manager user`:`New ${e.slug}`:`Edit ${f}`}),C&&(0,K.jsx)(EA,{label:`Duplicate user`,className:`mb-3`,children:C}),e.slug===`um-users`&&(0,K.jsx)(wbe,{device:t,user:f===`new`?void 0:f,value:m.profile??``,onChange:e=>h(t=>({...t,profile:e})),onReadyChange:b,disabled:c},`${t}:${f}`),(0,K.jsx)(`div`,{className:O2,children:e.fields.map(e=>n&&e.key===`password`?(0,K.jsx)(IO,{label:`Password${f===`new`?` *`:``}`,type:g?`text`:`password`,autoComplete:`new-password`,disabled:c,placeholder:f===`new`?`Enter or generate a password`:`(unchanged)`,value:m.password??``,onChange:e=>h(t=>({...t,password:e})),classNames:{label:j2,field:`h-9 rounded-xl`,input:`pr-20 text-[13px] leading-5`,rightIcon:`[&_button]:size-9`},rightIcon:(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(`button`,{type:`button`,disabled:c,"aria-label":g?`Hide password`:`Show password`,"aria-pressed":g,title:g?`Hide password`:`Show password`,className:`rounded-lg transition-colors hover:bg-brand/10 hover:text-brand focus-visible:outline-2 focus-visible:outline-ring focus-visible:-outline-offset-2 disabled:opacity-50`,onClick:()=>_(e=>!e),children:g?(0,K.jsx)(lu,{"aria-hidden":`true`}):(0,K.jsx)(du,{"aria-hidden":`true`})}),(0,K.jsx)(`button`,{type:`button`,disabled:c,"aria-label":`Generate 8-character password`,title:`Generate 8 characters: uppercase, lowercase, number and symbol`,className:`rounded-lg text-brand transition-colors hover:bg-brand/10 focus-visible:outline-2 focus-visible:outline-ring focus-visible:-outline-offset-2 disabled:opacity-50`,onClick:()=>{try{let e=Sbe();h(t=>({...t,password:e}))}catch{s(`Secure password generation is unavailable. Enter a password manually.`)}},children:(0,K.jsx)(ff,{"aria-hidden":`true`})})]})},e.key):(0,K.jsxs)(`label`,{className:A2,children:[(0,K.jsxs)(`span`,{className:j2,children:[e.label,e.required&&f===`new`?` *`:``]}),e.type===`bool`?(0,K.jsx)(LA,{disabled:c,value:m[e.key]??``,onValueChange:t=>h({...m,[e.key]:t}),options:[{value:``,label:`—`},{value:`no`,label:`no`},{value:`yes`,label:`yes`}]}):e.type===`select`?(0,K.jsx)(LA,{disabled:c,value:m[e.key]??``,onValueChange:t=>h({...m,[e.key]:t}),options:[{value:``,label:`—`},...(e.options??[]).map(e=>({value:e,label:e}))]}):(0,K.jsx)(NA,{disabled:c,type:e.type===`password`?`password`:e.type===`number`?`number`:`text`,placeholder:e.placeholder??(e.type===`password`?`(unchanged)`:``),value:m[e.key]??``,onChange:t=>h({...m,[e.key]:t.target.value})})]},e.key))}),(0,K.jsxs)(`div`,{className:k2,children:[(0,K.jsx)(Z,{size:`sm`,type:`accent`,loading:c,disabled:n&&!!m.profile&&!y,onClick:()=>void I(),children:f===`new`?`Create`:`Save`}),(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:c,onClick:()=>{p(null),h({}),w(``)},children:`Cancel`})]})]}),i?L.length===0?(0,K.jsx)(`div`,{className:`px-1 py-5 text-muted-foreground text-[11px]`,children:e.empty??`Nothing here yet.`}):(0,K.jsxs)(_O,{className:`text-[13px]`,children:[(0,K.jsx)(vO,{children:(0,K.jsxs)(bO,{children:[e.columns.map(e=>(0,K.jsx)(xO,{children:e.label},e.key)),n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(xO,{className:`text-right`,children:`Total connected time`}),(0,K.jsx)(xO,{className:`text-right text-chart-1`,children:`↓ Download`}),(0,K.jsx)(xO,{className:`text-right text-chart-2`,children:`↑ Upload`})]}),(0,K.jsx)(xO,{className:`text-right`,children:`Actions`})]})}),(0,K.jsx)(yO,{children:L.map(t=>{let i=t[e.idKey],a=T2(t),o=r.rows.get(t.name);return(0,K.jsxs)(bO,{children:[e.columns.map(e=>(0,K.jsx)(SO,{className:q(a&&`text-muted-foreground`),title:t[e.key]??``,children:e.key===`_status`?(0,K.jsx)(kA,{type:a?`secondary`:`success`,children:a?`disabled`:`enabled`}):n&&e.key===`name`?(0,K.jsxs)(`div`,{className:`grid gap-1`,children:[(0,K.jsx)(`span`,{className:`font-medium`,children:t.name}),(0,K.jsx)(`span`,{className:`text-[10px] text-muted-foreground`,children:o?.active==null?`Connection count unknown`:`${o.active} active connection${o.active===1?``:`s`}`})]}):t[e.key]??``},e.key)),n&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(SO,{className:`text-right font-mono tabular-nums`,title:`Cumulative accounted connection time across this user's sessions`,children:o?.seconds==null?`—`:Dbe(o.seconds)}),(0,K.jsx)(SO,{className:`text-right font-mono tabular-nums text-chart-1`,title:`Total bytes downloaded by this user`,children:o?.download==null?`—`:ZO(o.download)}),(0,K.jsx)(SO,{className:`text-right font-mono tabular-nums text-chart-2`,title:`Total bytes uploaded by this user`,children:o?.upload==null?`—`:ZO(o.upload)})]}),(0,K.jsx)(SO,{className:`text-right`,children:(0,K.jsxs)(`span`,{className:`flex justify-end gap-1.5`,children:[n&&(0,K.jsx)(Z,{size:`sm`,ghost:!0,icon:(0,K.jsx)(ql,{}),disabled:c,"aria-label":`Duplicate ${t.name}`,title:`Copy settings into a new user`,onClick:()=>void F(t),children:`Duplicate`}),e.toggle&&(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:c,onClick:()=>void j(`toggle`,{id:i,enable:a}),children:a?`Enable`:`Disable`}),!e.addOnly&&(0,K.jsx)(Z,{size:`sm`,ghost:!0,disabled:c,onClick:()=>P(t),children:`Edit`}),(0,K.jsx)(Z,{size:`sm`,type:`error`,ghost:!0,disabled:c,onClick:()=>void j(`remove`,{id:i}),children:`Remove`})]})})]},i||Tbe(t,e))})})]}):!o&&(0,K.jsx)(`div`,{className:`text-muted-foreground text-[11px]`,role:`status`,children:`Loading…`}),x&&(0,K.jsx)(Cbe,{user:x,onClose:()=>S(null),onCloseAutoFocus:()=>T.current?.focus()})]})}function N2({device:e,getPath:t,setPath:n,fields:r,title:i,unwrap:a,extra:o}){let[s,c]=(0,v.useState)(null),[l,u]=(0,v.useState)(``),[d,f]=(0,v.useState)(!0),[p,m]=(0,v.useState)({}),[h,g]=(0,v.useState)(null),[_,y]=(0,v.useState)(!1),b=(0,v.useCallback)(()=>W(`${t}${e?`?device=${encodeURIComponent(e)}`:``}`).then(e=>{let{available:t,row:n}=a(e);f(t),c(n),m({}),u(``)}).catch(e=>{u(e instanceof Error?e.message:`Settings could not be read.`),c(null)}),[e,t,a]);(0,v.useEffect)(()=>{b()},[b]);let x=async()=>{y(!0),g(null);try{let t=await vc(n,{device:e,fields:p});g(t.message),t.ok?(await b(),X.success(`Settings saved`)):X.error(t.message||`Save failed`)}catch(e){X.error(e instanceof Error?e.message:`Save failed`)}finally{y(!1)}};return d?l?(0,K.jsxs)(EA,{type:`error`,label:i,children:[l,` `,(0,K.jsx)(Z,{size:`sm`,ghost:!0,onClick:()=>void b(),children:`Retry`})]}):s?(0,K.jsxs)(`div`,{className:E2,children:[(0,K.jsx)(`div`,{className:D2,children:i}),s&&(0,K.jsx)(`div`,{className:`mb-3 text-muted-foreground text-xs`,children:r.map(e=>`${e.label}: ${s[e.key]??`—`}`).join(` · `)}),(0,K.jsx)(`div`,{className:O2,children:r.map(e=>(0,K.jsxs)(`label`,{className:A2,children:[(0,K.jsx)(`span`,{className:j2,children:e.label}),e.type===`bool`?(0,K.jsx)(LA,{value:p[e.key]??``,onValueChange:t=>m({...p,[e.key]:t}),options:[{value:``,label:`(unchanged)`},{value:`no`,label:`no`},{value:`yes`,label:`yes`}]}):(0,K.jsx)(NA,{type:e.type===`number`?`number`:`text`,placeholder:e.placeholder??s?.[e.key]??``,value:p[e.key]??``,onChange:t=>m({...p,[e.key]:t.target.value})})]},e.key))}),(0,K.jsxs)(`div`,{className:k2,children:[(0,K.jsx)(Z,{size:`sm`,type:`accent`,loading:_,onClick:()=>void x(),children:`Save`}),o,h&&(0,K.jsx)(`span`,{className:`text-muted-foreground text-[11px]`,children:h})]})]}):(0,K.jsxs)(`p`,{className:`text-xs text-muted-foreground`,role:`status`,children:[`Loading `,i,`…`]}):(0,K.jsxs)(EA,{type:`warning`,label:`Not available`,children:[i,` is not available on this device.`]})}var Obe={slug:`radius`,idKey:`.id`,toggle:!0,columns:[{key:`address`,label:`Address`},{key:`service`,label:`Service`},{key:`authentication-port`,label:`Auth`},{key:`accounting-port`,label:`Acct`},{key:`protocol`,label:`Proto`},{key:`_status`,label:`Status`}],empty:`No RADIUS servers configured.`,fields:[{key:`address`,label:`Address`,required:!0,placeholder:`1.2.3.4 or host`},{key:`secret`,label:`Secret`,type:`password`,required:!0},{key:`service`,label:`Service`,required:!0,placeholder:`login,ppp,hotspot,wireless,dhcp,ipsec,dot1x`},{key:`authentication-port`,label:`Auth port`,type:`number`,placeholder:`1812`},{key:`accounting-port`,label:`Acct port`,type:`number`,placeholder:`1813`},{key:`timeout`,label:`Timeout`,placeholder:`300ms`},{key:`src-address`,label:`Src address`},{key:`realm`,label:`Realm`},{key:`called-id`,label:`Called ID`},{key:`domain`,label:`Domain`},{key:`protocol`,label:`Protocol`,type:`select`,options:[`udp`,`radsec`]},{key:`certificate`,label:`Certificate`},{key:`accounting-backup`,label:`Acct backup`,type:`bool`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},kbe={slug:`um-users`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared`},{key:`caller-id`,label:`Caller ID`},{key:`comment`,label:`Comment`},{key:`_status`,label:`Status`}],empty:`No RADIUS users.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`password`,label:`Password`,type:`password`,required:!0},{key:`group`,label:`Group`},{key:`shared-users`,label:`Shared users`,type:`number`,placeholder:`1`},{key:`attributes`,label:`RADIUS attributes`},{key:`caller-id`,label:`Caller ID (MAC)`},{key:`otp-secret`,label:`OTP secret`,type:`password`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},Abe={slug:`um-profiles`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`name-for-users`,label:`Display`},{key:`validity`,label:`Validity`},{key:`price`,label:`Price`},{key:`starts-when`,label:`Starts`}],empty:`No service profiles.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`name-for-users`,label:`Display name`},{key:`validity`,label:`Validity`,placeholder:`30d`},{key:`price`,label:`Price`,type:`number`},{key:`starts-when`,label:`Starts when`,type:`select`,options:[`assigned`,`first-auth`]},{key:`override-shared-users`,label:`Override shared-users`},{key:`comment`,label:`Comment`}]},jbe={slug:`um-limitations`,idKey:`name`,columns:[{key:`name`,label:`Name`},{key:`rate-limit-rx`,label:`Rate ↓`},{key:`rate-limit-tx`,label:`Rate ↑`},{key:`transfer-limit`,label:`Transfer`},{key:`uptime-limit`,label:`Uptime`}],empty:`No limitation templates.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`rate-limit-rx`,label:`Download rate`,placeholder:`10M`},{key:`rate-limit-tx`,label:`Upload rate`,placeholder:`10M`},{key:`rate-limit-min-rx`,label:`Min download (CIR)`,placeholder:`2M`},{key:`rate-limit-min-tx`,label:`Min upload (CIR)`,placeholder:`2M`},{key:`rate-limit-burst-rx`,label:`Burst download`,placeholder:`20M`},{key:`rate-limit-burst-tx`,label:`Burst upload`,placeholder:`20M`},{key:`rate-limit-burst-threshold-rx`,label:`Burst thr. ↓`},{key:`rate-limit-burst-threshold-tx`,label:`Burst thr. ↑`},{key:`rate-limit-burst-time-rx`,label:`Burst time ↓`,placeholder:`10s`},{key:`rate-limit-burst-time-tx`,label:`Burst time ↑`,placeholder:`10s`},{key:`rate-limit-priority`,label:`Priority (1-8)`,type:`number`},{key:`download-limit`,label:`Download cap`,placeholder:`5G`},{key:`upload-limit`,label:`Upload cap`,placeholder:`5G`},{key:`transfer-limit`,label:`Total transfer cap`,placeholder:`10G`},{key:`uptime-limit`,label:`Uptime cap`,placeholder:`1d`},{key:`reset-counters-interval`,label:`Reset interval`},{key:`reset-counters-start-time`,label:`Reset start time`},{key:`comment`,label:`Comment`}]},Mbe={slug:`um-routers`,idKey:`name`,toggle:!0,columns:[{key:`name`,label:`Name`},{key:`address`,label:`Address`},{key:`coa-port`,label:`CoA port`},{key:`protocol`,label:`Proto`},{key:`comment`,label:`Comment`},{key:`_status`,label:`Status`}],empty:`No NAS clients registered.`,fields:[{key:`name`,label:`Name`,required:!0},{key:`address`,label:`Address`,required:!0,placeholder:`192.168.88.1`},{key:`shared-secret`,label:`Shared secret`,type:`password`,required:!0},{key:`coa-port`,label:`CoA port`,type:`number`},{key:`protocol`,label:`Protocol`,placeholder:`radius`},{key:`comment`,label:`Comment`},{key:`disabled`,label:`Disabled`,type:`bool`}]},Nbe={slug:`um-user-profiles`,idKey:`.id`,addOnly:!0,columns:[{key:`user`,label:`User`},{key:`profile`,label:`Profile`},{key:`state`,label:`State`},{key:`end-time`,label:`Ends`}],empty:`No profile assignments.`,fields:[{key:`user`,label:`User`,required:!0},{key:`profile`,label:`Profile`,required:!0}]},Pbe=[{id:`reports`,label:`Reports & insights`},{id:`radius`,label:`RADIUS Servers`},{id:`users`,label:`Users`},{id:`profiles`,label:`Profiles`},{id:`limitations`,label:`Limitations`},{id:`nas`,label:`NAS Clients`},{id:`assignments`,label:`Assignments`},{id:`settings`,label:`Settings`}],Fbe=[{key:`accept`,label:`Accept CoA`,type:`bool`},{key:`port`,label:`CoA port`,type:`number`,placeholder:`3799`}],Ibe=[{key:`enabled`,label:`Enabled`,type:`bool`},{key:`use-profiles`,label:`Use profiles`,type:`bool`},{key:`certificate`,label:`Certificate`},{key:`authentication-port`,label:`Auth port`,type:`number`},{key:`accounting-port`,label:`Acct port`,type:`number`}];function Lbe(){let[e,t]=(0,v.useState)(``),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(!1),[o,s]=(0,v.useState)(null),c=(0,v.useCallback)(()=>W(`/api/usage/sampler`).then(e=>{r(e.intervalMs)}).catch(()=>{r(null)}),[]);(0,v.useEffect)(()=>{c()},[c]);let l=async()=>{let n=Number(e);if(!Number.isFinite(n)||n<=0){s(`Enter a positive number of minutes.`),X.error(`Enter a positive number of minutes`);return}a(!0),s(null);try{let e=await vc(`/api/usage/sampler`,{intervalMs:Math.round(n*6e4)});r(e.intervalMs),t(``),s(`Now sampling every ${P2(e.intervalMs)}.`),X.success(`Now sampling every ${P2(e.intervalMs)}`)}catch(e){s(e instanceof Error?e.message:String(e)),X.error(e instanceof Error?e.message:`Save failed`)}finally{a(!1)}};return(0,K.jsxs)(`div`,{className:`rounded-md border border-border bg-card p-3.5`,children:[(0,K.jsx)(`div`,{className:D2,children:`Usage sampling`}),(0,K.jsxs)(`div`,{className:`mb-3 text-muted-foreground text-xs`,children:[`How often client traffic + User Manager sessions are recorded into the usage history. Current: `,n==null?`…`:P2(n),` · default 1 minute · range 30s–6h.`]}),(0,K.jsx)(`div`,{className:O2,children:(0,K.jsxs)(`label`,{className:A2,children:[(0,K.jsx)(`span`,{className:j2,children:`Interval (minutes)`}),(0,K.jsx)(NA,{type:`number`,step:`0.5`,min:`0.5`,placeholder:n?String(n/6e4):`1`,value:e,onChange:e=>t(e.target.value)})]})}),(0,K.jsxs)(`div`,{className:k2,children:[(0,K.jsx)(Z,{size:`sm`,type:`accent`,loading:i,onClick:()=>void l(),children:`Save`}),[1,5,10,30].map(e=>(0,K.jsxs)(Z,{size:`sm`,ghost:!0,onClick:()=>{t(String(e))},children:[e,`m`]},e)),o&&(0,K.jsx)(`span`,{className:`text-muted-foreground text-[11px]`,children:o})]})]})}function P2(e){if(e<6e4)return`${Math.round(e/1e3)}s`;let t=e/6e4;return`${Number.isInteger(t)?t:t.toFixed(1)} min`}function Rbe(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(``),[i,a]=(0,v.useState)(`reports`);(0,v.useEffect)(()=>{W(`/api/devices`).then(e=>{t(e),r(t=>t||e.defaultDevice||e.devices[0]?.name||``)}).catch(()=>t({server:``,defaultDevice:``,devices:[]}))},[]);let o=e?.devices??[];return(0,K.jsxs)(`section`,{className:`grid content-start gap-[18px]`,children:[(0,K.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,K.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:`RADIUS & User Manager workspace`}),o.length>0?(0,K.jsx)(LA,{value:n,onValueChange:r,"aria-label":`Router`,options:o.map(e=>({value:e.name,label:`${e.name}${e.isDefault?` (default)`:``}`}))}):null]}),(0,K.jsxs)(Ok,{value:i,onValueChange:e=>a(e),children:[(0,K.jsx)(kk,{className:`mb-3.5 h-auto w-full flex-wrap justify-start border-b border-border`,children:Pbe.map(e=>(0,K.jsx)(Ak,{value:e.id,children:e.label},e.id))}),(0,K.jsx)(jk,{value:`radius`,children:(0,K.jsx)(M2,{config:Obe,device:n})}),(0,K.jsx)(jk,{value:`users`,children:(0,K.jsx)(M2,{config:kbe,device:n})}),(0,K.jsx)(jk,{value:`profiles`,children:(0,K.jsx)(M2,{config:Abe,device:n})}),(0,K.jsx)(jk,{value:`limitations`,children:(0,K.jsx)(M2,{config:jbe,device:n})}),(0,K.jsx)(jk,{value:`nas`,children:(0,K.jsx)(M2,{config:Mbe,device:n})}),(0,K.jsx)(jk,{value:`assignments`,children:(0,K.jsx)(M2,{config:Nbe,device:n})}),(0,K.jsx)(jk,{value:`reports`,children:(0,K.jsx)(ybe,{device:n},n)}),(0,K.jsx)(jk,{value:`settings`,children:(0,K.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,K.jsx)(N2,{device:n,getPath:`/api/aaa/radius-incoming`,setPath:`/api/aaa/radius-incoming`,title:`RADIUS Incoming (CoA listener)`,fields:Fbe,unwrap:e=>({available:!0,row:e??{}}),extra:(0,K.jsx)(Z,{size:`sm`,ghost:!0,onClick:()=>void vc(`/api/aaa/radius-reset-counters`,{device:n}).then(()=>X.success(`Counters reset`)).catch(()=>X.error(`Reset counters failed`)),children:`Reset RADIUS counters`})}),(0,K.jsx)(N2,{device:n,getPath:`/api/aaa/um-settings`,setPath:`/api/aaa/um-settings`,title:`User Manager (built-in RADIUS server)`,fields:Ibe,unwrap:e=>{let t=e??{};return{available:t.available!==!1,row:t.settings??{}}}}),(0,K.jsx)(Lbe,{})]})})]},n)]})}function F2(e){let[t,n]=(0,v.useState)(``),[r,i]=(0,v.useState)([]),[a,o]=(0,v.useState)(),[s,c]=(0,v.useState)(!1),[l,u]=(0,v.useState)(!0),[d,f]=(0,v.useState)(``),[p,m]=(0,v.useState)(Date.now),h=(0,v.useRef)(0),g=(0,v.useCallback)(()=>{h.current++},[]),_=e=>{g(),o(void 0),f(``),n(e)};(0,v.useEffect)(()=>{let e=!1;return W(`/api/devices`).then(t=>{e||(i(t.devices.map(e=>e.name)),n(t.devices.some(e=>e.name===t.defaultDevice)?t.defaultDevice:t.devices[0]?.name??``),u(!1))}).catch(()=>{e||(f(`Routers could not be loaded. Check the dashboard connection and retry.`),u(!1))}),()=>{e=!0,g()}},[g]);let y=(0,v.useCallback)(async()=>{if(!t)return;let n=++h.current;u(!0);try{let r=await W(`${e}?device=${encodeURIComponent(t)}`);n===h.current&&(o(r),m(Date.now()),f(``))}catch(e){n===h.current&&f(e instanceof Error?e.message:`Could not load this workspace.`)}finally{n===h.current&&u(!1)}},[t,e]);(0,v.useEffect)(()=>{let e=setTimeout(()=>void y(),0);return()=>{clearTimeout(e),g()}},[y,g]);async function b(n,r){if(!t||s)return;c(!0),f(``);let i=h.current;try{let a=await vc(`${e}${n}?device=${encodeURIComponent(t)}`,r);if(a.error)throw Error(a.error);if(i===h.current)return await y(),a}catch(e){i===h.current&&f(e instanceof Error?e.message:`Operation failed. Review the router state before retrying a write.`)}finally{c(!1)}}return{device:t,setDevice:_,devices:r,data:a,busy:s,loading:l,error:d,refresh:y,action:b,observedAt:p}}function I2({eyebrow:e,title:t,description:n,device:r,devices:i,onDevice:a,busy:o,onRefresh:s,children:c}){return(0,K.jsxs)(`header`,{className:`ops-header`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`p`,{className:`ops-eyebrow`,children:e}),(0,K.jsx)(`h2`,{children:t}),(0,K.jsx)(`p`,{className:`ops-description`,children:n})]}),(0,K.jsxs)(`div`,{className:`ops-toolbar`,children:[(0,K.jsxs)(yA,{value:r,onValueChange:a,disabled:o||!i.length,children:[(0,K.jsxs)(bA,{"aria-label":`Workspace router`,children:[(0,K.jsx)(Vd,{size:16}),(0,K.jsx)(gA,{placeholder:`Select router`})]}),(0,K.jsx)(xA,{children:i.map(e=>(0,K.jsx)(vA,{value:e,children:e},e))})]}),(0,K.jsx)(Y,{variant:`outline`,onClick:s,disabled:o,"aria-label":`Refresh workspace`,children:(0,K.jsx)(Nd,{size:16})}),c]})]})}function L2({message:e}){return e?(0,K.jsxs)(`div`,{role:`alert`,className:`ops-notice ops-notice--error`,children:[(0,K.jsx)(If,{size:18}),(0,K.jsx)(`span`,{children:e})]}):null}function R2({children:e}){return(0,K.jsxs)(`div`,{className:`ops-notice`,children:[(0,K.jsx)(rf,{size:18}),(0,K.jsx)(`span`,{children:e})]})}function z2({state:e}){return(0,K.jsxs)(`span`,{className:`ops-state`,"data-state":e,children:[(0,K.jsx)(`i`,{"aria-hidden":`true`}),e.replaceAll(`-`,` `)]})}function B2(e){if(e===null)return`Unavailable`;let t=Math.max(0,Math.floor(e)),n=Math.floor(t/86400),r=[Math.floor(t/3600)%24,Math.floor(t/60)%60,t%60].map(e=>String(e).padStart(2,`0`)).join(`:`);return`${n?`${n}d `:``}${r}`}function zbe(){let[e,t]=(0,v.useState)([]),[n,r]=(0,v.useState)(``),[i,a]=(0,v.useState)(``),[o,s]=(0,v.useState)(!1),[c,l]=(0,v.useState)(0);return(0,v.useEffect)(()=>{let e=new AbortController;return W(`/api/devices`,e.signal).then(n=>{if(e.signal.aborted)return;let i=n.devices.filter(e=>!e.disabled).map(e=>e.name);t(i),r(i.includes(n.defaultDevice)?n.defaultDevice:i[0]??``),a(``),s(!0)}).catch(()=>{e.signal.aborted||(a(`Routers could not be loaded. Check the dashboard connection and retry.`),s(!0))}),()=>e.abort()},[c]),(0,K.jsxs)(`div`,{className:`ovpn-workspace`,children:[(0,K.jsxs)(`header`,{className:`ovpn-intro`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsxs)(`span`,{className:`ovpn-eyebrow`,children:[(0,K.jsx)(Zu,{size:15}),` OPENVPN / LIVE CONNECTIONS`]}),(0,K.jsxs)(`h2`,{children:[`Who's connected`,(0,K.jsx)(`span`,{children:`to your network.`})]}),(0,K.jsx)(`p`,{children:`One connection per row. See who is here, how long they have stayed, and end a session when needed.`})]}),(0,K.jsxs)(`div`,{className:`ovpn-router`,children:[(0,K.jsx)(`label`,{htmlFor:`ovpn-router`,children:`Router`}),(0,K.jsxs)(yA,{value:n,onValueChange:r,disabled:!e.length,children:[(0,K.jsx)(bA,{id:`ovpn-router`,"aria-label":`OpenVPN router`,children:(0,K.jsx)(gA,{placeholder:`Select a router`})}),(0,K.jsx)(xA,{children:e.map(e=>(0,K.jsx)(vA,{value:e,children:e},e))})]}),(0,K.jsx)(`small`,{children:`Incoming OpenVPN connections only`})]})]}),i&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(L2,{message:i}),(0,K.jsx)(Y,{variant:`outline`,onClick:()=>l(e=>e+1),children:`Retry routers`})]}),n?(0,K.jsx)(Bbe,{device:n},n):!i&&(0,K.jsx)(`div`,{className:`ovpn-empty`,children:o?`No enabled routers. Add or enable a router in Devices to see its OpenVPN connections.`:`Loading routers…`})]})}function Bbe({device:e}){let[t,n]=(0,v.useState)(),[r,i]=(0,v.useState)(``),[a,o]=(0,v.useState)(``),[s,c]=(0,v.useState)(!0),[l,u]=(0,v.useState)(!1),[d,f]=(0,v.useState)(0),[p,m]=(0,v.useState)(Date.now),[h,g]=(0,v.useState)(``),[_,y]=(0,v.useState)(),[b,x]=(0,v.useState)(!1),S=(0,v.useRef)(!0),C=(0,v.useRef)(!1);(0,v.useEffect)(()=>{S.current=!0;let e=setInterval(()=>m(Date.now()),1e3);return()=>{S.current=!1,clearInterval(e)}},[]),(0,v.useEffect)(()=>{if(l||_)return;let t=new AbortController,r,a=async()=>{if(!document.hidden){c(!0);try{let r=await W(`/api/openvpn/sessions?device=${encodeURIComponent(e)}`,AbortSignal.any([t.signal,AbortSignal.timeout(15e3)]));t.signal.aborted||(n({data:r,receivedAt:Date.now()}),i(``),m(Date.now()))}catch(e){t.signal.aborted||i(e instanceof Error?e.message:`Router unavailable. Refresh to try again.`)}finally{t.signal.aborted||c(!1)}}t.signal.aborted||(r=setTimeout(()=>void a(),5e3))};return a(),()=>{t.abort(),clearTimeout(r)}},[e,d,l,_]);let w=t?.data,T=!!r||!t||p-t.receivedAt>15e3,E=!!_&&(!t||p-t.receivedAt>=55e3),D=T||!t?0:Math.max(0,Math.floor((p-t.receivedAt)/1e3)),O=w?.sessions??[],k=O.filter(e=>[e.name,e.address,e.callerId,e.sessionId].join(` `).toLowerCase().includes(h.trim().toLowerCase())),A=O.reduce((e,t)=>t.uptimeSeconds===null?e:Math.max(e??0,t.uptimeSeconds),null);function j(e){x(!1),o(``),y(e)}async function M(){if(_?.disconnectToken&&b&&!E&&!C.current){C.current=!0,u(!0),o(``);try{let t=await vc(`/api/openvpn/disconnect?device=${encodeURIComponent(e)}`,{token:_.disconnectToken,confirm:!0});S.current&&o(t.error??t.message??`No confirmation received. Refresh to check the current connection; do not retry automatically.`)}catch{S.current&&o(`Connection interrupted before confirmation. Refresh to check the router; the request will not be replayed.`)}finally{C.current=!1,S.current&&(u(!1),y(void 0),f(e=>e+1))}}}return(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`section`,{className:`ovpn-summary`,"aria-label":`OpenVPN connection summary`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(Wf,{size:18}),(0,K.jsxs)(`span`,{children:[`Active connections`,(0,K.jsx)(`strong`,{children:w?O.length:`—`})]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(rf,{size:18}),(0,K.jsxs)(`span`,{children:[`Distinct users`,(0,K.jsx)(`strong`,{children:w?new Set(O.map(e=>e.name)).size:`—`})]})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(zl,{size:18}),(0,K.jsxs)(`span`,{children:[`Longest connection`,(0,K.jsx)(`strong`,{children:A===null?`—`:B2(A+D)})]})]})]}),(0,K.jsxs)(`div`,{className:`ovpn-toolbar`,children:[(0,K.jsxs)(`div`,{className:`ovpn-search`,children:[(0,K.jsx)(qd,{size:16}),(0,K.jsx)(LO,{"aria-label":`Search OpenVPN connections`,placeholder:`Find a user, source or tunnel IP…`,value:h,onChange:e=>g(e.target.value)})]}),(0,K.jsxs)(`span`,{className:`ovpn-fresh`,"data-stale":T,children:[(0,K.jsx)(`i`,{}),t?T?`Last known connections · stale`:`Live · 5s refresh`:`Waiting for router`]}),(0,K.jsxs)(Y,{variant:`outline`,size:`sm`,disabled:s||l||!!_,onClick:()=>f(e=>e+1),children:[(0,K.jsx)(Nd,{size:14,className:s?`animate-spin`:``}),` Refresh`]})]}),(0,K.jsx)(L2,{message:r}),a&&(0,K.jsx)(`div`,{className:`ovpn-notice`,role:`status`,children:a}),w&&(0,K.jsxs)(`p`,{className:`ovpn-caption`,children:[k.length,` of `,O.length,` connections · Router read`,` `,new Date(w.observedAt).toLocaleTimeString(),w.canDisconnect?``:` · Read-only access`,T?` · Times are frozen until the next successful read.`:` · Times advance between router reads.`]}),w?k.length===0?(0,K.jsxs)(`div`,{className:`ovpn-empty`,children:[(0,K.jsx)(Zu,{size:28}),(0,K.jsx)(`strong`,{children:O.length?`No matching connections`:`No active OpenVPN connections`}),(0,K.jsx)(`span`,{children:O.length?`Try another username or IP address.`:`No incoming OpenVPN sessions were reported by ${e} at the last read.`})]}):(0,K.jsx)(`section`,{className:`ovpn-list`,"aria-label":`Active OpenVPN connections`,children:k.map(e=>(0,K.jsxs)(`article`,{className:`ovpn-session`,children:[(0,K.jsxs)(`div`,{className:`ovpn-person`,children:[(0,K.jsx)(`span`,{className:`ovpn-avatar`,children:(0,K.jsx)(Zu,{size:20})}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`h3`,{children:e.name}),(0,K.jsxs)(`small`,{children:[e.radius?`RADIUS authenticated`:`OpenVPN connection`,` · `,e.id]})]})]}),(0,K.jsxs)(`div`,{className:`ovpn-path`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`small`,{children:`Client source`}),(0,K.jsx)(`code`,{children:e.callerId||`Not reported`})]}),(0,K.jsx)(Yc,{size:16}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`small`,{children:`Tunnel IP`}),(0,K.jsx)(`code`,{children:e.address||`Not reported`})]})]}),(0,K.jsxs)(`div`,{className:`ovpn-duration`,children:[(0,K.jsxs)(`small`,{children:[(0,K.jsx)(zl,{size:13}),` Connected for`]}),(0,K.jsx)(`strong`,{children:B2(e.uptimeSeconds===null?null:e.uptimeSeconds+D)}),(0,K.jsx)(`span`,{children:e.encoding||`Encoding not reported`})]}),(0,K.jsxs)(Y,{variant:`outline`,size:`sm`,className:`ovpn-disconnect`,"aria-label":`Disconnect ${e.name} session ${e.id}`,title:e.disconnectToken?void 0:`Session identity or uptime is missing; disconnect is unavailable.`,disabled:T||l||!w.canDisconnect||!e.disconnectToken,onClick:()=>j(e),children:[(0,K.jsx)(Bf,{size:14}),` Disconnect`]})]},`${e.id}:${e.sessionId}`))}):(0,K.jsxs)(`div`,{className:`ovpn-empty`,children:[(0,K.jsx)(Fc,{size:26}),(0,K.jsx)(`strong`,{children:r?`Connection list unavailable`:`Reading active connections…`}),(0,K.jsx)(`span`,{children:r?`An unreachable router is not an empty connection list.`:`Reading runtime sessions, not user passwords or history.`})]}),(0,K.jsxs)(`p`,{className:`ovpn-footnote`,children:[(0,K.jsx)(rf,{size:15}),` Disconnect ends only the selected connection. It does not disable the account; the client may reconnect.`]}),(0,K.jsx)(y2,{open:!!_,onOpenChange:e=>{!e&&!l&&y(void 0)},children:(0,K.jsxs)(b2,{className:`ovpn-dialog`,showCloseButton:!l,children:[(0,K.jsxs)(x2,{children:[(0,K.jsx)(C2,{children:`Disconnect this connection?`}),(0,K.jsxs)(w2,{children:[`Only this OpenVPN session on `,e,` will be ended. Other connections for the same username are not selected.`]})]}),(0,K.jsx)(RO,{className:`ovpn-dialog-scroll`,children:_&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsxs)(`dl`,{className:`ovpn-confirm-details`,children:[(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`User`}),(0,K.jsx)(`dd`,{children:_.name})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Router`}),(0,K.jsx)(`dd`,{children:e})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Client source`}),(0,K.jsx)(`dd`,{children:_.callerId||`Not reported`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Tunnel IP`}),(0,K.jsx)(`dd`,{children:_.address||`Not reported`})]}),(0,K.jsxs)(`div`,{children:[(0,K.jsx)(`dt`,{children:`Session`}),(0,K.jsxs)(`dd`,{children:[_.id,` · `,_.sessionId]})]})]}),(0,K.jsx)(`p`,{className:`ovpn-notice`,children:`If this is your management tunnel, you may lose access to this router. The client can reconnect with its existing credentials.`}),E&&(0,K.jsx)(`p`,{role:`alert`,className:`ovpn-notice`,children:`This selection expired. Close this dialog and select the current connection again.`}),(0,K.jsxs)(`label`,{className:`ovpn-consent`,children:[(0,K.jsx)(rO,{checked:b,onCheckedChange:e=>x(e===!0),disabled:l}),` `,`I want to disconnect this one connection.`]})]})}),(0,K.jsxs)(S2,{children:[(0,K.jsx)(Y,{variant:`outline`,disabled:l,onClick:()=>y(void 0),children:`Cancel`}),(0,K.jsx)(Y,{variant:`destructive`,disabled:!b||l||E,onClick:()=>void M(),children:l?`Disconnecting…`:`Disconnect connection`})]})]})})]})}var V2=new Set;function H2(e){return V2.add(e),()=>V2.delete(e)}function Vbe(e){for(let t of V2)t(e)}var U2=new Set;function W2(e){return U2.add(e),()=>U2.delete(e)}function Hbe(e){for(let t of U2)t(e)}function Ube(e,t){let n=(0,v.useRef)(e),r=(0,v.useRef)(t);(0,v.useLayoutEffect)(()=>{n.current=e,r.current=t},[e,t]),(0,v.useEffect)(()=>{let e=!1,t=null,i=null,a=()=>{t&&=(t.onopen=t.onerror=t.onmessage=t.onclose=null,t.close(),null),i&&=(i.close(),null)},o=()=>{e||(i=new EventSource(hc(`/api/sse`)),i.addEventListener(`hello`,()=>r.current(`sse`)),i.addEventListener(`tool`,e=>{try{n.current(JSON.parse(e.data))}catch{}}),i.onerror=()=>{i&&i.readyState===EventSource.CONNECTING&&r.current(`off`)})},s=()=>{if(e)return;let i=location.protocol===`https:`?`wss`:`ws`;t=new WebSocket(hc(`${i}://${location.host}/api/stream`));let a=!1;t.onopen=()=>{a=!0,r.current(`ws`)},t.onerror=()=>t?.close(),t.onmessage=e=>{try{let t=JSON.parse(e.data);t.type===`event`&&t.event&&n.current(t.event),t.type===`txn`&&t.update&&Vbe(t.update),t.type===`rollout`&&t.update&&Hbe(t.update)}catch{}},t.onclose=()=>{e||(r.current(`off`),a?setTimeout(s,2e3):o())}},c=()=>t?.readyState===WebSocket.OPEN||i?.readyState===EventSource.OPEN,l=()=>{e||c()||(a(),s())},u=()=>{document.visibilityState===`visible`&&l()};return s(),document.addEventListener(`visibilitychange`,u),window.addEventListener(`online`,l),()=>{e=!0,document.removeEventListener(`visibilitychange`,u),window.removeEventListener(`online`,l),a()}},[])}function Wbe(e){(0,v.useLayoutEffect)(()=>{let t=e.current;if(!t||window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)return;document.documentElement.classList.add(`js-motion`);let n=new WeakSet,r=e=>{n.has(e)||(n.add(e),Ri.set(e,{opacity:0,y:26}),ic.create({trigger:e,start:`top 90%`,once:!0,onEnter:()=>Ri.to(e,{opacity:1,y:0,duration:.7,ease:`power3.out`})}))},i=e=>{for(let t of e.querySelectorAll(`.reveal`))r(t)};i(t);let a=new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&(e.matches(`.reveal`)&&r(e),i(e))});a.observe(t,{childList:!0,subtree:!0});let o=setInterval(()=>ic.refresh(),1200),s=setTimeout(()=>clearInterval(o),7e3);return()=>{a.disconnect(),clearInterval(o),clearTimeout(s);for(let e of ic.getAll())e.kill();document.documentElement.classList.remove(`js-motion`)}},[e])}var G2={completed:`success`,"completed-with-failures":`warning`,halted:`warning`,reverted:`secondary`,"needs-attention":`error`,aborted:`secondary`},Gbe={completed:`Every device applied the change.`,"completed-with-failures":`The rollout finished, but a gate failed along the way.`,halted:`Stopped at a failed gate. The devices already changed are still changed.`,reverted:`Stopped and put back — the fleet is where it started.`,"needs-attention":`A revert itself failed. Restore the flagged device(s) by hand from the snapshot named below.`,aborted:`A human stopped it; whatever had been applied was reverted.`},K2={pending:`bg-muted/30 text-muted-foreground`,applied:`bg-emerald-500/15 text-emerald-600 dark:text-emerald-400`,failed:`bg-red-500/15 text-red-600 dark:text-red-400`,reverted:`bg-amber-500/15 text-amber-600 dark:text-amber-400`,"revert-failed":`bg-red-500/25 text-red-600 dark:text-red-400 font-semibold`,skipped:`bg-muted/20 text-muted-foreground line-through`};function Kbe(e){let t=Date.now()-e;return t<6e4?`just now`:t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function qbe({rollout:e}){let t=t=>e.gates.find(e=>e.wave===t);return(0,K.jsx)(`div`,{className:`space-y-3`,children:e.waves.map(n=>{let r=t(n.index),i=n.devices.map(t=>e.devices.find(e=>e.device===t)).filter(e=>e!==void 0),a=e.outcome===void 0&&i.some(e=>e.stage===`pending`);return(0,K.jsxs)(`div`,{className:`rounded-md border p-3`,children:[(0,K.jsxs)(`div`,{className:`mb-2 flex items-center gap-2 text-sm`,children:[(0,K.jsxs)(`span`,{className:`font-medium`,children:[`Wave `,n.index+1,n.isCanary&&(0,K.jsx)(`span`,{className:`ml-2 rounded-sm bg-amber-500/15 px-1.5 py-0.5 text-xs text-amber-600 dark:text-amber-400`,children:`canary`})]}),(0,K.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[i.length,` device(s)`]}),a&&(0,K.jsx)(jA,{type:`warning`,pulse:!0}),r&&(0,K.jsxs)(kA,{type:r.ok?`success`:`error`,className:`ml-auto`,children:[`gate `,r.ok?`pass`:`fail`]})]}),(0,K.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:i.map(e=>(0,K.jsx)(`span`,{title:e.error??e.stage,className:q(`rounded-md px-2 py-1 font-mono text-xs`,K2[e.stage]??K2.pending),children:e.device},e.device))}),r&&!r.ok&&(0,K.jsxs)(`ul`,{className:`mt-2 space-y-1 text-xs text-red-600 dark:text-red-400`,children:[r.collateral&&(0,K.jsx)(`li`,{className:`font-medium`,children:`An UNTOUCHED device went dark — the change affected the wider fleet.`}),r.failures.map(e=>(0,K.jsxs)(`li`,{children:[e.device,`: `,e.reason]},e.device))]})]},n.index)})})}function Jbe({id:e,onClose:t}){let[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)([]),[o,s]=(0,v.useState)(!1),c=(0,v.useCallback)(()=>W(`/api/rollout/${encodeURIComponent(e)}`).then(e=>{r(e.rollout),a(e.events)}).catch(e=>{X.error(`Failed to load rollout: ${e instanceof Error?e.message:String(e)}`)}),[e]);(0,v.useEffect)(()=>(c(),W2(t=>{t.rolloutId===e&&c()})),[e,c]);let l=async t=>{s(!0);try{let n=await vc(`/api/rollout/${encodeURIComponent(e)}/${t}`,{});n.error?X.error(n.error):X.success(n.outcome??(t===`hold`?`Held`:`Done`)),await c()}finally{s(!1)}};if(!n)return(0,K.jsx)(wO,{title:`Rollout`,children:`Loading…`});let u=n.outcome===void 0,d=n.devices.filter(e=>e.stage===`failed`||e.stage===`revert-failed`);return(0,K.jsxs)(wO,{title:n.label?`${n.label} — ${n.id}`:n.id,extra:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[u&&(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Z,{size:`sm`,type:`secondary`,disabled:o,onClick:()=>void l(`hold`),children:`Hold`}),(0,K.jsx)(Z,{size:`sm`,type:`secondary`,disabled:o,onClick:()=>void l(`resume`),children:`Resume`}),(0,K.jsx)(Z,{size:`sm`,type:`error`,disabled:o,onClick:()=>void l(`abort`),children:`Abort`})]}),(0,K.jsx)(Z,{size:`sm`,type:`secondary`,onClick:t,children:`Close`})]}),children:[(0,K.jsxs)(`div`,{className:q(`mb-4 rounded-md border p-3 text-sm`,n.outcome===`needs-attention`&&`border-red-500/40 bg-red-500/10`,n.outcome===`completed`&&`border-emerald-500/40 bg-emerald-500/10`,u&&`border-amber-500/40 bg-amber-500/10`),children:[(0,K.jsxs)(`div`,{className:`flex items-center gap-2 font-medium`,children:[(0,K.jsx)(jA,{type:n.outcome?G2[n.outcome]:`warning`,pulse:u}),n.outcome??`IN FLIGHT — wave ${n.phase}`]}),(0,K.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:n.outcome?Gbe[n.outcome]:`Applying wave by wave; each wave is gated and soaked before the next.`})]}),(0,K.jsx)(qbe,{rollout:n}),d.length>0&&(0,K.jsxs)(`div`,{className:`mt-4 rounded-md border border-red-500/40 p-3 text-sm`,children:[(0,K.jsx)(`div`,{className:`font-medium`,children:`Failures`}),(0,K.jsx)(`ul`,{className:`mt-1 space-y-1 font-mono text-xs text-muted-foreground`,children:d.map(e=>(0,K.jsxs)(`li`,{children:[e.device,` · `,e.stage,e.error?` — ${e.error}`:``,e.stage===`revert-failed`&&e.snapshotId?` · restore with diff_config_snapshots ${e.snapshotId} live`:``]},e.device))})]}),n.notes.length>0&&(0,K.jsx)(`ul`,{className:`mt-4 space-y-1 text-sm text-amber-600 dark:text-amber-400`,children:n.notes.map(e=>(0,K.jsxs)(`li`,{children:[`• `,e]},e))}),(0,K.jsx)(`h4`,{className:`mt-6 mb-2 text-sm font-medium`,children:`Commands`}),(0,K.jsx)(`pre`,{className:`overflow-x-auto rounded-md bg-muted/30 p-2 font-mono text-xs`,children:n.commands.join(`
238
238
  `)}),(0,K.jsx)(`h4`,{className:`mt-6 mb-2 text-sm font-medium`,children:`Timeline`}),i.length===0?(0,K.jsx)(`p`,{className:`text-sm text-muted-foreground`,children:`No steps recorded yet.`}):(0,K.jsx)(`ol`,{className:`space-y-1 font-mono text-xs`,children:i.map(e=>(0,K.jsxs)(`li`,{className:`flex gap-2`,children:[(0,K.jsx)(`span`,{className:`text-muted-foreground`,children:new Date(e.ts).toLocaleTimeString()}),(0,K.jsx)(`span`,{className:e.ok?`text-emerald-600 dark:text-emerald-400`:`text-red-500`,children:e.ok?`✓`:`✕`}),(0,K.jsxs)(`span`,{children:[e.kind,e.device?` ${e.device}`:``]})]},e.seq))})]})}function Ybe(){let[e,t]=(0,v.useState)([]),[n,r]=(0,v.useState)(null),[i,a]=(0,v.useState)(null),o=(0,v.useCallback)(()=>W(`/api/rollout`).then(e=>{t(e.rollouts),a(e.error??null)}).catch(e=>{a(e instanceof Error?e.message:String(e))}),[]);(0,v.useEffect)(()=>(o(),W2(()=>void o())),[o]);let s=e.filter(e=>e.outcome===void 0);return(0,K.jsxs)(`div`,{className:`space-y-4`,children:[n&&(0,K.jsx)(Jbe,{id:n,onClose:()=>r(null)}),i&&(0,K.jsx)(wO,{title:`Rollout history`,children:(0,K.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`The history could not be read (`,i,`); rollouts running right now are still shown.`]})}),(0,K.jsx)(wO,{title:`Rollouts`,extra:(0,K.jsxs)(`div`,{className:`flex items-center gap-2`,children:[s.length>0&&(0,K.jsxs)(kA,{type:`warning`,children:[s.length,` in flight`]}),(0,K.jsx)(Z,{size:`sm`,type:`secondary`,onClick:()=>void o(),children:`Refresh`})]}),children:e.length===0?(0,K.jsxs)(`p`,{className:`text-sm text-muted-foreground`,children:[`No rollouts yet. Preview one with `,(0,K.jsx)(`span`,{className:`font-mono`,children:`plan_rollout`}),`, then run it with `,(0,K.jsx)(`span`,{className:`font-mono`,children:`start_rollout`}),` — canary first, with a health gate and soak between waves.`]}):(0,K.jsx)(`ul`,{className:`divide-y divide-border`,children:e.map(e=>(0,K.jsx)(`li`,{children:(0,K.jsxs)(`button`,{type:`button`,onClick:()=>r(e.id),className:`flex w-full items-center gap-3 py-2 text-left hover:bg-muted/40`,children:[(0,K.jsx)(kA,{type:e.outcome?G2[e.outcome]:`warning`,children:e.outcome??`LIVE`}),(0,K.jsxs)(`span`,{className:`flex-1 truncate`,children:[e.label??e.id,(0,K.jsxs)(`span`,{className:`ml-2 text-xs text-muted-foreground`,children:[e.devices.length,` device(s) · `,e.waves.length,` wave(s)`]})]}),(0,K.jsx)(`span`,{className:`whitespace-nowrap text-xs text-muted-foreground`,children:Kbe(e.ts)})]})},e.id))})})]})}function q2({className:e,...t}){return(0,K.jsx)(`textarea`,{"data-slot":`textarea`,className:q(`flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:aria-invalid:ring-destructive/40`,e),...t})}var Xbe={add:`+`,set:`~`,remove:`−`,enable:`▲`,disable:`▽`,move:`⇅`},Zbe={high:`border-l-destructive`,medium:`border-l-warning`,low:`border-l-success`};function Qbe(){let[e,t]=(0,v.useState)(`plan`),[n,r]=(0,v.useState)(``),[i,a]=(0,v.useState)(null),[o,s]=(0,v.useState)(null),[c,l]=(0,v.useState)(!1),u=async()=>{l(!0),s(null);let e=await vc(`/api/plan`,{script:n}).catch(()=>({error:`request failed`}));if(l(!1),e.error||!e.plan){s(e.error??`no plan produced`),a(null),X.error(e.error??`no plan produced`);return}a({plan:e.plan,text:e.text??``}),X.success(`Plan ready`)},d=i?.plan.grade??``,f=d===`critical`||d===`high`,p=(0,K.jsxs)(`div`,{className:`mb-4 flex items-center gap-1`,children:[(0,K.jsx)(Z,{size:`sm`,type:e===`plan`?`default`:`secondary`,onClick:()=>t(`plan`),children:`Dry-run`}),(0,K.jsx)(Z,{size:`sm`,type:e===`rollout`?`default`:`secondary`,onClick:()=>t(`rollout`),children:`Rollout`})]});return e===`rollout`?(0,K.jsxs)(`div`,{children:[p,(0,K.jsx)(Ybe,{})]}):(0,K.jsxs)(K.Fragment,{children:[p,(0,K.jsxs)(`section`,{className:`grid content-start gap-[18px]`,children:[(0,K.jsxs)(wO,{title:`Change plan — dry-run`,className:`reveal`,extra:(0,K.jsx)(`span`,{className:`text-muted-foreground text-[11px]`,children:`terraform-style preview · pure analysis, never touches a device`}),children:[(0,K.jsx)(q2,{className:`min-h-40 resize-y font-mono text-xs leading-relaxed`,spellCheck:!1,placeholder:`Paste intended RouterOS commands, one per line, e.g.
239
239
  /ip firewall filter add chain=input action=drop in-interface=WAN
240
240
  /ip address add address=10.0.0.1/24 interface=ether1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usex/mikrotik-mcp",
3
- "version": "5.21.0",
3
+ "version": "5.22.0",
4
4
  "description": "MCP server for MikroTik RouterOS — 780+ tools over SSH for firewall, NAT, routing, DHCP, DNS, WireGuard, wireless, QoS and more.",
5
5
  "keywords": [
6
6
  "ai",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "format": 1,
3
- "version": "5.21.0",
3
+ "version": "5.22.0",
4
4
  "modules": [
5
5
  {
6
6
  "slug": "client-check",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
- "version": "5.21.0",
3
+ "version": "5.22.0",
4
4
  "generated": "by scripts/gen-schemas.ts — do not edit by hand",
5
5
  "toolCount": 960,
6
6
  "tools": [