All files / src/apps/user/pages/rules NewRule.tsx

82.57% Statements 218/264
84.77% Branches 206/243
70% Functions 77/110
85.1% Lines 200/235

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238                                                                                                                                                          161x 145x     4x     4x                       4x           26x 4x             22x               22x                     22x                                 22x                           22x 22x                                             4x           161x 324x   161x   161x           161x     161x         161x 161x 145x 145x 145x     161x     26x     26x 25x 25x 26x 26x   26x                                                   25x   25x                               25x                                                                               145x                                                         4x         3x 3x     1x     3x 3x 3x 3x 2x       3x                                                             4x       4x 203x     4x 111x   4x             111x 36x 111x     111x 2x     109x                         109x 17x         92x 17x         2x             75x     6x     6x     6x 1x 1x 1x 2x   6x             12x             1x                 69x 6x       1x         12x               63x         2x                         61x                               4x           161x   161x   161x 15x   161x             161x 10x   161x   161x     134x   81x                             207x                         112x   111x                     10x                                                                 339x     15x                             4x           805x                                         4x       4x 164x         4x       5x 5x                                                       4x 191x 191x 191x 191x             191x 191x       191x     191x 191x 191x           191x   191x 191x 191x 191x 20x           191x 42x 42x   191x 27x             191x 191x   3x         191x 191x       191x 191x 46x 2x 2x 2x 2x 46x 46x 46x 46x   46x         191x   42x       191x             191x 3x 3x 3x 3x           364x 191x 61x           191x           191x 393x     191x 191x   191x 3x     3x           191x   42x               191x   191x 32x   191x   5x       5x 5x 2x       5x 5x 5x           191x 5x 5x       5x                           191x   191x                                                             764x 764x 764x 764x 764x 764x         3x                                                                                                                                                   405x 405x       3x                                                                     1x                   24x                                                         26x 26x                                                                                                                                                                                                                                   37x      
import { encodeResourceId } from "@/components/detail";
import SubPage from "@/components/page/SubPage/SubPage";
import { isSystemManaged } from "@/objects/Doc";
import {
  blankAction,
  blankCondition,
  Rule,
  RuleAction,
  RuleActionSpec,
  RuleCatalogue,
  RuleCondition,
  RuleCreate,
  RuleUpdate,
  RuleFieldSpec,
  RuleOperatorSpec,
  RuleScope,
  RuleScopeSpec,
  RuleScopeTarget,
  RuleScopeTargets,
  RuleLayer,
  RuleLayerSpec,
  RuleVocabularyEntry,
  paramShown,
  ruleLayerSpec,
  ruleOperators,
  ruleScopes,
  vocabularyEntries,
  DOMAIN_ITEM,
  PII_KINDS_VOCABULARY,
} from "@/objects/Rule";
import {
  FROM_BUILT_IN_PARAM,
  LAYER_PARAM,
  ruleHref,
} from "@/apps/user/pages/rules/links";
import DomainListInput from "@/apps/user/pages/rules/DomainListInput";
import {
  applyDomainEdit,
  describeDomainEdit,
  domainEditOf,
} from "@/apps/user/pages/rules/domainEdit";
import PiiKindsInput from "@/apps/user/pages/rules/PiiKindsInput";
import {
  RULE_LAYERS,
  ruleLayerMeta,
} from "@/apps/user/pages/rules/ruleLayer";
import { APP_ROUTES } from "@/routes/const";
import { QUERY_KEYS, INCLUDE_SYSTEM } from "@/services/query_keys";
import { DEFAULT_PASS_MARK, TestSuite } from "@/objects/Evaluation";
import { useApiHandler } from "@/services/useApiHandler";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  AlertTriangle,
  BadgeCheck,
  Globe,
  Minus,
  Plus,
  ShieldCheck,
} from "lucide-react";
import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
 
// ─── Vocabulary ───────────────────────────────────────────────────────────────
//
// The scopes, condition fields, operators and actions a rule may use are NOT
// listed here. They come from `GET /app/rules/catalogue`, which serves
// svc-core's registries, so the builder can only ever offer something the
// engine can actually evaluate. Hard-coding them meant every backend widening
// needed a matching frontend release — and a mismatch produced a rule the user
// believed was governing them while the engine skipped it with a warning.
//
// The scope list was the last hard-coded one, and it had already drifted: it
// offered five scopes while the engine matched on one at a time, and it had
// no way to express "everything in this project" at all.
 
/** Quick-add condition buttons — the first few fields the backend offers. */
const conditionPresets = (spec?: RuleLayerSpec): RuleFieldSpec[] =>
  (spec?.fields ?? []).filter((field) => field?.key !== "always").slice(0, 3);
 
const inputCls =
  "px-2.5 py-1.5 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 font-mono placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300 dark:focus:ring-gray-500 w-full";
 
const selectCls =
  "px-2.5 py-1.5 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-300 dark:focus:ring-gray-500 w-full";
 
// ─── Condition value input ────────────────────────────────────────────────────
 
/**
 * The right input control for one condition, chosen from the field's value
 * type and the operator's operand.
 *
 * The two differ: `execution_type` is an enum, but `execution_type is one of
 * …` collects a comma-separated set, not a single choice. The operand wins
 * wherever they disagree, because it describes what the *comparison* needs.
 */
const ConditionValueInput: React.FC<{
  field?: RuleFieldSpec;
  operator?: RuleOperatorSpec;
  value: string;
  onChange: (value: string) => void;
}> = ({ field, operator, value, onChange }) => {
  if (!field || field.value_type === "none") {
    return (
      <span className="flex items-center text-xs text-gray-400 dark:text-gray-500 italic px-1">
        always matches
      </span>
    );
  }
 
  Iif (field.vocabulary === PII_KINDS_VOCABULARY && operator?.operand === "list") {
    // The kinds the detectors know, by name and grouped — not a free-text
    // list of keys to remember.
    return (
      <PiiKindsInput value={value} onChange={onChange} label={field.label} />
    );
  }
 
  Iif (operator?.operand === "list") {
    return (
      <input
        placeholder="comma, separated, values"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={inputCls}
      />
    );
  }
 
  Iif (field.value_type === "enum" && field.options.length > 0) {
    return (
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={selectCls}
      >
        <option value="">Select…</option>
        {field.options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    );
  }
 
  Iif (field.value_type === "boolean") {
    return (
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={selectCls}
      >
        <option value="">Select…</option>
        <option value="true">true</option>
        <option value="false">false</option>
      </select>
    );
  }
 
  Eif (field.value_type === "number") {
    return (
      <input
        type="number"
        placeholder="0"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={inputCls}
      />
    );
  }
 
  return (
    <input
      placeholder="value"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className={inputCls}
    />
  );
};
 
// ─── Condition editor ─────────────────────────────────────────────────────────
 
const ConditionEditor: React.FC<{
  conditions: RuleCondition[];
  onChange: (cs: RuleCondition[]) => void;
  typeSpec?: RuleLayerSpec;
  operators: RuleOperatorSpec[];
}> = ({ conditions, onChange, typeSpec, operators }) => {
  const fields = typeSpec?.fields ?? [];
  const operatorByKey = new Map(operators.map((op) => [op.key, op]));
 
  const add = () => onChange([...conditions, blankCondition(typeSpec)]);
 
  const addPreset = (field: RuleFieldSpec) =>
    onChange([
      ...conditions,
      { field: field.key, operator: field.operators[0] ?? "eq", value: "" },
    ]);
 
  const update = (i: number, patch: Partial<RuleCondition>) =>
    onChange(conditions.map((c, idx) => (idx === i ? { ...c, ...patch } : c)));
 
  const remove = (i: number) =>
    onChange(conditions.filter((_, idx) => idx !== i));
 
  // Fields arrive grouped by the backend (content, invocation, cost, …);
  // preserve that order rather than sorting, so related fields stay adjacent.
  const groups: { group: string; fields: RuleFieldSpec[] }[] = [];
  fields.forEach((field) => {
    const existing = groups.find((g) => g.group === field.group);
    Iif (existing) existing.fields.push(field);
    else groups.push({ group: field.group, fields: [field] });
  });
 
  return (
    <div className="space-y-3">
      {conditions.map((c, i) => {
        const fieldSpec = fields.find((f) => f.key === c.field);
        // An operator the field does not support would never match, so the
        // dropdown offers only the legal pairings the backend computed.
        const validOps = (fieldSpec?.operators ?? [])
          .map((key) => operatorByKey.get(key))
          .filter((op): op is RuleOperatorSpec => Boolean(op));
        const operatorSpec = operatorByKey.get(c.operator);
        const isUnary = !fieldSpec || fieldSpec.value_type === "none";
 
        return (
          <div
            key={i}
            className="flex items-start gap-2 p-3 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-800/50"
          >
            <span className="shrink-0 flex items-center justify-center size-5 rounded-full bg-gray-200 dark:bg-gray-600 text-xs font-mono text-gray-600 dark:text-gray-300 mt-2">
              {i + 1}
            </span>
            <div className="flex-1 space-y-2">
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                {/* Field dropdown, grouped as the backend groups them */}
                <select
                  value={c.field}
                  onChange={(e) => {
                    const next = fields.find((f) => f.key === e.target.value);
                    update(i, {
                      field: e.target.value,
                      // Carrying the old operator over could leave an illegal
                      // pairing selected, which silently never matches.
                      operator: next?.operators[0] ?? "eq",
                      value: "",
                    });
                  }}
                  className={selectCls}
                >
                  {groups.map((group) => (
                    <optgroup key={group.group} label={group.group}>
                      {group.fields.map((f) => (
                        <option key={f.key} value={f.key}>
                          {f.key}
                        </option>
                      ))}
                    </optgroup>
                  ))}
                </select>
 
                {/* Operator dropdown — only pairings the engine accepts */}
                <select
                  value={c.operator}
                  onChange={(e) => update(i, { operator: e.target.value })}
                  disabled={isUnary}
                  className={selectCls}
                >
                  {validOps.map((op) => (
                    <option key={op.key} value={op.key}>
                      {op.label}
                    </option>
                  ))}
                </select>
 
                <ConditionValueInput
                  field={fieldSpec}
                  operator={operatorSpec}
                  value={String(c.value ?? "")}
                  onChange={(value) => update(i, { value })}
                />
              </div>
              {fieldSpec && (
                <p className="text-xs text-gray-400 dark:text-gray-500 leading-relaxed">
                  {fieldSpec.description}
                </p>
              )}
            </div>
            <button
              type="button"
              onClick={() => remove(i)}
              className="shrink-0 p-1.5 rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors mt-1"
            >
              <Minus className="size-3.5" />
            </button>
          </div>
        );
      })}
 
      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          onClick={add}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 text-xs text-gray-500 dark:text-gray-400 hover:border-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
        >
          <Plus className="size-3.5" />
          Add condition
        </button>
        {conditionPresets(typeSpec).map((field) => (
          <button
            key={field.key}
            type="button"
            onClick={() => addPreset(field)}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors font-mono"
          >
            {field.key}
          </button>
        ))}
      </div>
    </div>
  );
};
 
// ─── Action editor ────────────────────────────────────────────────────────────
 
/**
 * One action parameter input, rendered from the catalogue's param spec.
 *
 * Previously each parameter had its own `type === "block"` branch here, which
 * meant a new action's parameters were invisible until someone added another
 * branch. Rendering from the spec means a new action is usable the moment the
 * backend registers it.
 */
/**
 * A parameter that names a dataset by id — the evidence gate's. Offers the
 * caller's datasets and the gold ones by name; "any dataset" is the empty
 * value, which the gate reads as "every dataset the version ran must pass".
 */
const DatasetParamInput: React.FC<{
  param: RuleActionSpec["params"][number];
  value: string;
  onChange: (value: string) => void;
}> = ({ param, value, onChange }) => {
  const { getApiHandler } = useApiHandler();
  const { data, isLoading } = useQuery<TestSuite[]>({
    queryKey: [QUERY_KEYS.GET.TEST_SUITES, INCLUDE_SYSTEM],
    queryFn: () =>
      getApiHandler().evaluation_router.listTestSuites({ includeSystem: true }),
    staleTime: 60_000,
  });
  const datasets: TestSuite[] = data ?? [];
  const builtIn = datasets.filter((d) => d.is_system);
  const own = datasets.filter((d) => !d.is_system);
  const option = (d: TestSuite) => (
    <option key={d.id} value={d.id}>
      {d.name} — pass {(d.pass_mark ?? DEFAULT_PASS_MARK).toFixed(2)}
    </option>
  );
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className={selectCls}
      aria-label={param.label}
      title={param.description}
      disabled={isLoading}
    >
      <option value="">{param.label}: any — every dataset it ran must pass</option>
      {builtIn.length > 0 && <optgroup label="Built-in">{builtIn.map(option)}</optgroup>}
      {own.length > 0 && (
        <optgroup label="Your datasets">{own.map(option)}</optgroup>
      )}
      {/* A saved id this list does not hold, kept visible rather than
          silently shown as "any". */}
      {value && !datasets.some((d) => d.id === value) && !isLoading && (
        <option value={value}>Unknown dataset ({value.slice(0, 8)}…)</option>
      )}
    </select>
  );
};
 
/** Pickers for parameters that name a resource, by resource kind. */
const RESOURCE_PARAM_INPUTS: Record<
  string,
  React.FC<{
    param: RuleActionSpec["params"][number];
    value: string;
    onChange: (value: string) => void;
  }>
> = { dataset: DatasetParamInput };
 
/** A yes / no setting with a default — "Use only these" — rather than a
 *  requirement that may be left unstated (a capability check). */
const isTwoState = (param: RuleActionSpec["params"][number]) =>
  param.value_type === "boolean" && typeof param.default === "boolean";
 
/** Inputs that carry their own label, so the editor does not title them. */
const titlesItself = (param: RuleActionSpec["params"][number]) =>
  param.vocabulary === PII_KINDS_VOCABULARY || isTwoState(param);
 
const ActionParamInput: React.FC<{
  param: RuleActionSpec["params"][number];
  value: string;
  onChange: (value: string) => void;
  /** The catalogue's labels for `param.options`, when it names them. */
  entries?: RuleVocabularyEntry[];
}> = ({ param, value, onChange, entries = [] }) => {
  const labelOf = (option: string) =>
    entries.find((entry) => entry.key === option)?.label ?? option;
  const ResourceInput = param.resource
    ? RESOURCE_PARAM_INPUTS[param.resource]
    : undefined;
  if (ResourceInput) {
    return <ResourceInput param={param} value={value} onChange={onChange} />;
  }
 
  Iif (param.vocabulary === PII_KINDS_VOCABULARY) {
    // Empty is meaningful here — the default set — so the picker offers it
    // as a choice rather than leaving it to an empty box.
    return (
      <PiiKindsInput
        value={value}
        onChange={onChange}
        allowDefault
        label={param.label}
      />
    );
  }
 
  if (param.item === DOMAIN_ITEM) {
    return (
      <DomainListInput value={value} onChange={onChange} label={param.label} />
    );
  }
 
  if (isTwoState(param)) {
    return (
      <label className="inline-flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">
        <input
          type="checkbox"
          checked={value === "true"}
          onChange={(e) => onChange(e.target.checked ? "true" : "false")}
        />
        {param.label}
      </label>
    );
  }
 
  if (param.options.length > 0 && param.value_type === "list") {
    // Several of a closed set — a budget for some kinds of work: one box
    // each, labelled from the catalogue. None ticked means all of them.
    const chosen = new Set(
      value
        .split(",")
        .map((part) => part.trim())
        .filter(Boolean),
    );
    const toggle = (option: string) => {
      const next = new Set(chosen);
      Iif (next.has(option)) next.delete(option);
      else next.add(option);
      onChange(param.options.filter((o) => next.has(o)).join(","));
    };
    return (
      <div
        role="group"
        aria-label={param.label}
        className="flex flex-wrap gap-x-4 gap-y-1.5"
      >
        {param.options.map((option) => (
          <label
            key={option}
            className="inline-flex items-center gap-1.5 text-xs text-gray-700 dark:text-gray-300"
          >
            <input
              type="checkbox"
              checked={chosen.has(option)}
              onChange={() => toggle(option)}
            />
            {labelOf(option)}
          </label>
        ))}
      </div>
    );
  }
 
  if (param.options.length > 0) {
    return (
      <select
        aria-label={param.label}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={selectCls}
      >
        <option value="">Select…</option>
        {param.options.map((option) => (
          <option key={option} value={option}>
            {labelOf(option)}
          </option>
        ))}
      </select>
    );
  }
 
  if (param.value_type === "boolean") {
    // A capability requirement is tri-state: unset means "do not check this",
    // which is not the same as requiring false. Rendering it as a checkbox
    // would collapse those two and silently turn an unstated requirement into
    // a stated negative one.
    return (
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={selectCls}
      >
        <option value="">{param.label} — not required</option>
        <option value="true">{param.label} — required</option>
        <option value="false">{param.label} — must not</option>
      </select>
    );
  }
 
  return (
    <input
      aria-label={param.label}
      type={param.value_type === "number" ? "number" : "text"}
      placeholder={
        param.value_type === "list"
          ? "comma, separated, values"
          : param.description || param.label
      }
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className={inputCls}
    />
  );
};
 
const ActionEditor: React.FC<{
  actions: RuleAction[];
  onChange: (as: RuleAction[]) => void;
  typeSpec?: RuleLayerSpec;
  catalogue?: RuleCatalogue | null;
}> = ({ actions, onChange, typeSpec, catalogue }) => {
  const available = typeSpec?.actions ?? [];
 
  const add = () => onChange([...actions, blankAction(available[0])]);
 
  const addPreset = (spec: RuleActionSpec) =>
    onChange([...actions, blankAction(spec)]);
 
  const updateType = (i: number, type: string) => {
    const spec = available.find((a) => a.type === type);
    // Replace rather than merge: parameters belong to an action type, and
    // keeping the old one's would send a block message on a redaction.
    onChange(actions.map((a, idx) => (idx === i ? blankAction(spec) : a)));
  };
 
  const updateParam = (i: number, key: string, value: string) =>
    onChange(actions.map((a, idx) => (idx === i ? { ...a, [key]: value } : a)));
 
  const remove = (i: number) => onChange(actions.filter((_, idx) => idx !== i));
 
  return (
    <div className="space-y-3">
      {actions.map((a, i) => {
        const spec = available.find((m) => m.type === a.type);
 
        return (
          <div
            key={i}
            className="flex items-start gap-2 p-3 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-800/50"
          >
            <span className="shrink-0 flex items-center justify-center size-5 rounded-full bg-gray-200 dark:bg-gray-600 text-xs font-mono text-gray-600 dark:text-gray-300 mt-2">
              {i + 1}
            </span>
            <div className="flex-1 space-y-2">
              <select
                value={a.type}
                onChange={(e) => updateType(i, e.target.value)}
                className={selectCls}
              >
                {available.map((m) => (
                  <option key={m.type} value={m.type}>
                    {m.label || m.type}
                  </option>
                ))}
              </select>
 
              {spec && (
                <p className="text-xs text-gray-400 dark:text-gray-500 leading-relaxed">
                  {spec.description}
                </p>
              )}
 
              {spec?.params
                .filter((param) => paramShown(param, a, spec))
                .map((param) => (
                  <div key={param.key} className="space-y-1">
                    {/* The PII picker and a yes / no box title themselves. */}
                    {!titlesItself(param) && (
                      <span className="block text-xs font-medium text-gray-600 dark:text-gray-300">
                        {param.label}
                        {param.required ? " *" : ""}
                      </span>
                    )}
                    <ActionParamInput
                      param={param}
                      value={String(a[param.key] ?? "")}
                      onChange={(value) => updateParam(i, param.key, value)}
                      entries={vocabularyEntries(catalogue, param.vocabulary)}
                    />
                    {param.description &&
                      param.vocabulary !== PII_KINDS_VOCABULARY && (
                        <span className="block text-[11px] leading-snug text-gray-400 dark:text-gray-500">
                          {param.description}
                        </span>
                      )}
                  </div>
                ))}
            </div>
            <button
              type="button"
              onClick={() => remove(i)}
              className="shrink-0 p-1.5 rounded-lg text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30 transition-colors mt-1"
            >
              <Minus className="size-3.5" />
            </button>
          </div>
        );
      })}
 
      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          onClick={add}
          className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 text-xs text-gray-500 dark:text-gray-400 hover:border-gray-400 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
        >
          <Plus className="size-3.5" />
          Add action
        </button>
        {available.map((spec) => (
          <button
            key={spec.type}
            type="button"
            onClick={() => addPreset(spec)}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
          >
            {spec.label || spec.type}
          </button>
        ))}
      </div>
    </div>
  );
};
 
// ─── Steps ────────────────────────────────────────────────────────────────────
 
/** One numbered step of the builder: what a rule is, in the order a person
 *  thinks it — where it acts, what it does, when, over what, and its name. */
const Step: React.FC<{
  n: number;
  title: string;
  hint?: React.ReactNode;
  children: React.ReactNode;
}> = ({ n, title, hint, children }) => (
  <section className="space-y-3">
    <div className="flex items-start gap-3">
      <span className="mt-0.5 inline-flex size-5 shrink-0 items-center justify-center rounded-full border border-gray-300 dark:border-gray-600 text-[11px] font-semibold text-gray-600 dark:text-gray-300 tabular-nums">
        {n}
      </span>
      <div className="min-w-0">
        <h3 className="text-sm font-semibold text-gray-800 dark:text-gray-200">
          {title}
        </h3>
        {hint && (
          <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400 leading-relaxed">
            {hint}
          </p>
        )}
      </div>
    </div>
    <div className="pl-8">{children}</div>
  </section>
);
 
const fieldInputCls =
  "w-full px-3 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300 dark:focus:ring-gray-500";
 
/** The layers a link may preselect (`?layer=`), validated against the
 *  registry rather than trusted. */
const requestedLayerOf = (raw: string | null): RuleLayer | null =>
  raw && (RULE_LAYERS as readonly string[]).includes(raw) ? (raw as RuleLayer) : null;
 
// ─── RuleBuilder ──────────────────────────────────────────────────────────────
 
/** What the change a link asked for came to, above the form. */
const DomainEditBanner: React.FC<{ text: string; warn: boolean }> = ({
  text,
  warn,
}) => {
  const Icon = warn ? AlertTriangle : Globe;
  return (
    <div
      role="status"
      className={`flex items-start gap-2.5 p-3 rounded-lg border text-sm ${
        warn
          ? "border-amber-200 dark:border-amber-800/60 bg-amber-50 dark:bg-amber-950/30 text-amber-800 dark:text-amber-200"
          : "border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/60 text-gray-700 dark:text-gray-200"
      }`}
    >
      <Icon className="size-4 shrink-0 mt-0.5" aria-hidden="true" />
      <p>{text}</p>
    </div>
  );
};
 
export interface RuleBuilderProps {
  /** The rule being edited; absent to create one. */
  editing?: Rule;
}
 
/**
 * Write or edit a rule, in the order a person thinks one: **where** in a
 * request it acts (its layer), **what** it does, **when** (always, unless
 * conditions are added), **over what** (its scope), then its name — which
 * starts as what its first action does, until the person writes their own.
 * Priority and whether it is on sit under "More settings": neither is a
 * decision most rules need.
 */
export const RuleBuilder: React.FC<RuleBuilderProps> = ({ editing }) => {
  const { getApiHandler } = useApiHandler();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [searchParams] = useSearchParams();
 
  // Pre-select the scope and target when launched from a resource, e.g.
  // ?scope=agent&target=<id> from an agent's detail page, and the layer from
  // a layer's "Add" on the Rules page (?layer=output). Validated against the
  // catalogue and the registry rather than trusted, so a link can only
  // preselect something the engine has.
  const requestedScope = editing ? editing.scope_type : searchParams.get("scope");
  const requestedTarget = editing
    ? editing.scope_id ?? ""
    : searchParams.get("target") ?? "";
 
  const [name, setName] = useState(editing?.name ?? "");
  // A name the person has typed is theirs; until then it follows what the
  // rule's first action does.
  const [nameTouched, setNameTouched] = useState(!!editing);
  const [description, setDescription] = useState(editing?.description ?? "");
  const [layer, setLayer] = useState<RuleLayer>(
    editing?.layer ?? requestedLayerOf(searchParams.get(LAYER_PARAM)) ?? "input",
  );
  // `null` until the user (or the catalogue) settles it — distinct from
  // "global", so a `?scope=` from a link is not overwritten by a default the
  // moment the catalogue resolves.
  const [scopeChoice, setScopeChoice] = useState<RuleScope | null>(null);
  // Empty string = rule applies to ALL resources of the selected scope type.
  const [scopeId, setScopeId] = useState(requestedTarget);
  const [isActive, setIsActive] = useState(editing?.is_active ?? true);
  const [priority, setPriority] = useState(editing?.priority ?? 0);
  const [conditions, setConditions] = useState<RuleCondition[]>(
    editing ? editing.conditions.map((c) => ({ ...c })) : [],
  );
  // A change the note under an answer offers a Tools rule
  // (`?add_trusted=` / `?remove_blocked=`): made once, on the rule as it
  // opens, and said in a banner. Saving is the person's — the rule's
  // ordinary edit, with its version; a link alone never changes a rule.
  const [domainEdit] = useState(() => {
    const edit = editing ? domainEditOf(searchParams) : null;
    return edit && editing ? applyDomainEdit(editing.actions, edit) : null;
  });
  const [actions, setActions] = useState<RuleAction[]>(
    editing ? (domainEdit?.actions ?? editing.actions).map((a) => ({ ...a })) : [],
  );
 
  // A built-in rule to start from: `?from=<id>`, from its card or its page.
  // Only a built-in seeds the form — anything else the link names is
  // ignored, and the server refuses it as a source too. Never when editing:
  // a rule's source is fixed when it is created.
  const fromId = editing ? null : searchParams.get(FROM_BUILT_IN_PARAM);
  const { data: fromData } = useQuery<Rule | null>({
    queryKey: [`${QUERY_KEYS.GET.RULE_BY_ID}:${fromId}`],
    queryFn: () => getApiHandler().rule_router.get(fromId!),
    enabled: !!fromId,
  });
  // Bound to an explicit type: the pinned TypeScript cannot infer
  // react-query v5's return type (docs/guides/frontend-components.md).
  const fromRule: Rule | null = fromData ?? null;
  const builtIn = fromRule && isSystemManaged(fromRule) ? fromRule : null;
 
  // Seeded once per built-in, then the form is the user's: the catalogue or
  // the rule refetching must not overwrite what they have changed since.
  const [seededFrom, setSeededFrom] = useState<string | null>(null);
  useEffect(() => {
    if (!builtIn || seededFrom === builtIn.id) return;
    setSeededFrom(builtIn.id);
    setName(builtIn.name);
    setNameTouched(true);
    setDescription(builtIn.description ?? "");
    setLayer(builtIn.layer);
    setConditions(builtIn.conditions.map((c) => ({ ...c })));
    setActions(builtIn.actions.map((a) => ({ ...a })));
    setPriority(builtIn.priority);
    // Created switched on: using a rule is asking for it to govern.
    setIsActive(true);
  }, [builtIn, seededFrom]);
 
  // The grammar the engine can evaluate. Cached indefinitely: it describes
  // the backend build, not the user's data, so it only changes on deploy.
  const { data: catalogue } = useQuery<RuleCatalogue | null>({
    queryKey: [QUERY_KEYS.GET.RULE_CATALOGUE],
    queryFn: () => getApiHandler().rule_router.catalogue(),
    staleTime: Infinity,
  });
 
  const typeSpec = ruleLayerSpec(catalogue, layer);
 
  // Changing the layer changes which fields and actions exist, so any
  // conditions and actions already composed are no longer necessarily valid
  // — an Output rule's `response` condition means nothing on an Input rule.
  // Clearing is the honest option; silently keeping them would submit a rule
  // the engine skips.
  const changeLayer = (next: RuleLayer) => {
    Iif (next === layer) return;
    setLayer(next);
    setConditions([]);
    setActions([]);
  };
 
  // What the first action does, as the catalogue labels it — the name a
  // rule starts with until the person writes one.
  const suggestedName =
    typeSpec?.actions.find((spec) => spec.type === actions[0]?.type)?.label ?? "";
  useEffect(() => {
    if (!nameTouched) setName(suggestedName);
  }, [nameTouched, suggestedName]);
 
  // The scopes a rule may be written against, broad to narrow. One list from
  // the backend registry — the builder no longer has its own, and a scope
  // added there becomes selectable without a release here.
  const scopeSpecs: RuleScopeSpec[] = ruleScopes(catalogue);
 
  // Resolved rather than stored, so a `?scope=` link survives the catalogue
  // arriving and an unknown one falls back to the broadest scope instead of
  // submitting something the backend will refuse.
  const scopeType: RuleScope =
    scopeChoice ??
    (scopeSpecs.some((spec) => spec.key === requestedScope)
      ? (requestedScope as RuleScope)
      : editing?.scope_type ?? "global");
  const scopeSpec = scopeSpecs.find((spec) => spec.key === scopeType);
  const canPin = scopeSpec ? scopeSpec.targets_resource : scopeType !== "global";
 
  const changeScope = (next: RuleScope) => {
    setScopeChoice(next);
    // A target belongs to the scope it was chosen under; carrying it across
    // would submit an agent id as a model scope, which the backend refuses.
    setScopeId("");
  };
 
  // Everything the user may pin a rule to, in one request rather than six.
  // Shared cache key with the rules list, which uses the same payload to
  // label each rule's scope.
  const { data: scopeTargets } = useQuery<RuleScopeTargets | null>({
    queryKey: [QUERY_KEYS.GET.RULE_SCOPE_TARGETS],
    queryFn: () => getApiHandler().rule_router.targets(),
    staleTime: 60_000,
  });
 
  // Bound to an explicit type: the pinned TypeScript cannot infer react-query
  // v5's return type, so `scopeTargets` arrives as `any` and everything read
  // off it goes unchecked. See docs/guides/frontend-components.md.
  const scopeResources: RuleScopeTarget[] =
    (scopeTargets as RuleScopeTargets | null)?.targets?.[scopeType] ?? [];
 
  const ruleUrl = (id: string) =>
    APP_ROUTES.USER.GOVERNANCE.RULES.id.replace(":ruleId", encodeResourceId(id));
 
  const mutation = useMutation({
    mutationFn: (body: RuleCreate) =>
      editing
        ? getApiHandler().rule_router.update(editing.id, body as RuleUpdate)
        : getApiHandler().rule_router.create(body),
    onSuccess: (saved) => {
      void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.RULES] });
      if (editing) {
        void queryClient.invalidateQueries({
          queryKey: [`${QUERY_KEYS.GET.RULE_BY_ID}:${editing.id}`],
        });
      }
      toast.success(editing ? "Rule saved" : "Rule created");
      const id = saved?.id ?? editing?.id;
      void navigate(id ? ruleUrl(id) : APP_ROUTES.USER.rules);
    },
    onError: () =>
      toast.error(editing ? "Failed to save rule" : "Failed to create rule"),
  });
 
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    Iif (!name.trim()) {
      toast.error("Name is required");
      return;
    }
    mutation.mutate({
      name: name.trim(),
      description: description.trim() || undefined,
      layer,
      scope_type: scopeType,
      scope_id: canPin && scopeId ? scopeId : undefined,
      conditions,
      actions,
      is_active: isActive,
      priority,
      ...(editing ? {} : { based_on_rule_id: builtIn?.id }),
    });
  };
 
  const back = editing ? ruleUrl(editing.id) : APP_ROUTES.USER.rules;
 
  return (
    <SubPage title={editing ? "Edit Rule" : "New Rule"} back={back}>
      <form onSubmit={handleSubmit} className="space-y-8 max-w-2xl">
        {builtIn && (
          <div className="flex items-start gap-2.5 p-3 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/60 text-sm text-gray-700 dark:text-gray-200">
            <BadgeCheck className="size-4 shrink-0 mt-0.5" aria-hidden="true" />
            <p>
              Starting from the built-in rule{" "}
              <Link
                to={ruleHref(builtIn.id)}
                className="font-semibold hover:underline"
              >
                {builtIn.name}
              </Link>
              . Choose its scope and adjust anything you need, then create it
              as a rule of your own. Later releases of the built-in will not
              change it.
            </p>
          </div>
        )}
        {domainEdit && (
          <DomainEditBanner {...describeDomainEdit(domainEdit)} />
        )}
 
        <Step
          n={1}
          title="Where in a request it acts"
          hint="Requests meet the layers in this order. Each layer offers its own conditions and actions."
        >
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            {RULE_LAYERS.map((value) => {
              const meta = ruleLayerMeta(value);
              const spec = ruleLayerSpec(catalogue, value);
              const Icon = meta.Icon;
              const label = spec?.label ?? meta.label;
              const selected = layer === value;
              return (
                <button
                  key={value}
                  type="button"
                  aria-pressed={selected}
                  onClick={() => changeLayer(value)}
                  className={`flex flex-col items-start gap-2 p-4 rounded-xl border text-left transition-all ${
                    selected
                      ? "border-gray-900 dark:border-white bg-gray-50 dark:bg-gray-800"
                      : "border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-500"
                  }`}
                >
                  <Icon
                    className={`size-5 ${
                      selected
                        ? "text-gray-900 dark:text-white"
                        : "text-gray-400 dark:text-gray-500"
                    }`}
                  />
                  <div>
                    <div
                      className={`text-sm font-semibold ${
                        selected
                          ? "text-gray-900 dark:text-white"
                          : "text-gray-700 dark:text-gray-300"
                      }`}
                    >
                      {label}
                    </div>
                    {spec?.summary && (
                      <div className="text-xs font-medium text-gray-600 dark:text-gray-300 mt-0.5">
                        {spec.summary}
                      </div>
                    )}
                    {spec?.description && (
                      <div className="text-xs text-gray-500 dark:text-gray-400 mt-1 leading-relaxed">
                        {spec.description}
                      </div>
                    )}
                  </div>
                </button>
              );
            })}
          </div>
        </Step>
 
        <Step n={2} title="What it does">
          <ActionEditor
            actions={actions}
            onChange={setActions}
            typeSpec={typeSpec}
            catalogue={catalogue}
          />
        </Step>
 
        <Step
          n={3}
          title="When it applies"
          hint={
            conditions.length === 0
              ? "Always — to every request in its scope. Add a condition to narrow it."
              : "When every condition holds."
          }
        >
          <ConditionEditor
            conditions={conditions}
            onChange={setConditions}
            typeSpec={typeSpec}
            operators={ruleOperators(catalogue)}
          />
        </Step>
 
        <Step
          n={4}
          title="What it covers"
          hint="Scopes nest — a rule on a project covers every agent in it, and a request meets every rule over anything it touches."
        >
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
            {scopeSpecs.map((spec) => {
              const selected = scopeType === spec.key;
              return (
                <button
                  key={spec.key}
                  type="button"
                  onClick={() => changeScope(spec.key)}
                  className={`flex flex-col items-start gap-0.5 p-3 rounded-lg border text-left transition-all ${
                    selected
                      ? "border-gray-900 dark:border-white bg-gray-50 dark:bg-gray-800"
                      : "border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-500"
                  }`}
                >
                  <span
                    className={`text-sm font-semibold ${
                      selected
                        ? "text-gray-900 dark:text-white"
                        : "text-gray-700 dark:text-gray-300"
                    }`}
                  >
                    {spec.label}
                  </span>
                  <span className="text-xs text-gray-500 dark:text-gray-400 leading-relaxed">
                    {spec.description}
                  </span>
                </button>
              );
            })}
          </div>
 
          {canPin && (
            <div className="mt-3">
              <label
                htmlFor="rule-target"
                className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5 block"
              >
                Applies to
              </label>
              <select
                id="rule-target"
                value={scopeId}
                onChange={(e) => setScopeId(e.target.value)}
                className={fieldInputCls}
              >
                {/* The default is the whole kind, not the first resource —
                    "every agent" is both the commoner intent and the safer
                    one to land on by accident. */}
                <option value="">
                  {scopeSpec?.plural ?? `All ${scopeType}s`}
                </option>
                {scopeResources.map((r) => (
                  <option key={r.id} value={r.id}>
                    {r.label}
                  </option>
                ))}
              </select>
              {scopeResources.length === 0 && (
                <p className="mt-1.5 text-xs text-gray-400 dark:text-gray-500">
                  You have no {scopeType}s to target yet — this rule will cover
                  every {scopeType} you create.
                </p>
              )}
            </div>
          )}
        </Step>
 
        <Step n={5} title="Name">
          <div className="space-y-4">
            <div>
              <label
                htmlFor="rule-name"
                className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5 block"
              >
                Name <span className="text-red-500">*</span>
              </label>
              <input
                id="rule-name"
                type="text"
                value={name}
                onChange={(e) => {
                  setName(e.target.value);
                  setNameTouched(true);
                }}
                placeholder="e.g. Block competitor mentions"
                className={fieldInputCls}
              />
            </div>
            <div>
              <label
                htmlFor="rule-description"
                className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5 block"
              >
                Description
              </label>
              <textarea
                id="rule-description"
                rows={2}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Why this rule exists, for whoever reads it next."
                className={`${fieldInputCls} resize-none`}
              />
            </div>
          </div>
        </Step>
 
        {/* Neither is a decision most rules need: priority only orders rules
            within a layer, and a new rule is meant to govern. */}
        <details className="group rounded-xl border border-gray-200 dark:border-gray-700 px-4 py-3">
          <summary className="cursor-pointer select-none text-sm font-medium text-gray-700 dark:text-gray-300">
            More settings
          </summary>
          <div className="mt-4 grid grid-cols-1 sm:grid-cols-2 gap-4">
            <div>
              <label
                htmlFor="rule-priority"
                className="text-xs font-medium text-gray-600 dark:text-gray-400 mb-1.5 block"
              >
                Priority
              </label>
              <input
                id="rule-priority"
                type="number"
                value={priority}
                onChange={(e) => setPriority(Number(e.target.value))}
                min={0}
                max={100}
                className={fieldInputCls}
              />
              <p className="mt-1 text-xs text-gray-400 dark:text-gray-500">
                Higher runs first, within its layer.
              </p>
            </div>
            <div className="flex flex-col gap-1.5">
              <span className="text-xs font-medium text-gray-600 dark:text-gray-400">
                Active
              </span>
              <label className="flex items-center gap-2 cursor-pointer mt-1">
                <div className="relative">
                  <input
                    type="checkbox"
                    checked={isActive}
                    onChange={(e) => setIsActive(e.target.checked)}
                    className="sr-only"
                  />
                  <div
                    className={`w-10 h-5 rounded-full transition-colors ${
                      isActive
                        ? "bg-gray-900 dark:bg-white"
                        : "bg-gray-300 dark:bg-gray-600"
                    }`}
                  >
                    <div
                      className={`absolute top-0.5 left-0.5 size-4 rounded-full bg-white dark:bg-gray-900 shadow transition-transform ${
                        isActive ? "translate-x-5" : "translate-x-0"
                      }`}
                    />
                  </div>
                </div>
                <span className="text-sm text-gray-700 dark:text-gray-300">
                  {isActive ? "Enabled" : "Disabled"}
                </span>
              </label>
            </div>
          </div>
        </details>
 
        <div className="flex items-center gap-3 pt-2 border-t border-gray-200 dark:border-gray-700">
          <button
            type="submit"
            disabled={mutation.isPending}
            className="flex items-center gap-2 px-4 py-2 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-sm font-medium hover:opacity-80 transition-opacity disabled:opacity-50"
          >
            <ShieldCheck className="size-4" />
            {editing
              ? mutation.isPending
                ? "Saving…"
                : "Save changes"
              : mutation.isPending
                ? "Creating…"
                : "Create Rule"}
          </button>
          <button
            type="button"
            onClick={() => void navigate(back)}
            className="px-4 py-2 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
          >
            Cancel
          </button>
        </div>
      </form>
    </SubPage>
  );
};
 
const NewRule: React.FC = () => <RuleBuilder />;
 
export default NewRule;