All files / src/components ItemFormSidebar.vue

89.04% Statements 252/283
74.89% Branches 176/235
77.77% Functions 56/72
90.37% Lines 216/239

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  140x                       58x 2x 2x   116x           1x   2x             46x                                                               1x                     1x                         1x                                                     1x     6x                                                 2x 2x                                                 2x                                               2x                                                   2x           1x               4x                                                                                         7x                                                               79x 79x 79x                                                     79x                           79x             79x     79x     2x           79x 54x       10x 10x   7x   7x 7x 5x 5x     4x     7x 13x 11x             4x 4x         225x       1x       1x     79x   79x 79x 79x 79x 79x                         6x 10x 10x 10x   4x 10x 10x   1x 1x               7x 3x 3x 2x 1x       9x 5x 5x 4x 3x       4x 3x 5x   1x       8x 7x 1x 2x       6x 2x   4x       3x 3x   2x 2x 2x   1x             1x 3x             3x 3x       5x 5x 5x   5x 5x 5x 5x 5x   5x 5x 7x 7x       5x 5x 5x 5x 5x         5x 5x     5x         5x 5x                   6x 6x 6x 1x   5x 5x                 6x 6x   6x       6x   6x 9x 9x   8x 8x   7x 9x 9x   9x 4x 4x     3x 9x 9x         6x 6x 6x 2x 1x 3x 2x 2x       6x 4x     6x             6x 7x 7x     6x 5x       4x 1x                 4x 4x 4x   1x     1x 1x   4x 1x 1x           1x 1x 1x                   1x 1x                           1x 1x 1x 1x 1x 1x 1x             1x             7x 7x   6x 7x 7x   6x 1x     5x 5x 5x                     4x 7x 5x 5x   5x             7x 7x           4x 4x 1x 1x       4x 4x   1x 1x   5x 5x 5x         6x 11x 5x 1x 1x 1x     1x       5x       79x                                                                                                                                                    
<template>
  <BaseFormSidebar
    :is-open="isOpen"
    :title="mode === 'create' ? t('item.createNew') : t('item.editItem')"
    panel-width="1400px"
    :loading="loading"
    :submit-disabled="false"
    :submit-label="mode === 'create' ? t('item.createItem') : t('item.updateItem')"
    :submit-icon="mode === 'create' ? 'fa-solid fa-plus' : 'fa-solid fa-save'"
    submit-button-class="btn-success"
    @close="handleClose"
    @submit="handleSubmit"
  >
    <!-- Language Selector -->
    <div class="mb-3 d-flex justify-content-end align-items-center gap-2">
      <label class="small text-muted mb-0">{{ t('language.editingLanguage') }}</label>
      <div class="btn-group btn-group-sm" role="group">
        <button
          v-for="lang in enabledLanguages"
          :key="lang"
          type="button"
          :class="['btn', currentLanguage === lang ? 'btn-primary' : 'btn-outline-secondary']"
          :title="getLanguageInfo(lang)?.nativeName"
          @click="$emit('update:currentLanguage', lang)"
        >
          <span class="me-1">{{ getLanguageInfo(lang)?.flag }}</span>
          {{ lang.toUpperCase() }}
        </button>
      </div>
    </div>
 
    <form @submit.prevent="handleSubmit">
      <div v-for="field in visibleFields" :key="getFieldKey(field)" class="mb-3">
        <label :for="`field-${getFieldKey(field)}`" class="form-label">
          {{ getTranslation(field.name) }}
          <span v-if="field.mandatory" class="text-danger">*</span>
        </label>
 
        <!-- Text input (multilingual) -->
        <MultilingualInput
          v-if="!field.type || field.type === 'text'"
          :input-id="`field-${getFieldKey(field)}`"
          :model-value="formData[getFieldKey(field)]"
          :label="''"
          :placeholder="field.placeholder"
          :required="field.mandatory"
          :default-language="defaultLanguage"
          :enabled-languages="enabledLanguages"
          :current-language="currentLanguage"
          :show-language-selector="false"
          :show-language-hint="false"
          @update:model-value="updateField(getFieldKey(field), $event)"
        />
 
        <!-- Email input (not multilingual) -->
        <input
          v-else-if="field.type === 'email'"
          :id="`field-${getFieldKey(field)}`"
          :value="formData[getFieldKey(field)]"
          type="email"
          :maxlength="field.length"
          :placeholder="field.placeholder"
          :required="field.mandatory"
          class="form-control"
          @input="updateField(getFieldKey(field), ($event.target as HTMLInputElement).value)"
        />
 
        <!-- Number input -->
        <input
          v-else-if="field.type === 'number'"
          :id="`field-${getFieldKey(field)}`"
          :value="formData[getFieldKey(field)]"
          type="number"
          :required="field.mandatory"
          class="form-control"
          @input="
            updateField(getFieldKey(field), Number(($event.target as HTMLInputElement).value))
          "
        />
 
        <!-- Date input -->
        <input
          v-else-if="field.type === 'date'"
          :id="`field-${getFieldKey(field)}`"
          :value="formData[getFieldKey(field)]"
          type="date"
          :required="field.mandatory"
          class="form-control"
          @input="updateField(getFieldKey(field), ($event.target as HTMLInputElement).value)"
        />
 
        <!-- Textarea (multilingual) -->
        <MultilingualTextarea
          v-else-if="field.type === 'textarea'"
          :input-id="`field-${getFieldKey(field)}`"
          :model-value="formData[getFieldKey(field)]"
          :label="''"
          :placeholder="field.placeholder"
          :required="field.mandatory"
          :default-language="defaultLanguage"
          :enabled-languages="enabledLanguages"
          :current-language="currentLanguage"
          :show-language-selector="false"
          :show-language-hint="false"
          :rows="3"
          @update:model-value="updateField(getFieldKey(field), $event)"
        />
 
        <!-- Select -->
        <select
          v-else-if="field.type === 'select'"
          :id="`field-${getFieldKey(field)}`"
          :value="formData[getFieldKey(field)]"
          :required="field.mandatory"
          class="form-select"
          @change="updateField(getFieldKey(field), ($event.target as HTMLSelectElement).value)"
        >
          <option v-if="!field.mandatory" value="">{{ t('common.select') }}</option>
          <option
            v-for="option in field.options || []"
            :key="typeof option === 'string' ? option : option.value"
            :value="typeof option === 'string' ? option : option.value"
          >
            {{ typeof option === 'string' ? option : option.label }}
          </option>
        </select>
 
        <!-- User reference (single/multi, backend search) -->
        <RichReferenceSelect
          v-else-if="field.type === 'user'"
          :input-id="`field-${getFieldKey(field)}`"
          :model-value="formData[getFieldKey(field)]"
          :multiple="!!field.reference?.multiple"
          :required="field.mandatory"
          :min-values="field.reference?.minValues"
          :max-values="field.reference?.maxValues"
          :search-placeholder="t('common.search')"
          :loading-label="t('common.loading')"
          :no-results-label="t('common.noResults')"
          :load-options="searchMemberOptions"
          @update:model-value="updateField(getFieldKey(field), $event)"
        >
          <template #option="{ option }">
            <div class="reference-option-default">
              <div class="reference-option-title">{{ option.label }}</div>
              <div v-if="option.description" class="reference-option-subtitle">
                {{ option.description }}
              </div>
            </div>
          </template>
        </RichReferenceSelect>
 
        <!-- Entity item reference (single/multi, backend search + rich rendering) -->
        <RichReferenceSelect
          v-else-if="field.type === 'entity_ref'"
          class="entity-reference-select"
          :input-id="`field-${getFieldKey(field)}`"
          :model-value="formData[getFieldKey(field)]"
          :multiple="!!field.reference?.multiple"
          :required="field.mandatory"
          :min-values="field.reference?.minValues"
          :max-values="field.reference?.maxValues"
          :search-placeholder="t('common.search')"
          :loading-label="t('common.loading')"
          :no-results-label="t('common.noResults')"
          :load-options="(query) => searchEntityItemOptions(field, query)"
          @update:model-value="updateField(getFieldKey(field), $event)"
        >
          <template #selected="{ option }">
            <div class="reference-selected-entity">
              <div
                v-for="(row, rowIndex) in (option as any).rows || []"
                :key="`${option.value}-selected-row-${rowIndex}`"
                class="reference-option-row"
              >
                <div
                  v-for="cell in (row as any).cells"
                  :key="cell.key"
                  class="reference-option-cell"
                  :style="{ gridColumn: `${cell.start} / span ${cell.span}` }"
                >
                  {{ cell.text }}
                </div>
              </div>
              <span
                v-if="!(option as any).rows || (option as any).rows.length === 0"
                class="reference-option-title"
              >
                {{ option.label }}
              </span>
            </div>
          </template>
          <template #option="{ option }">
            <div class="reference-option-entity">
              <div
                v-for="(row, rowIndex) in (option as any).rows || []"
                :key="`${option.value}-row-${rowIndex}`"
                class="reference-option-row"
              >
                <div
                  v-for="cell in (row as any).cells"
                  :key="cell.key"
                  class="reference-option-cell"
                  :style="{ gridColumn: `${cell.start} / span ${cell.span}` }"
                >
                  {{ cell.text }}
                </div>
              </div>
              <div
                v-if="!(option as any).rows || (option as any).rows.length === 0"
                class="reference-option-title"
              >
                {{ option.label }}
              </div>
            </div>
          </template>
        </RichReferenceSelect>
 
        <!-- Boolean -->
        <div v-else-if="field.type === 'boolean'" class="form-check">
          <input
            :id="`field-${getFieldKey(field)}`"
            :checked="formData[getFieldKey(field)]"
            type="checkbox"
            class="form-check-input"
            @change="updateField(getFieldKey(field), ($event.target as HTMLInputElement).checked)"
          />
          <label class="form-check-label" :for="`field-${getFieldKey(field)}`"> Yes </label>
        </div>
 
        <!-- Image or Image Set -->
        <ImageField
          v-else-if="field.type === 'image' || field.type === 'image_set'"
          :ref="(el) => setImageFieldRef(getFieldKey(field), el)"
          :model-value="formData[getFieldKey(field)]"
          :field="field"
          :is-editing="true"
          :item-id="itemId"
          @update:model-value="updateField(getFieldKey(field), $event)"
        />
 
        <!-- Workflow (edit mode only — hidden in create, auto-assigned by backend) -->
        <!-- Use <div> (block) not <template> (fragment) so the toggle button
             sits below the <label> instead of flowing inline beside it. -->
        <div v-else-if="field.type === 'workflow'">
          <!-- Collapsible workflow diagram -->
          <button
            type="button"
            class="btn btn-sm btn-link p-0 mb-2 text-secondary text-decoration-none"
            @click="toggleWorkflowViewer(getFieldKey(field))"
          >
            <font-awesome-icon
              :icon="
                workflowOpen[getFieldKey(field)]
                  ? 'fa-solid fa-chevron-down'
                  : 'fa-solid fa-chevron-right'
              "
              class="me-1"
            />
            {{
              workflowOpen[getFieldKey(field)] ? t('workflow.hideViewer') : t('workflow.showViewer')
            }}
          </button>
 
          <div v-if="workflowOpen[getFieldKey(field)]" class="mb-2">
            <WorkflowViewer
              :workflow-definition="field.workflowDefinition"
              :current-state-id="formData[getFieldKey(field)]"
              :get-translation="getTranslation"
            />
          </div>
 
          <select
            :id="`field-${getFieldKey(field)}`"
            :value="formData[getFieldKey(field)]"
            class="form-select"
            @change="updateField(getFieldKey(field), ($event.target as HTMLSelectElement).value)"
          >
            <option v-for="option in getWorkflowOptions(field)" :key="option.id" :value="option.id">
              {{ option.label }}
            </option>
          </select>
        </div>
      </div>
 
      <div v-if="error" class="alert alert-danger">
        {{ error }}
      </div>
    </form>
  </BaseFormSidebar>
</template>
 
<script setup lang="ts">
// @implements UC-WORKFLOW-002.1, UC-WORKFLOW-003.1, UC-I18N-006.1, UC-I18N-010.1
import BaseFormSidebar from '@/components/BaseFormSidebar.vue'
import ImageField from '@/components/ImageField.vue'
import MultilingualInput from '@/components/MultilingualInput.vue'
import MultilingualTextarea from '@/components/MultilingualTextarea.vue'
import RichReferenceSelect from '@/components/RichReferenceSelect.vue'
import WorkflowViewer from '@/components/WorkflowViewer.vue'
import type { EntityField } from '@/stores/entities'
import type { WorkflowDefinition } from '@/schemas/entity-schema'
import { useUILanguage } from '@/composables/useUILanguage'
import { useFlowMemberReference } from '@/composables/useFlowMemberReference'
import { useAuthStore } from '@/stores/auth'
import { getLanguageInfo } from '@/utils/languages'
import type { ReferenceOption } from '@/composables/useFlowMemberReference'
import api from '@/services/api'
import { ref, computed } from 'vue'
 
const { t } = useUILanguage()
const authStore = useAuthStore()
const { ensureMembersLoaded } = useFlowMemberReference()
 
interface RichReferenceOption extends ReferenceOption {
  rows?: Array<{ cells: Array<{ key: string; text: string; span: number; start: number }> }>
}
 
interface EntityReferenceFormPlacement {
  fieldId: string
  order: number
  x?: number
  y?: number
  w?: number
  h?: number
}
 
interface EntityReferenceForm {
  id: string
  purpose?: 'default' | 'short'
  fields: EntityReferenceFormPlacement[]
}
 
interface EntityReferenceMeta {
  fieldsById: Map<string, EntityField>
  formsById: Map<string, EntityReferenceForm>
  formsInOrder: EntityReferenceForm[]
}
 
const props = defineProps<{
  isOpen: boolean
  mode: 'create' | 'edit'
  formData: Record<string, any>
  fields: EntityField[]
  itemId: string
  defaultLanguage: string
  enabledLanguages: string[]
  currentLanguage: string
  loading: boolean
  error: string
  getTranslation: (value: string | Record<string, string> | null | undefined) => string
}>()
 
const emit = defineEmits<{
  'update:formData': [value: any]
  'update:currentLanguage': [value: string]
  close: []
  submit: []
}>()
 
const imageFieldRefs = ref<Record<string, any>>({})
 
// Tracks which workflow fields have their diagram expanded
const workflowOpen = ref<Record<string, boolean>>({})
 
function toggleWorkflowViewer(fieldKey: string) {
  workflowOpen.value[fieldKey] = !workflowOpen.value[fieldKey]
}
 
// Workflow fields are hidden in create mode and auto-assigned by the backend.
// In edit mode they appear as a select showing only transitions reachable from
// the current state (plus the current state itself).
const visibleFields = computed(() =>
  props.mode === 'create' ? props.fields.filter((f) => f.type !== 'workflow') : props.fields
)
 
function getWorkflowOptions(field: EntityField): Array<{ id: string; label: string }> {
  const def = field.workflowDefinition as WorkflowDefinition | undefined
  if (!def?.states?.length) return []
 
  const currentStateId = props.formData[getFieldKey(field)] as string | undefined
 
  const reachableIds = new Set<string>()
  if (currentStateId) {
    reachableIds.add(currentStateId)
    def.transitions.filter((t) => t.from === currentStateId).forEach((t) => reachableIds.add(t.to))
  } else {
    // No current state — show all states (shouldn't happen after proper creation)
    def.states.forEach((s) => reachableIds.add(s.id))
  }
 
  return def.states
    .filter((s) => reachableIds.has(s.id))
    .map((s) => ({
      id: s.id,
      label: props.getTranslation(s.label as string | Record<string, string>)
    }))
}
 
function setImageFieldRef(fieldKey: string, el: any) {
  Eif (el) {
    imageFieldRefs.value[fieldKey] = el
  }
}
 
function getFieldKey(field: { fieldId?: string; name: string | Record<string, string> }): string {
  return field.fieldId!
}
 
function handleClose() {
  emit('close')
}
 
function handleSubmit() {
  emit('submit')
}
 
void ensureMembersLoaded()
 
const memberSearchCache = ref<Map<string, RichReferenceOption[]>>(new Map())
const entityMetaCache = ref<Map<string, EntityReferenceMeta>>(new Map())
const entityOptionCache = ref<Map<string, RichReferenceOption[]>>(new Map())
const entityItemsLoading = ref<Set<string>>(new Set())
const ignoredItemLabelKeys = new Set([
  'id',
  'entityId',
  'flowId',
  'createdAt',
  'updatedAt',
  'createdBy',
  'updatedBy'
])
 
function sortFormFieldsByPosition(
  fields: EntityReferenceFormPlacement[]
): EntityReferenceFormPlacement[] {
  return [...fields].sort((a, b) => {
    const aY = a.y ?? Number.MAX_SAFE_INTEGER
    const bY = b.y ?? Number.MAX_SAFE_INTEGER
    if (aY !== bY) return aY - bY
 
    const aX = a.x ?? Number.MAX_SAFE_INTEGER
    const bX = b.x ?? Number.MAX_SAFE_INTEGER
    if (aX !== bX) return aX - bX
 
    Eif ((a.order ?? 0) !== (b.order ?? 0)) {
      return (a.order ?? 0) - (b.order ?? 0)
    }
 
    return a.fieldId.localeCompare(b.fieldId)
  })
}
 
function toGridSpan(width: number | undefined): number {
  if (!width || !Number.isFinite(width)) return 12
  const normalized = Math.floor(width)
  if (normalized < 1) return 1
  if (normalized > 12) return 12
  return normalized
}
 
function toGridStart(column: number | undefined): number {
  if (column === undefined || !Number.isFinite(column)) return 1
  const normalized = Math.floor(column) + 1
  if (normalized < 1) return 1
  if (normalized > 12) return 12
  return normalized
}
 
function getObjectText(value: Record<string, unknown> | null | undefined): string {
  if (!value) return ''
  for (const candidate of Object.values(value)) {
    if (candidate) return String(candidate)
  }
  return ''
}
 
function formatItemFieldValue(value: unknown): string {
  if (!value) return ''
  if (Array.isArray(value)) {
    return value
      .map((entry) => String(entry))
      .filter(Boolean)
      .join(', ')
  }
  if (typeof value === 'object') {
    return getObjectText(value as Record<string, unknown>)
  }
  return String(value)
}
 
async function searchMemberOptions(query: string): Promise<RichReferenceOption[]> {
  const flowId = authStore.currentFlow
  if (!flowId) return []
 
  const cacheKey = `${flowId}::${query.trim().toLowerCase()}`
  const cached = memberSearchCache.value.get(cacheKey)
  if (cached) return cached
 
  const response = await api.get(`/v1/flows/${flowId}/members`, {
    params: {
      q: query,
      limit: 30
    }
  })
 
  const members = Array.isArray(response?.data) ? response.data : []
  const options = members.map((member: any) => ({
    value: member.userId,
    label: member.name || member.email || member.userId,
    description: member.email || undefined,
    disabled: member.status !== 'active' && !member.isOwner
  }))
 
  memberSearchCache.value = new Map([...memberSearchCache.value, [cacheKey, options]])
  return options
}
 
async function ensureEntityMetaLoaded(entityId: string): Promise<EntityReferenceMeta | null> {
  Iif (!entityId) return null
  const cached = entityMetaCache.value.get(entityId)
  Iif (cached) return cached
 
  try {
    const response = await api.get(`/v1/entities/${entityId}`)
    const entity = response?.data
    const fields = Array.isArray(entity?.fields) ? entity.fields : []
    const forms = Array.isArray(entity?.forms) ? entity.forms : []
 
    const fieldsById = new Map<string, EntityField>()
    for (const field of fields) {
      Eif (field?.fieldId) {
        fieldsById.set(field.fieldId, field)
      }
    }
 
    const formsById = new Map<string, EntityReferenceForm>()
    const formsInOrder: EntityReferenceForm[] = []
    for (const form of forms) {
      Iif (!form?.id || !Array.isArray(form.fields)) continue
      const normalizedForm: EntityReferenceForm = {
        id: form.id,
        purpose: form.purpose,
        fields: sortFormFieldsByPosition(form.fields)
      }
      formsById.set(normalizedForm.id, normalizedForm)
      formsInOrder.push(normalizedForm)
    }
 
    const meta: EntityReferenceMeta = {
      fieldsById,
      formsById,
      formsInOrder
    }
    entityMetaCache.value = new Map([...entityMetaCache.value, [entityId, meta]])
    return meta
  } catch {
    return null
  }
}
 
function getReferenceFormForField(
  field: EntityField,
  meta: EntityReferenceMeta | null
): EntityReferenceForm | null {
  Iif (!meta || meta.formsInOrder.length === 0) return null
  const targetFormId = field.reference?.displayFormId
  if (targetFormId && meta.formsById.has(targetFormId)) {
    return meta.formsById.get(targetFormId) || null
  }
  const shortForm = meta.formsInOrder.find((form) => form.purpose === 'short')
  Eif (shortForm) return shortForm
  return meta.formsInOrder[0] || null
}
 
function buildEntityItemRows(
  item: Record<string, any>,
  meta: EntityReferenceMeta | null,
  field: EntityField
): Array<{ cells: Array<{ key: string; text: string; span: number; start: number }> }> {
  const form = getReferenceFormForField(field, meta)
  Iif (!form || !meta) return []
 
  const rowsByY = new Map<
    number,
    Array<{ key: string; text: string; x: number; span: number; start: number }>
  >()
  const fallbackRows: Array<{ key: string; text: string; span: number; start: number }> = []
 
  for (const placement of form.fields) {
    const targetField = meta.fieldsById.get(placement.fieldId)
    if (!targetField) continue
 
    const fieldValue = formatItemFieldValue(item[placement.fieldId])
    if (!fieldValue) continue
 
    const key = `${placement.fieldId}-${placement.order}-${placement.x ?? 'na'}-${placement.y ?? 'na'}`
    const span = toGridSpan(placement.w)
    const start = toGridStart(placement.x)
 
    if (placement.y === undefined || placement.x === undefined) {
      fallbackRows.push({ key, text: fieldValue, span, start: 1 })
      continue
    }
 
    const row = rowsByY.get(placement.y) ?? []
    row.push({ key, text: fieldValue, x: placement.x, span, start })
    rowsByY.set(placement.y, row)
  }
 
  const rows: Array<{
    cells: Array<{ key: string; text: string; span: number; start: number }>
  }> = []
  const sortedY = [...rowsByY.keys()].sort((a, b) => a - b)
  for (const y of sortedY) {
    const row = (rowsByY.get(y) ?? [])
      .sort((a, b) => a.x - b.x)
      .map((cell) => ({ key: cell.key, text: cell.text, span: cell.span, start: cell.start }))
    Eif (row.length > 0) {
      rows.push({ cells: row })
    }
  }
 
  for (const cell of fallbackRows) {
    rows.push({ cells: [{ key: cell.key, text: cell.text, span: cell.span, start: cell.start }] })
  }
 
  return rows.slice(0, 4)
}
 
function buildEntityItemLabelFromRows(
  rows: Array<{ cells: Array<{ key: string; text: string; span: number; start: number }> }>,
  fallbackLabel: string
): string {
  const values = rows
    .flatMap((row) => row.cells.map((cell) => cell.text))
    .map((value) => value.trim())
    .filter(Boolean)
 
  if (values.length === 0) return fallbackLabel
  return values.join(' | ')
}
 
function normalizeReferenceIds(value: unknown): string[] {
  if (!value) return []
  return (Array.isArray(value) ? value : [value]).map((entry) => String(entry)).filter(Boolean)
}
 
async function loadMissingSelectedEntityOptions(
  field: EntityField,
  entityId: string,
  knownById: Map<string, RichReferenceOption>,
  meta: EntityReferenceMeta | null
): Promise<RichReferenceOption[]> {
  const selectedIds = normalizeReferenceIds(props.formData[getFieldKey(field)])
  const missingSelectedIds = selectedIds.filter((id) => !knownById.has(id))
  if (missingSelectedIds.length === 0) return []
 
  const resolvedById = new Map<string, { id: string; [key: string]: any }>()
 
  const preferredFormId =
    (field.reference?.displayFormId && meta?.formsById.get(field.reference.displayFormId)?.id) ||
    meta?.formsInOrder.find((form) => form.purpose === 'short')?.id
 
  if (preferredFormId) {
    try {
      const lookupByFormResponse = await api.post(`/v1/entities/${entityId}/items/lookup-form`, {
        ids: missingSelectedIds,
        formId: preferredFormId
      })
 
      const items: Array<{ id: string; values?: Record<string, unknown> }> =
        lookupByFormResponse.data?.items ?? []
      for (const item of items) {
        resolvedById.set(item.id, {
          id: item.id,
          ...(item.values ?? {})
        })
      }
    } catch {
      // Fallback to generic lookup below.
    }
  }
 
  const stillMissing = missingSelectedIds.filter((id) => !resolvedById.has(id))
  Iif (stillMissing.length > 0) {
    try {
      const lookupResponse = await api.post(`/v1/entities/${entityId}/items/lookup`, {
        ids: stillMissing
      })
      const items: Array<{ id: string; [key: string]: any }> = lookupResponse.data?.items ?? []
      for (const item of items) {
        resolvedById.set(item.id, item)
      }
    } catch {
      // Keep missing entries unresolved.
    }
  }
 
  const mergedOptions: RichReferenceOption[] = []
  for (const selectedId of selectedIds) {
    const resolvedItem = resolvedById.get(selectedId)
    Iif (!resolvedItem) continue
    const rows = buildEntityItemRows(resolvedItem, meta, field)
    const fallbackLabel = getItemLabel(resolvedItem)
    mergedOptions.push({
      value: resolvedItem.id,
      label: buildEntityItemLabelFromRows(rows, fallbackLabel),
      rows
    })
  }
 
  return mergedOptions
}
 
async function searchEntityItemOptions(
  field: EntityField,
  query: string
): Promise<RichReferenceOption[]> {
  const entityId = field.reference?.entityId
  if (!entityId) return []
 
  const cacheKey = `${entityId}::${field.reference?.displayFormId ?? 'auto'}::${query.trim().toLowerCase()}`
  const cached = entityOptionCache.value.get(cacheKey)
  Iif (cached) return cached
 
  if (entityItemsLoading.value.has(cacheKey)) {
    return []
  }
 
  entityItemsLoading.value = new Set([...entityItemsLoading.value, cacheKey])
  try {
    const [meta, response] = await Promise.all([
      ensureEntityMetaLoaded(entityId),
      api.get(`/v1/entities/${entityId}/items`, {
        params: {
          limit: 30,
          q: query
        }
      })
    ])
 
    const items: Array<{ id: string; [key: string]: any }> =
      response.data.items ?? response.data ?? []
    const options: RichReferenceOption[] = items.map((item) => {
      const rows = buildEntityItemRows(item, meta, field)
      const fallbackLabel = getItemLabel(item)
 
      return {
        value: item.id,
        label: buildEntityItemLabelFromRows(rows, fallbackLabel),
        rows
      }
    })
 
    const optionById = new Map(options.map((option) => [option.value, option]))
    const missingSelected = await loadMissingSelectedEntityOptions(
      field,
      entityId,
      optionById,
      meta
    )
    const mergedOptions = [...options]
    for (const option of missingSelected) {
      Eif (!optionById.has(option.value)) {
        mergedOptions.push(option)
      }
    }
 
    entityOptionCache.value = new Map([...entityOptionCache.value, [cacheKey, mergedOptions]])
    return mergedOptions
  } catch {
    entityOptionCache.value = new Map([...entityOptionCache.value, [cacheKey, []]])
    return []
  } finally {
    const next = new Set(entityItemsLoading.value)
    next.delete(cacheKey)
    entityItemsLoading.value = next
  }
}
 
function getItemLabel(item: { id: string; [key: string]: any }): string {
  for (const [key, val] of Object.entries(item)) {
    if (ignoredItemLabelKeys.has(key)) continue
    if (val && typeof val === 'string' && val !== item.id) return val
    Eif (val && typeof val === 'object' && !Array.isArray(val)) {
      const first = Object.values(val).find((v) => v)
      Eif (first) return String(first)
    }
  }
  return item.id
}
 
function updateField(fieldKey: string, value: any) {
  emit('update:formData', { ...props.formData, [fieldKey]: value })
}
 
// Expose imageFieldRefs to parent
defineExpose({
  imageFieldRefs
})
</script>
 
<style scoped>
.reference-option-default {
  min-width: 0;
}
 
.reference-option-title {
  font-weight: 600;
  color: #243447;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.reference-option-subtitle {
  font-size: 0.8rem;
  color: #6b7280;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
 
.reference-option-entity {
  min-width: 0;
}
 
.reference-selected-entity {
  width: 100%;
  min-width: 0;
}
 
:deep(.entity-reference-select .selected-chips) {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}
 
:deep(.entity-reference-select .selected-chips .chip) {
  border: 1px solid #dfe3e8;
  border-radius: 0.375rem;
  background-color: #ffffff;
  padding: 0.45rem 1.8rem 0.45rem 0.55rem;
  width: 100%;
  text-align: left;
  position: relative;
  display: block;
}
 
:deep(.entity-reference-select .selected-chips .chip .chip-remove) {
  position: absolute;
  top: 0.32rem;
  right: 0.5rem;
  color: #6b7280;
  font-size: 0.78rem;
}
 
.reference-option-row {
  display: grid;
  grid-template-columns: repeat(12, minmax(0, 1fr));
  gap: 0.35rem;
  margin-bottom: 0.15rem;
}
 
.reference-option-cell {
  min-width: 0;
  font-size: 0.82rem;
  color: #4f5964;
  overflow-wrap: anywhere;
}
</style>