All files / src/components SchemaBuilder.vue

89.1% Statements 327/367
84.91% Branches 259/305
73.14% Functions 79/108
89.66% Lines 295/329

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 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401  4x 4x   4x 4x                     1980x                             4x                       180x               32x   4x     4x 4x                 4x 4x                                           4x 262x           4x     4x       4x 4x                           4x 4x 4x                       4x                                                                                                             4x                 4x                                   4x 4x               4x 4x               4x 4x                               4x               41x 4x                 43x           1x             1x             2x                         1x                                     4x 4x                       4x                       4x                       4x                           4x 4x           8x       4x                   4x       5x                 4x   4x 4x                     4x 4x                         4x 4x                     4x           4x                                                             4x 4x           4x 5x                         4x           4x 4x             4x 1x                 4x           4x 4x                         4x 4x                 4x 4x                           4x     2x                             4x                                   4x                                                                                                                                                                   129x 129x                                                                         129x                     129x     129x                                   129x 129x   129x 4644x       129x                 129x 78x   129x 68x 62x 68x   129x 68x   129x 11x       129x 20x               129x 154x   25x 7x 10x 7x       4x 129x 129x 129x   129x   129x 11x 11x   9x 9x   9x     129x 14x 14x   5x 5x   5x 2x     3x     129x 12x       12x 12x       202x 184x 184x 184x     18x 202x 12x 12x 12x     6x 4x 4x 4x     2x 2x       8x   8x 1x 1x 1x     7x 6x 6x       6x   6x     1x 1x       5x   5x 5x   3x 3x     129x 4x 4x 4x 1x 1x         3x   3x                 3x 1x     3x       3x 1x     3x 1x     3x       2934x       361x 12x   349x         180x   180x       3960x       70x   1x   69x 69x 69x 69x 69x     129x   129x 131x 131x         3x 1x   2x       1x 1x 1x   1x 1x 2x 1x     1x 1x             1x           69x 34x               129x   39x 39x                 129x         129x 129x   129x     43x       30x 14x 29x   14x           30x 14x       5x 5x 5x 5x       3x 3x 3x 3x       5x 5x       1x 1x       129x 208x     79x 19x 19x           18x 1x     1x             129x   204x 73x     202x             129x 129x   129x 129x 129x     3x 2x 2x 1x 1x         129x       3x 6x 3x 3x 3x   3x 3x     3x       5x 4x 4x 3x 3x 3x 3x       2x 1x       3x 2x     3x     2x 2x           3x 3x 2x 2x 2x 1x 1x       3x 2x     3x     2x 2x 2x                                                                                                                                                                                                                                                                                                                                                                              
<template>
  <div class="schema-builder">
    <div class="row g-4">
      <!-- Left Panel: Field Palette -->
      <div class="col-md-2">
        <div class="field-palette">
          <draggable
            :model-value="sortedFieldTypes"
            :group="{ name: 'fields', pull: 'clone', put: false }"
            :clone="cloneFieldType"
            :sort="false"
            item-key="type"
            class="palette-list"
            filter=".palette-item-disabled"
            :prevent-on-filter="true"
          >
            <template #item="{ element }">
              <div
                class="palette-item"
                :class="{ 'palette-item-disabled': isFieldTypeDisabled(element.type) }"
                :title="isFieldTypeDisabled(element.type) ? t('field.userTypeDisabledPublic') : ''"
              >
                <font-awesome-icon :icon="element.icon" class="me-2" />
                {{ t(`field.${element.type}`) }}
              </div>
            </template>
          </draggable>
        </div>
      </div>
 
      <!-- Center Panel: Schema Fields -->
      <div class="col-md-3">
        <draggable
          :model-value="modelValue"
          :group="{ name: 'fields', put: true, pull: false }"
          :sort="false"
          filter=".field-item"
          :prevent-on-filter="false"
          item-key="fieldId"
          class="fields-list"
          :class="{ empty: modelValue.length === 0 }"
          @update:model-value="onFieldsUpdate"
        >
          <template #item="{ element }">
            <div
              class="field-item"
              :class="{
                selected: selectedField?.fieldId === element.fieldId,
                'has-error': !!(element.fieldId && props.fieldErrors?.[element.fieldId])
              }"
              :style="{ order: getFieldSortOrder(element) }"
              @click="selectField(element)"
            >
              <div class="field-icon">
                <font-awesome-icon :icon="getFieldIcon(element.type)" />
              </div>
              <div class="field-content flex-grow-1">
                <div class="field-name">
                  {{ getFieldName(element) }}
                  <font-awesome-icon
                    v-if="element.fieldId && props.fieldErrors?.[element.fieldId]"
                    icon="fa-solid fa-exclamation-circle"
                    class="text-danger ms-1"
                    :title="t(props.fieldErrors[element.fieldId])"
                  />
                </div>
                <div class="field-meta">
                  <span class="badge bg-light text-dark">{{ t(`field.${element.type}`) }}</span>
                  <span v-if="element.length" class="text-muted ms-2">
                    <small>max: {{ element.length }}</small>
                  </span>
                </div>
              </div>
              <button
                type="button"
                class="btn btn-sm btn-danger field-delete"
                @click.stop="requestRemoveField(element)"
              >
                <font-awesome-icon icon="fa-solid fa-trash" />
              </button>
            </div>
          </template>
          <template #footer>
            <div v-if="modelValue.length === 0" class="empty-state text-center py-5">
              <font-awesome-icon
                icon="fa-solid fa-hand-pointer"
                size="3x"
                class="text-muted mb-3"
              />
              <p class="text-muted">{{ t('schema.dragFieldsHere') }}</p>
            </div>
          </template>
        </draggable>
      </div>
 
      <!-- Right Panel: Field Configuration -->
      <div class="col-md-7">
        <div v-if="!selectedField" class="text-center text-muted py-4">
          <font-awesome-icon icon="fa-solid fa-mouse-pointer" size="2x" class="mb-2" />
          <p class="small">{{ t('schema.selectFieldToConfig') }}</p>
        </div>
        <div v-else class="field-config">
          <!-- Field Name (Multilingual) -->
          <div class="mb-3">
            <label class="form-label small fw-bold">{{ t('schema.fieldName') }}</label>
            <MultilingualInput
              v-model="selectedField.name"
              :placeholder="t('field.placeholderFieldName')"
              :default-language="defaultLanguage"
              :enabled-languages="enabledLanguages"
              :current-language="currentLanguage"
              :show-language-selector="false"
              :show-language-hint="true"
              required
            />
          </div>
 
          <!-- Field Type (Read-only) -->
          <div class="mb-3">
            <label class="form-label small fw-bold">{{ t('schema.fieldType') }}</label>
            <div class="form-control-plaintext">
              <font-awesome-icon :icon="getFieldIcon(selectedField.type || 'text')" class="me-2" />
              {{ selectedField.type ? t(`field.${selectedField.type}`) : '' }}
            </div>
          </div>
 
          <!-- Field type validation error (unrecognized type) -->
          <div v-if="fieldTypeError" class="alert alert-danger py-2 px-3 mb-3 small">
            {{ t(fieldTypeError) }}
          </div>
 
          <!-- Help text (all field types) -->
          <div class="mb-3">
            <label class="form-label small fw-bold" for="field-help-text">{{
              t('field.helpText')
            }}</label>
            <MultilingualInput
              v-model="selectedField.helpText"
              input-id="field-help-text"
              :placeholder="t('field.helpTextPlaceholder')"
              :default-language="defaultLanguage"
              :enabled-languages="enabledLanguages"
              :current-language="currentLanguage"
              :show-language-selector="false"
              :show-language-hint="true"
            />
          </div>
 
          <!-- Type-specific configurations -->
          <template
            v-if="
              selectedField.type &&
              ['text', 'textarea', 'email', 'number', 'select'].includes(selectedField.type)
            "
          >
            <template v-if="['text', 'textarea', 'email'].includes(selectedField.type)">
              <div class="mb-3">
                <label class="form-label small fw-bold" for="field-max-length">{{
                  t('field.maxLength')
                }}</label>
                <input
                  id="field-max-length"
                  v-model.number="selectedField.length"
                  type="number"
                  class="form-control form-control-sm"
                  min="1"
                />
                <div
                  v-if="selectedField.type !== 'textarea' && numberConstraintsError"
                  class="alert alert-danger py-2 px-3 mt-2 mb-0 small"
                >
                  {{ t(numberConstraintsError) }}
                </div>
              </div>
            </template>
            <template v-if="selectedField.type === 'textarea'">
              <div class="mb-3">
                <label class="form-label small fw-bold" for="field-max-lines">{{
                  t('field.maxLines')
                }}</label>
                <input
                  id="field-max-lines"
                  v-model.number="selectedField.maxLines"
                  type="number"
                  class="form-control form-control-sm"
                  min="1"
                />
                <small class="text-muted">{{ t('field.maxLinesHint') }}</small>
                <div
                  v-if="numberConstraintsError"
                  class="alert alert-danger py-2 px-3 mt-2 mb-0 small"
                >
                  {{ t(numberConstraintsError) }}
                </div>
              </div>
            </template>
            <div class="mb-3">
              <label class="form-label small fw-bold" for="field-placeholder">{{
                t('field.placeholder')
              }}</label>
              <MultilingualInput
                v-model="selectedField.placeholder"
                input-id="field-placeholder"
                :placeholder="t('field.placeholderHint')"
                :default-language="defaultLanguage"
                :enabled-languages="enabledLanguages"
                :current-language="currentLanguage"
                :show-language-selector="false"
                :show-language-hint="true"
              />
            </div>
          </template>
 
          <template v-if="selectedField.type === 'number'">
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('schema.minValue') }}</label>
              <input
                v-model.number="selectedField.min"
                type="number"
                class="form-control form-control-sm"
                name="field-min"
              />
            </div>
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('schema.maxValue') }}</label>
              <input
                v-model.number="selectedField.max"
                type="number"
                class="form-control form-control-sm"
                name="field-max"
              />
            </div>
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('schema.step') }}</label>
              <input
                v-model.number="selectedField.step"
                type="number"
                class="form-control form-control-sm"
                step="0.01"
                name="field-step"
              />
            </div>
            <div v-if="numberConstraintsError" class="alert alert-danger py-2 px-3 mb-3 small">
              {{ t(numberConstraintsError) }}
            </div>
          </template>
 
          <template v-if="selectedField.type === 'select'">
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('field.options') }}</label>
              <draggable
                :model-value="optionRows"
                item-key="id"
                :animation="150"
                handle=".option-drag-handle"
                @update:model-value="reorderOptions(selectedField, $event)"
              >
                <template #item="{ element: row, index }">
                  <div class="input-group input-group-sm mb-2 select-option-row">
                    <span
                      class="input-group-text option-drag-handle d-flex align-items-center justify-content-center"
                      :title="t('schema.dragToReorder')"
                      :aria-label="t('schema.dragToReorder')"
                    >
                      <font-awesome-icon icon="fa-solid fa-grip-vertical" />
                    </span>
                    <input
                      :ref="(el) => setOptionInputRef(el as HTMLInputElement | null, index)"
                      :value="row.value"
                      type="text"
                      class="form-control form-control-sm"
                      :placeholder="t('schema.optionPlaceholder')"
                      name="field-option"
                      @input="
                        updateOption(
                          selectedField,
                          index,
                          ($event.target as HTMLInputElement).value
                        )
                      "
                      @keydown.enter.prevent="addOption(selectedField, index)"
                    />
                    <button
                      type="button"
                      class="btn btn-sm btn-outline-danger d-flex align-items-center justify-content-center"
                      :title="t('schema.removeOption')"
                      :aria-label="t('schema.removeOption')"
                      @click="removeOption(selectedField, index)"
                    >
                      <font-awesome-icon icon="fa-solid fa-times" />
                    </button>
                  </div>
                </template>
              </draggable>
              <div v-if="optionRows.length === 0" class="text-muted small mb-2">
                {{ t('schema.noOptionsYet') }}
              </div>
              <button
                type="button"
                class="btn btn-sm btn-outline-secondary"
                @click="addOption(selectedField)"
              >
                <font-awesome-icon icon="fa-solid fa-plus" class="me-1" />
                {{ t('schema.addOption') }}
              </button>
              <div v-if="selectOptionsError" class="alert alert-danger py-2 px-3 mt-2 mb-0 small">
                {{ t(selectOptionsError) }}
              </div>
              <div
                v-if="removedOptionsNotice"
                class="alert alert-warning py-2 px-3 mt-2 mb-0 small"
              >
                <font-awesome-icon icon="fa-solid fa-triangle-exclamation" class="me-1" />
                {{ removedOptionsNotice }}
              </div>
            </div>
          </template>
 
          <template v-if="selectedField.type === 'image' || selectedField.type === 'image_set'">
            <div class="row g-2 mb-2">
              <div class="col-6">
                <label class="form-label small fw-bold" for="field-image-min-width">{{
                  t('schema.imageMinWidth')
                }}</label>
                <input
                  id="field-image-min-width"
                  v-model.number="selectedField.minWidth"
                  type="number"
                  min="1"
                  class="form-control form-control-sm"
                />
              </div>
              <div class="col-6">
                <label class="form-label small fw-bold" for="field-image-max-width">{{
                  t('schema.imageMaxWidth')
                }}</label>
                <input
                  id="field-image-max-width"
                  v-model.number="selectedField.maxWidth"
                  type="number"
                  min="1"
                  class="form-control form-control-sm"
                />
              </div>
              <div class="col-6">
                <label class="form-label small fw-bold" for="field-image-min-height">{{
                  t('schema.imageMinHeight')
                }}</label>
                <input
                  id="field-image-min-height"
                  v-model.number="selectedField.minHeight"
                  type="number"
                  min="1"
                  class="form-control form-control-sm"
                />
              </div>
              <div class="col-6">
                <label class="form-label small fw-bold" for="field-image-max-height">{{
                  t('schema.imageMaxHeight')
                }}</label>
                <input
                  id="field-image-max-height"
                  v-model.number="selectedField.maxHeight"
                  type="number"
                  min="1"
                  class="form-control form-control-sm"
                />
              </div>
            </div>
 
            <div class="row g-2 mb-2">
              <div class="col-12">
                <label class="form-label small fw-bold" for="field-image-aspect-ratio">{{
                  t('schema.imageAspectRatio')
                }}</label>
                <select
                  id="field-image-aspect-ratio"
                  v-model="selectedAspectRatioPreset"
                  class="form-select form-select-sm"
                  @change="onAspectRatioPresetChange"
                >
                  <option value="">{{ t('schema.imageAspectRatioFree') }}</option>
                  <option value="1:1">1:1</option>
                  <option value="4:3">4:3</option>
                  <option value="3:2">3:2</option>
                  <option value="16:9">16:9</option>
                  <option value="9:16">9:16</option>
                  <option :value="CUSTOM_ASPECT_RATIO">
                    {{ t('schema.imageAspectRatioCustom') }}
                  </option>
                </select>
                <small class="text-muted">{{ t('schema.imageAspectRatioHint') }}</small>
              </div>
              <div v-if="selectedAspectRatioPreset === CUSTOM_ASPECT_RATIO" class="col-12">
                <input
                  v-model="selectedAspectRatioCustom"
                  type="text"
                  class="form-control form-control-sm"
                  :class="{ 'is-invalid': isCustomAspectRatioInvalid }"
                  :placeholder="t('schema.imageAspectRatioCustomPlaceholder')"
                  name="image-aspect-ratio"
                  @blur="onAspectRatioCustomBlur"
                  @keyup.enter="onAspectRatioCustomBlur"
                />
                <small class="text-muted">{{ t('schema.imageAspectRatioCustomHint') }}</small>
              </div>
              <div class="col-6">
                <label class="form-label small fw-bold">
                  {{ t('schema.imageResizeMaxWidth') }}
                </label>
                <input
                  v-model.number="selectedField.resizeMaxWidth"
                  type="number"
                  min="1"
                  class="form-control form-control-sm"
                  name="image-resize-max-width"
                />
              </div>
              <div class="col-6">
                <label class="form-label small fw-bold">
                  {{ t('schema.imageResizeMaxHeight') }}
                </label>
                <input
                  v-model.number="selectedField.resizeMaxHeight"
                  type="number"
                  min="1"
                  class="form-control form-control-sm"
                  name="image-resize-max-height"
                />
              </div>
            </div>
 
            <div class="mb-3">
              <div class="form-check">
                <input
                  id="field-image-crop-enabled"
                  v-model="selectedField.cropEnabled"
                  type="checkbox"
                  class="form-check-input"
                />
                <label class="form-check-label small fw-bold" for="field-image-crop-enabled">
                  {{ t('schema.imageEnableCrop') }}
                </label>
              </div>
              <small class="text-muted">{{ t('schema.imageCropHint') }}</small>
            </div>
          </template>
 
          <template v-if="selectedField.type === 'image_set'">
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('schema.maxImages') }}</label>
              <input
                v-model.number="selectedField.maxImages"
                type="number"
                class="form-control form-control-sm"
                min="1"
                max="20"
                name="max-images"
              />
            </div>
          </template>
 
          <!-- file_set: max number of files -->
          <template v-if="selectedField.type === 'file_set'">
            <div class="mb-3">
              <label class="form-label small fw-bold" for="field-max-files">{{
                t('schema.maxFiles')
              }}</label>
              <input
                id="field-max-files"
                v-model.number="selectedField.maxFiles"
                type="number"
                class="form-control form-control-sm"
                min="1"
                max="20"
              />
            </div>
          </template>
 
          <!-- entity_ref: target entity selector -->
          <template v-if="selectedField.type === 'entity_ref'">
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('field.referenceTargetEntity') }}</label>
              <select
                v-model="selectedField.reference!.entityId"
                class="form-select form-select-sm"
                name="reference-entity"
              >
                <option value="">{{ t('common.select') }}</option>
                <option
                  v-for="entity in entitiesStore.entities"
                  :key="entity.id"
                  :value="entity.id"
                  :disabled="props.isPublicEntity && entity.visibility !== 'public'"
                >
                  {{
                    typeof entity.name === 'string'
                      ? entity.name
                      : (entity.name?.['en'] ?? entity.id)
                  }}
                </option>
              </select>
              <small class="text-muted">{{ t('field.referenceTargetEntityHelp') }}</small>
              <small v-if="props.isPublicEntity" class="text-muted d-block">
                {{ t('field.referenceTargetEntityPublicOnlyHint') }}
              </small>
            </div>
 
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('field.referenceDisplayForm') }}</label>
              <select
                v-model="selectedField.reference!.displayFormId"
                class="form-select form-select-sm"
                :disabled="!selectedTargetEntityForms.length"
                name="reference-display-form"
              >
                <option value="">{{ t('field.referenceDisplayFormDefault') }}</option>
                <option v-for="form in selectedTargetEntityForms" :key="form.id" :value="form.id">
                  {{
                    form.name?.[currentLanguage] ||
                    form.name?.[defaultLanguage] ||
                    form.name?.en ||
                    form.id
                  }}
                </option>
              </select>
              <small class="text-muted">{{ t('field.referenceDisplayFormHelp') }}</small>
            </div>
          </template>
 
          <!-- multi-value config (user and entity_ref) -->
          <template v-if="['user', 'entity_ref'].includes(selectedField.type ?? '')">
            <div class="mb-3">
              <div class="form-check">
                <input
                  id="field-reference-multiple"
                  v-model="selectedField.reference!.multiple"
                  type="checkbox"
                  class="form-check-input"
                />
                <label class="form-check-label small fw-bold" for="field-reference-multiple">
                  {{ t('field.referenceMultiple') }}
                </label>
              </div>
            </div>
            <template v-if="selectedField.reference?.multiple">
              <div class="mb-3">
                <label class="form-label small fw-bold">{{ t('field.referenceMinValues') }}</label>
                <input
                  v-model.number="selectedField.reference!.minValues"
                  type="number"
                  min="0"
                  class="form-control form-control-sm"
                  name="reference-min-values"
                />
              </div>
              <div class="mb-3">
                <label class="form-label small fw-bold">{{ t('field.referenceMaxValues') }}</label>
                <input
                  v-model.number="selectedField.reference!.maxValues"
                  type="number"
                  min="1"
                  class="form-control form-control-sm"
                  name="reference-max-values"
                />
              </div>
            </template>
          </template>
 
          <template v-if="selectedField.type === 'workflow'">
            <div class="mb-3">
              <label class="form-label small fw-bold">{{ t('schema.workflowDefinition') }}</label>
              <WorkflowEditor
                :key="selectedField.fieldId"
                v-model="selectedField.workflowDefinition"
                :default-language="defaultLanguage"
                :enabled-languages="enabledLanguages"
                :current-language="currentLanguage"
                :email-templates="emailTemplates"
                :fields="props.modelValue"
                @open-state-panel="openStatePanel"
                @open-transition-panel="openTransitionPanel"
                @state-removed="onWorkflowStateRemoved"
              />
            </div>
          </template>
 
          <!-- Mandatory toggle (not for boolean/workflow types) -->
          <div v-if="!['boolean', 'workflow'].includes(selectedField.type ?? '')" class="mb-3">
            <div class="form-check">
              <input
                id="field-mandatory"
                v-model="selectedField.mandatory"
                type="checkbox"
                class="form-check-input"
              />
              <label class="form-check-label small fw-bold" for="field-mandatory">
                {{ t('field.mandatory') }}
              </label>
            </div>
          </div>
 
          <!-- Unique toggle (text/email only — the reservation table backing
               this enforces uniqueness by embedding the raw value in a
               DynamoDB key, which only text/email values are bounded and
               string-shaped enough to support safely) -->
          <div v-if="['text', 'email'].includes(selectedField.type ?? '')" class="mb-3">
            <div class="form-check">
              <input
                id="field-unique"
                v-model="selectedField.unique"
                type="checkbox"
                class="form-check-input"
              />
              <label class="form-check-label small fw-bold" for="field-unique">
                {{ t('field.unique') }}
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
 
  <!-- Field removal confirmation -->
  <ConfirmModal
    :is-open="pendingFieldRemoval !== null"
    :title="t('schema.removeFieldTitle')"
    :message="removeFieldMessage"
    :confirm-label="t('common.delete')"
    variant="danger"
    @confirm="confirmRemoveField"
    @cancel="pendingFieldRemoval = null"
  />
 
  <!-- Workflow state editor panel -->
  <WorkflowStatePanel
    :is-open="statePanelOpen"
    :fields="props.modelValue"
    :state="editingState"
    :enabled-languages="enabledLanguages"
    :default-language="defaultLanguage"
    :current-language="currentLanguage"
    :forms="forms"
    @close="statePanelOpen = false"
    @save="onStateSaved"
  />
 
  <!-- Workflow transition editor panel -->
  <WorkflowTransitionPanel
    :is-open="transitionPanelOpen"
    :transition="editingTransition"
    :transition-index="editingTransitionIndex"
    :all-states="selectedField?.workflowDefinition?.states ?? []"
    :all-transitions="selectedField?.workflowDefinition?.transitions ?? []"
    :fields="props.modelValue"
    :linked-entities="linkedEntities"
    :email-templates="emailTemplates"
    :enabled-languages="enabledLanguages"
    :default-language="defaultLanguage"
    :current-language="currentLanguage"
    @close="transitionPanelOpen = false"
    @save="onTransitionSaved"
    @move="onTransitionMoved"
  />
</template>
 
<script setup lang="ts">
// @implements UC-WORKFLOW-001.1, UC-I18N-005.1, UC-I18N-010.1, UC-ENTITY-004.1, UC-ENTITY-014.1, UC-ENTITY-015.1, UC-ENTITY-021.1, UC-ENTITY-022.1, UC-ENTITY-027.1, UC-ENTITY-028.1
import { computed, nextTick, ref, watch } from 'vue'
import draggable from 'vuedraggable'
import ConfirmModal from './ConfirmModal.vue'
import MultilingualInput from './MultilingualInput.vue'
import WorkflowEditor from './WorkflowEditor.vue'
import WorkflowStatePanel from './WorkflowStatePanel.vue'
import WorkflowTransitionPanel from './WorkflowTransitionPanel.vue'
import { useUILanguage } from '@/composables/useUILanguage'
import { useEntitiesStore } from '@/stores/entities'
import type { EntityField } from '@/stores/entities'
import { validateFieldDefinition } from '@/utils/entityValidation'
import { automaticSiblings, swapTransitions, type LinkedEntities } from '@/utils/workflowConditions'
import type {
  WorkflowDefinition,
  WorkflowState,
  WorkflowTransition,
  FormDefinition,
  EmailTemplate
} from '@/schemas/entity-schema'
 
const { t, uiLanguage } = useUILanguage()
const entitiesStore = useEntitiesStore()
 
interface FieldForm extends EntityField {
  workflowDefinition?: WorkflowDefinition
}
 
interface FieldType {
  type: string
  icon: string
}
 
interface Props {
  modelValue: FieldForm[]
  defaultLanguage?: string
  enabledLanguages?: string[]
  currentLanguage?: string
  hasItems?: boolean // If true, disable schema modifications
  forms?: FormDefinition[]
  /** the entity's email templates, which transitions' Email actions send */
  emailTemplates?: EmailTemplate[]
  isPublicEntity?: boolean // If true, restrict field types not allowed in public entities
  fieldErrors?: Record<string, string> // fieldId -> i18n key, from validateEntityFields()
}
 
interface Emits {
  (e: 'update:modelValue', value: FieldForm[]): void
  /**
   * emitted when a workflow status is removed and a fallback has been chosen —
   * the caller must include this in the entity update request so existing
   * items in the removed status get migrated (see entities/update.js)
   */
  (
    e: 'workflow-state-removed',
    payload: { fieldId: string; removedStateId: string; fallbackStateId: string }
  ): void
}
 
const props = withDefaults(defineProps<Props>(), {
  defaultLanguage: 'en',
  enabledLanguages: () => ['en', 'fr'],
  currentLanguage: 'en',
  hasItems: false,
  forms: () => [],
  emailTemplates: () => [],
  isPublicEntity: false,
  fieldErrors: () => ({})
})
 
const emit = defineEmits<Emits>()
 
// Field types palette
const fieldTypes: FieldType[] = [
  { type: 'boolean', icon: 'fa-solid fa-toggle-on' },
  { type: 'date', icon: 'fa-solid fa-calendar' },
  { type: 'email', icon: 'fa-solid fa-envelope' },
  { type: 'entity_ref', icon: 'fa-solid fa-link' },
  { type: 'file', icon: 'fa-solid fa-file' },
  { type: 'file_set', icon: 'fa-solid fa-file-zipper' },
  { type: 'geo_location', icon: 'fa-solid fa-location-dot' },
  { type: 'image', icon: 'fa-solid fa-image' },
  { type: 'image_set', icon: 'fa-solid fa-images' },
  { type: 'number', icon: 'fa-solid fa-hashtag' },
  { type: 'select', icon: 'fa-solid fa-list' },
  { type: 'text', icon: 'fa-solid fa-font' },
  { type: 'textarea', icon: 'fa-solid fa-align-left' },
  { type: 'user', icon: 'fa-solid fa-user' },
  { type: 'workflow', icon: 'fa-solid fa-diagram-project' }
]
 
const sortedFieldTypes = computed(() => {
  const collator = new Intl.Collator(uiLanguage.value, { sensitivity: 'base' })
 
  return [...fieldTypes].sort((a, b) => {
    return collator.compare(t(`field.${a.type}`), t(`field.${b.type}`))
  })
})
 
const selectedField = ref<FieldForm | null>(null)
 
// The selected field's validation error, if any — rendered next to the
// specific control it's about rather than as one generic message, so it's
// clear which control needs fixing. Prefers a live, reactive check over
// selectedField's own current values (so e.g. typing an invalid max length
// shows the error immediately, not only after a failed submit), falling back
// to whatever the parent passed down (set after a submit attempt, or mapped
// from a backend rejection) for anything the live check doesn't catch.
const liveFieldError = computed(() =>
  selectedField.value ? validateFieldDefinition(selectedField.value) : undefined
)
const selectedFieldError = computed(() => {
  if (liveFieldError.value) return liveFieldError.value
  const fieldId = selectedField.value?.fieldId
  return fieldId ? props.fieldErrors?.[fieldId] : undefined
})
const fieldTypeError = computed(() =>
  selectedFieldError.value === 'entity.invalidFieldType' ? selectedFieldError.value : undefined
)
const numberConstraintsError = computed(() =>
  selectedFieldError.value === 'entity.invalidNumberConstraints'
    ? selectedFieldError.value
    : undefined
)
const selectOptionsError = computed(() =>
  selectedFieldError.value === 'entity.invalidSelectOptions' ? selectedFieldError.value : undefined
)
 
// When the parent surfaces new field-definition errors (typically right after
// a failed submit) and the currently selected field isn't one of them, jump
// to the first field that needs fixing — otherwise the message is invisible,
// since it only renders inside the (currently unselected) field's own config
// panel, and the field list gives no other way to tell which field it's on.
watch(
  () => props.fieldErrors,
  (errors) => {
    if (!errors || Object.keys(errors).length === 0) return
    Iif (selectedField.value?.fieldId && errors[selectedField.value.fieldId]) return
    const firstErroredField = props.modelValue.find((f) => f.fieldId && errors[f.fieldId])
    if (firstErroredField) selectField(firstErroredField)
  }
)
 
const CUSTOM_ASPECT_RATIO = '__custom__'
const PRESET_ASPECT_RATIOS = ['', '1:1', '4:3', '3:2', '16:9', '9:16']
const selectedAspectRatioPreset = ref('')
const selectedAspectRatioCustom = ref('')
 
const ASPECT_RATIO_PATTERN = /^(\d+(?:\.\d+)?)\s*[:xX/]\s*(\d+(?:\.\d+)?)$/
 
const isAspectRatioFormat = (value: string): boolean => {
  const match = value.trim().match(ASPECT_RATIO_PATTERN)
  if (!match) return false
 
  const width = Number.parseFloat(match[1])
  const height = Number.parseFloat(match[2])
 
  return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0
}
 
const normalizeAspectRatio = (value: string): string | null => {
  const match = value.trim().match(ASPECT_RATIO_PATTERN)
  if (!match) return null
 
  const width = Number.parseFloat(match[1])
  const height = Number.parseFloat(match[2])
 
  if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
    return null
  }
 
  return `${width}:${height}`
}
 
const isCustomAspectRatioInvalid = computed(() => {
  Iif (selectedAspectRatioPreset.value !== CUSTOM_ASPECT_RATIO) {
    return false
  }
 
  const current = selectedAspectRatioCustom.value.trim()
  return current !== '' && !isAspectRatioFormat(current)
})
 
function syncAspectRatioControls() {
  if (!selectedField.value || !['image', 'image_set'].includes(selectedField.value.type ?? '')) {
    selectedAspectRatioPreset.value = ''
    selectedAspectRatioCustom.value = ''
    return
  }
 
  const ratio = (selectedField.value.aspectRatio || '').trim()
  if (!ratio) {
    selectedAspectRatioPreset.value = ''
    selectedAspectRatioCustom.value = ''
    return
  }
 
  if (PRESET_ASPECT_RATIOS.includes(ratio)) {
    selectedAspectRatioPreset.value = ratio
    selectedAspectRatioCustom.value = ''
    return
  }
 
  selectedAspectRatioPreset.value = CUSTOM_ASPECT_RATIO
  selectedAspectRatioCustom.value = ratio
}
 
function onAspectRatioPresetChange() {
  Iif (!selectedField.value) return
 
  if (selectedAspectRatioPreset.value === '') {
    delete selectedField.value.aspectRatio
    selectedAspectRatioCustom.value = ''
    return
  }
 
  if (selectedAspectRatioPreset.value === CUSTOM_ASPECT_RATIO) {
    const normalized = normalizeAspectRatio(selectedAspectRatioCustom.value)
    Iif (normalized) {
      selectedAspectRatioCustom.value = normalized
      selectedField.value.aspectRatio = normalized
    } else {
      delete selectedField.value.aspectRatio
    }
    return
  }
 
  selectedField.value.aspectRatio = selectedAspectRatioPreset.value
  selectedAspectRatioCustom.value = ''
}
 
function onAspectRatioCustomBlur() {
  Iif (!selectedField.value || selectedAspectRatioPreset.value !== CUSTOM_ASPECT_RATIO) return
 
  const normalized = normalizeAspectRatio(selectedAspectRatioCustom.value)
  if (!normalized) return
 
  selectedAspectRatioCustom.value = normalized
  selectedField.value.aspectRatio = normalized
}
 
const selectedTargetEntityForms = computed<FormDefinition[]>(() => {
  Iif (selectedField.value?.type !== 'entity_ref') return []
  const targetEntityId = selectedField.value.reference?.entityId
  if (!targetEntityId) return []
  const targetEntity = entitiesStore.entities.find((entity) => entity.id === targetEntityId)
  return targetEntity?.forms ?? []
})
 
// Clone a field type from palette to create a new field
function cloneFieldType(fieldType: FieldType): FieldForm {
  const fieldId = `field_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
 
  const newField: FieldForm = {
    fieldId,
    name: { en: '', fr: '' },
    type: fieldType.type as any,
    mandatory: false,
    unique: false
  }
 
  // Set defaults based on type
  if (fieldType.type === 'image_set') {
    newField.maxImages = 10
  }
 
  Iif (fieldType.type === 'file_set') {
    newField.maxFiles = 10
  }
 
  if (fieldType.type === 'user') {
    newField.reference = { kind: 'user' }
  }
 
  if (fieldType.type === 'entity_ref') {
    newField.reference = { kind: 'entity' }
  }
 
  return newField
}
 
function getFieldIcon(type: string): string {
  return fieldTypes.find((ft) => ft.type === type)?.icon || 'fa-solid fa-question'
}
 
function getFieldName(field: FieldForm): string {
  if (typeof field.name === 'string') {
    return field.name || t('schema.unnamedField')
  }
  return field.name?.[props.currentLanguage] || field.name?.['en'] || t('schema.unnamedField')
}
 
function getFieldSortOrder(field: FieldForm): number {
  // Calculate alphabetical order for CSS flexbox ordering
  const fieldName = getFieldName(field).toLowerCase()
  // Simple hash to generate consistent order
  return fieldName.charCodeAt(0) * 1000 + (fieldName.charCodeAt(1) || 0)
}
 
function isFieldTypeDisabled(type: string): boolean {
  return props.isPublicEntity && type === 'user'
}
 
function selectField(field: FieldForm) {
  if (props.hasItems) {
    // Don't allow editing if entity has items
    return
  }
  selectedField.value = field
  removedOptionsNotice.value = ''
  const values = normalizeOptions(field)
  optionsSnapshot.value = values
  optionRows.value = values.map((value) => ({ id: nextOptionRowId(), value }))
}
 
const pendingFieldRemoval = ref<FieldForm | null>(null)
 
const removeFieldMessage = computed(() => {
  const field = pendingFieldRemoval.value
  Eif (!field) return ''
  return t('schema.removeFieldMessage').replace('{field}', getFieldName(field))
})
 
function requestRemoveField(field: FieldForm) {
  if (props.hasItems) {
    return
  }
  pendingFieldRemoval.value = field
}
 
function confirmRemoveField() {
  const field = pendingFieldRemoval.value
  pendingFieldRemoval.value = null
  Iif (!field) return
 
  const index = props.modelValue.findIndex((f) => f.fieldId === field.fieldId)
  Eif (index > -1) {
    const updatedFields = props.modelValue.filter((_, i) => i !== index)
    emit('update:modelValue', updatedFields)
 
    // Deselect if removed field was selected
    Eif (selectedField.value?.fieldId === field.fieldId) {
      selectedField.value = null
    }
  }
}
 
function onFieldsUpdate(updatedFields: FieldForm[]) {
  // When draggable updates the fields list (add, remove, reorder)
  emit('update:modelValue', updatedFields)
}
 
// Extracts the plain option values regardless of whether options are stored as
// strings or as { value, label } objects (legacy shape).
function normalizeOptions(field: FieldForm | null | undefined): string[] {
  if (!field || !Array.isArray(field.options)) return []
  return field.options.map((opt) => (typeof opt === 'string' ? opt : (opt?.value ?? '')))
}
 
interface OptionRow {
  id: string
  value: string
}
 
let optionRowIdCounter = 0
function nextOptionRowId(): string {
  optionRowIdCounter += 1
  return `option-row-${optionRowIdCounter}`
}
 
// The editor's own row state, each tagged with a stable id so the drag list
// (and typing focus) survive re-renders — plain option strings have no
// identity of their own, and re-deriving rows from field.options on every
// keystroke would reset that identity and break dragging/focus mid-edit.
// Synced out to field.options (a plain string[], per the persisted shape)
// after every add/update/remove/reorder.
const optionRows = ref<OptionRow[]>([])
 
// Options as they were when the field was selected — the baseline the
// removed-options warning is diffed against, so it reflects everything
// dropped during this editing session rather than just the last keystroke.
const optionsSnapshot = ref<string[]>([])
const removedOptionsNotice = ref('')
 
const optionInputRefs = ref<(HTMLInputElement | null)[]>([])
 
function setOptionInputRef(el: HTMLInputElement | null, index: number) {
  optionInputRefs.value[index] = el
}
 
function recomputeRemovedOptionsNotice(currentValues: string[]) {
  const currentSet = new Set(currentValues.filter((value) => value.trim()))
  const removedCount = optionsSnapshot.value.filter(
    (value) => value.trim() && !currentSet.has(value)
  ).length
  removedOptionsNotice.value = removedCount
    ? t('schema.optionsRemovedNotice').replace('{count}', String(removedCount))
    : ''
}
 
function syncOptionsToField(field: FieldForm) {
  field.options = optionRows.value.map((row) => row.value)
  recomputeRemovedOptionsNotice(field.options)
}
 
function addOption(field: FieldForm, afterIndex?: number) {
  const insertAt = afterIndex === undefined ? optionRows.value.length : afterIndex + 1
  optionRows.value.splice(insertAt, 0, { id: nextOptionRowId(), value: '' })
  syncOptionsToField(field)
  nextTick(() => optionInputRefs.value[insertAt]?.focus())
}
 
function updateOption(field: FieldForm, index: number, value: string) {
  const row = optionRows.value[index]
  Iif (!row) return
  row.value = value
  syncOptionsToField(field)
}
 
function removeOption(field: FieldForm, index: number) {
  optionRows.value.splice(index, 1)
  syncOptionsToField(field)
}
 
function reorderOptions(field: FieldForm, newRows: OptionRow[]) {
  optionRows.value = newRows
  syncOptionsToField(field)
}
 
// Watch modelValue for external changes (e.g., auto-save)
watch(
  () => props.modelValue,
  (newVal) => {
    // Update selectedField if it still exists in the list
    if (selectedField.value) {
      const updated = newVal.find((f) => f.fieldId === selectedField.value?.fieldId)
      if (updated) {
        // Only reassign when the object reference changed (e.g. after a drag emits
        // a new array that flows back from the parent). Skip reassignment for
        // in-place mutations (same ref, e.g. typing a field name): reassigning the
        // same object causes Vue to re-render all field-item :class bindings, which
        // patches the DOM and confuses SortableJS mid-drag.
        if (updated !== selectedField.value) {
          selectedField.value = updated
        }
      } else {
        selectedField.value = null
      }
    }
  },
  { deep: true }
)
 
watch(
  () => {
    if (!selectedField.value) return ''
    return `${selectedField.value.fieldId ?? ''}:${selectedField.value.type ?? ''}:${selectedField.value.aspectRatio ?? ''}`
  },
  () => {
    syncAspectRatioControls()
  },
  { immediate: true }
)
 
// ---- Workflow panel state ----
 
const statePanelOpen = ref(false)
const editingState = ref<WorkflowState | null>(null)
 
const transitionPanelOpen = ref(false)
const editingTransitionIndex = ref(-1)
const editingTransition = ref<WorkflowTransition | null>(null)
 
function openStatePanel(stateId: string) {
  if (!selectedField.value?.workflowDefinition) return
  const state = selectedField.value.workflowDefinition.states.find((s) => s.id === stateId)
  if (!state) return
  editingState.value = state
  statePanelOpen.value = true
}
 
// The entities targeted by the item link fields, for conditions on linked
// items (UC-WORKFLOW-008.1) — loaded when a transition panel opens
const linkedEntities = ref<LinkedEntities>({})
 
async function loadLinkedEntities() {
  // Every item link, capped or not: an uncapped one is shown greyed out, with why
  const targetIds = props.modelValue
    .filter((field) => field.type === 'entity_ref' && !!field.reference?.entityId)
    .map((field) => field.reference!.entityId!)
  const loaded: LinkedEntities = {}
  await Promise.all(
    [...new Set(targetIds)].map(async (entityId) => {
      const entity = await entitiesStore.fetchEntityDefinition(entityId)
      if (entity) loaded[entityId] = { name: entity.name, fields: entity.fields }
    })
  )
  linkedEntities.value = loaded
}
 
function openTransitionPanel(transitionIndex: number) {
  if (!selectedField.value?.workflowDefinition) return
  const transition = selectedField.value.workflowDefinition.transitions[transitionIndex]
  if (!transition) return
  editingTransition.value = transition
  editingTransitionIndex.value = transitionIndex
  transitionPanelOpen.value = true
  void loadLinkedEntities()
}
 
function onWorkflowStateRemoved(payload: { removedStateId: string; fallbackStateId: string }) {
  if (!selectedField.value?.fieldId) return
  emit('workflow-state-removed', { fieldId: selectedField.value.fieldId, ...payload })
}
 
function onStateSaved(updatedState: WorkflowState) {
  if (!selectedField.value?.workflowDefinition) return
  selectedField.value.workflowDefinition = {
    ...selectedField.value.workflowDefinition,
    states: selectedField.value.workflowDefinition.states.map((s) =>
      s.id === updatedState.id ? updatedState : s
    )
  }
  statePanelOpen.value = false
  editingState.value = null
}
 
// Moves an automatic transition before/after its previous/next automatic
// sibling (same source state): their order is the evaluation order.
function onTransitionMoved(index: number, direction: -1 | 1) {
  const definition = selectedField.value?.workflowDefinition
  if (!definition) return
  const siblings = automaticSiblings(definition.transitions, index)
  const target = siblings[siblings.indexOf(index) + direction]
  if (target === undefined) return
  selectedField.value!.workflowDefinition = swapTransitions(definition, index, target)
  editingTransitionIndex.value = target
}
 
function onTransitionSaved(index: number, updatedTransition: WorkflowTransition) {
  if (!selectedField.value?.workflowDefinition) return
  selectedField.value.workflowDefinition = {
    ...selectedField.value.workflowDefinition,
    transitions: selectedField.value.workflowDefinition.transitions.map((t, i) =>
      i === index ? updatedTransition : t
    )
  }
  transitionPanelOpen.value = false
  editingTransition.value = null
  editingTransitionIndex.value = -1
}
</script>
 
<style scoped>
.schema-builder {
  min-height: 500px;
}
 
.field-palette {
  min-height: 400px;
}
 
.palette-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
 
.palette-item {
  padding: 0.75rem;
  background: var(--bw-surface-muted);
  border: 2px dashed var(--bw-border);
  border-radius: 0.375rem;
  cursor: move;
  transition:
    background-color 0.2s,
    border-color 0.2s,
    border-style 0.2s;
  user-select: none;
}
 
.palette-item:hover {
  background: color-mix(in srgb, var(--bw-surface-muted) 80%, var(--bw-text) 20%);
  border-color: #615581;
  border-style: solid;
}
 
.palette-item-disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
 
.palette-item-disabled:hover {
  background: var(--bw-surface-muted);
  border-color: var(--bw-border);
  border-style: dashed;
}
 
.fields-list {
  min-height: 200px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
 
.fields-list.empty {
  min-height: 400px;
  height: 100%;
}
 
.field-item {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  background: var(--bw-surface);
  border: 1px solid var(--bw-border);
  border-radius: 0.375rem;
  cursor: pointer;
  /* Exclude 'order' from transition: flexbox reorder must be instant so SortableJS
     reads stable getBoundingClientRect() during drags (no mid-animation positions). */
  transition:
    background-color 0.2s,
    border-color 0.2s,
    border-width 0.1s,
    box-shadow 0.2s;
}
 
.field-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-color: #615581;
}
 
.field-item.selected {
  background: color-mix(in srgb, var(--bw-surface) 78%, #615581 22%);
  border-color: #615581;
  border-width: 2px;
}
 
.field-item.has-error {
  border-color: var(--bs-danger, #dc3545);
}
 
.field-item.has-error.selected {
  border-color: var(--bs-danger, #dc3545);
}
 
.field-icon {
  width: 2rem;
  height: 2rem;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bw-surface-muted);
  border-radius: 0.25rem;
  color: var(--bw-text-muted);
}
 
.field-content {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
}
 
.field-name {
  font-weight: 500;
  color: var(--bw-text);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.field-meta {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: 0;
}
 
.field-meta .badge {
  overflow: hidden;
  text-overflow: ellipsis;
}
 
.field-delete {
  flex-shrink: 0;
}
 
.empty-state {
  height: 100%;
  border: 2px dashed var(--bw-border);
  border-radius: 0.375rem;
  background: var(--bw-surface-muted);
}
 
.field-config {
  padding: 0.5rem;
}
 
.field-config .form-label {
  margin-bottom: 0.5rem;
}
 
.field-config .form-control,
.field-config .form-control-sm {
  font-size: 0.95rem;
}
 
/* Match the option row's button/handle to its bumped-up input (above) so
   the whole row stays visually the same height. Matching font-size alone
   isn't enough: an icon-only button/input-group-text's auto height doesn't
   collapse to padding + line-height the way a text input's does (Bootstrap's
   own line-height/vertical-align math for a lone inline SVG overshoots it),
   so the height is pinned explicitly using Bootstrap's own -sm formula —
   the same fix already used for the copy button in ShowApiKeyModal.vue. */
.select-option-row .btn,
.select-option-row .input-group-text {
  font-size: 0.95rem;
  height: calc(1.5em + 0.5rem + 2px);
}
 
.option-drag-handle {
  cursor: grab;
}
 
.option-drag-handle:active {
  cursor: grabbing;
}
</style>