All files / src/views EntityItemsPage.vue

91.27% Statements 314/344
88.1% Branches 237/269
89.74% Functions 70/78
92.25% Lines 286/310

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                106x 1x 363x             1x                     1x                 1x                 1x                                   1x 1x     363x             1x               1x       1x     1x                                 5x                               1x                     334x       1x 1x         1x 1x           9x     73x                                                         26x                                                                                                                                                                                     96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x 96x   1831x         96x 136x         96x   221x       96x 1831x   106x 96x 106x       96x 94x 94x 94x           96x     93x   96x                 96x 126x   79x     126x   45x               96x 91x             3x 2x 1x       7x 7x 7x 7x             3x       3x       1x 1x                 96x   96x   184x         96x 132x 128x       96x 96x         96x 96x 1x                     96x   96x   136x   1x       96x 96x     96x 97x 96x   96x 5x 5x       96x 23x   96x 96x 96x   96x       96x 96x 96x 96x 96x 96x           96x 96x 2x 2x 2x 2x   1x 1x             96x 96x 1x 1x 1x         96x   96x   96x 139x 139x 2x   139x 3x 1x 7x 3x 3x 1x       10x 10x 10x 10x               96x 6x 6x 6x 17x 13x 11x   4x 7x   6x 6x 2x 2x   4x 4x 12x 12x 2x       96x 96x 96x 96x 19x   96x       96x 92x   96x   96x 96x 96x         50x       22x 21x 21x 21x     21x 21x 34x 34x   34x 17x 17x 2x 15x 2x   13x       22x 22x       5x 4x 4x 4x     5x     5x                                   5x 5x       8x 8x 8x 8x 8x 8x 8x       12x 12x 12x           12x 12x 1x 1x 1x 1x     11x   11x 11x 4x             7x   4x 4x   7x 7x       7x 2x 2x 2x   1x   2x     5x 2x 2x   3x           5x   11x       96x     3x 3x       2x 2x 2x 1x   1x 1x           2x 2x 2x 1x   1x 1x         96x         4x 2x         2x 2x 2x 1x   1x 1x       96x               96x                 96x     96x 6x       3x 3x       1x 1x                 3x   3x 3x 3x 3x   3x 3x               3x 3x   3x 1x 1x 1x 2x 1x 1x                       3x   3x 3x 3x 2x   3x         3x 2x                                                                                                                    
<template>
  <PageLayout
    :title="entity ? getTranslation(entity.name) : ''"
    :description="entity?.description ? getTranslation(entity.description) : undefined"
    class="items-page"
  >
    <template #action>
      <router-link :to="backLink" class="btn btn-secondary me-2">
        <font-awesome-icon icon="fa-solid fa-arrow-left" class="me-md-2" />
        <span class="d-none d-md-inline">{{ backLabel }}</span>
      </router-link>
      <!-- Label always shown: next to the item actions, an icon alone would be ambiguous -->
      <button
        v-if="canEditEntity"
        type="button"
        class="btn btn-outline-primary me-2"
        data-testid="edit-entity-btn"
        @click="entityEditSidebar?.startEdit(entity)"
      >
        <font-awesome-icon icon="fa-solid fa-pen" class="me-2" />
        <span>{{ t('entity.editEntity') }}</span>
      </button>
      <button
        class="btn btn-outline-secondary me-2 refresh-items-btn"
        :disabled="loading"
        @click="refreshItems"
      >
        <font-awesome-icon icon="fa-solid fa-rotate-right" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('common.refresh') }}</span>
      </button>
      <button
        v-if="entity && authStore.currentFlow"
        class="btn btn-outline-secondary me-2"
        data-tour="items-export"
        @click="handleExportEntity"
      >
        <font-awesome-icon icon="fa-solid fa-file-export" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('entity.exportEntity') }}</span>
      </button>
      <button
        v-if="canModifyItems"
        class="btn btn-success"
        data-tour="items-create"
        @click="startCreate"
      >
        <font-awesome-icon icon="fa-solid fa-plus" class="me-md-2" />
        <span class="d-none d-md-inline">{{ t('item.createNew') }}</span>
      </button>
    </template>
 
    <ItemFormSidebar
      :is-open="showItemDialog"
      :mode="editingItemId ? 'edit' : 'create'"
      :form-data="itemForm"
      :fields="formFields"
      :entity="entity"
      :item-id="editingItemId || newItemId"
      :default-language="defaultLanguage"
      :enabled-languages="enabledLanguages"
      :current-language="currentFormLanguage"
      :loading="formLoading"
      :error="formError"
      :field-errors="fieldErrors"
      :get-translation="getTranslation"
      @update:form-data="itemForm = $event"
      @update:current-language="currentFormLanguage = $event"
      @close="cancelItemForm"
      @submit="saveItem"
    />
 
    <!-- The entity's own edit form, over the items: saving reloads them with the new definition -->
    <EntityEditSidebar
      ref="entityEditSidebar"
      @updated="refreshItems"
      @cleared="refreshItems"
      @deleted="router.push(flowLink('entities'))"
    />
 
    <ItemCommentsSidebar
      :is-open="commentsItemId !== null"
      :entity-id="entityId"
      :item-id="commentsItemId ?? ''"
      :can-manage="canManageComments(entity)"
      @close="commentsItemId = null"
      @count-change="handleCommentCountChange"
    />
 
    <div class="container-fluid">
      <PackOrigin v-if="entity?.fromPack" :from-pack="entity.fromPack" class="mb-2" />
      <div v-if="canListItems" class="row mb-2">
        <div class="col-12 d-flex justify-content-end">
          <div class="btn-group btn-group-sm" role="group" :aria-label="t('item.viewMode')">
            <button
              type="button"
              class="btn btn-outline-secondary grid-view-btn"
              :class="{ active: viewMode === 'grid' }"
              :title="t('item.gridView')"
              @click="viewMode = 'grid'"
            >
              <font-awesome-icon icon="fa-solid fa-table-cells-large" />
            </button>
            <button
              v-if="canUseTableView"
              type="button"
              class="btn btn-outline-secondary table-view-btn"
              :class="{ active: viewMode === 'table' }"
              :title="t('item.tableView')"
              @click="viewMode = 'table'"
            >
              <font-awesome-icon icon="fa-solid fa-table-list" />
            </button>
          </div>
        </div>
      </div>
 
      <SearchFilterHeader
        v-if="canListItems"
        v-model="searchQuery"
        :placeholder="t('item.searchPlaceholder')"
        :filtered-count="filteredCount"
        :total-count="totalCount"
      >
        <template v-if="!isTableView" #extra>
          <div class="item-sort-control">
            <SortControl
              select-id="item-sort-field"
              :options="sortSelectOptions"
              :field-value="itemsStore.sort?.fieldId || CREATED_AT_SORT_FIELD_ID"
              :direction="itemsStore.sort?.direction || 'desc'"
              :label="t('item.sortBy')"
              :direction-disabled="!isCurrentSortAlwaysAvailable && !isSortable"
              @update:field-value="handleGridSortFieldChange"
              @toggle-direction="handleGridSortDirectionToggle"
            />
          </div>
        </template>
      </SearchFilterHeader>
      <div v-if="canListItems && !isTableView && !isSortable" class="row mb-3">
        <div class="col-12">
          <small class="text-muted">{{ t('item.sortDisabledTooltip') }}</small>
        </div>
      </div>
 
      <div v-if="pageError" class="row mb-3">
        <div class="col-12">
          <div class="alert alert-danger mb-0">
            {{ pageError }}
          </div>
        </div>
      </div>
 
      <EmptyState v-if="!canListItems" variant="info">{{ t('item.noListPermission') }}</EmptyState>
      <LoadingSpinner v-else-if="initialLoading" />
      <EmptyState v-else-if="!loading && filteredCount === 0">
        {{ searchQuery ? t('common.noResults') : t('item.noItems') }}
      </EmptyState>
    </div>
 
    <div v-if="canListItems && !initialLoading && isTableView" class="container-fluid">
      <EntityItemHeader
        :fields="entity?.fields || []"
        :layout="entity?.forms?.[0]?.fields || []"
        :get-translation="getTranslation"
        :scrollbar-width="scrollbarWidth"
        :show-actions="canModifyItems"
        :sort="itemsStore.sort"
        :is-sortable="isSortable"
        :sort-disabled-tooltip="t('item.sortDisabledTooltip')"
        @sort="handleHeaderSort"
      />
    </div>
 
    <!-- Virtual scroll list -->
    <VirtualCardGrid
      v-if="canListItems && !initialLoading"
      :items="filteredItems"
      :has-more="itemsStore.hasMore"
      :is-loading="loading"
      :offset-height="250"
      :single-column="isTableView"
      @load-more="itemsStore.loadMore(entityId)"
      @scrollbar-width-change="scrollbarWidth = $event"
    >
      <template #card="{ item }">
        <EntityItemCard
          :item="item"
          :fields="entity?.fields || []"
          :layout="entity?.forms?.[0]?.fields || []"
          :get-translation="getTranslation"
          :can-edit="canModifyItems"
          :can-delete="canModifyItems"
          :hide-field-names="isTableView"
          :table-view="isTableView"
          @edit="startEdit"
          @delete="handleDeleteItem"
          @like="handleLikeItem"
          @unlike="handleUnlikeItem"
          @comments="commentsItemId = $event.id"
        />
      </template>
    </VirtualCardGrid>
  </PageLayout>
 
  <!-- Delete item confirmation -->
  <ConfirmModal
    :is-open="confirmDeleteItem.open"
    :title="t('item.deleteItem')"
    :message="t('common.confirmDeleteItem')"
    :confirm-label="t('common.delete')"
    variant="danger"
    @confirm="doDeleteItem"
    @cancel="confirmDeleteItem.open = false"
  />
 
  <!-- Export entity: ZIP (schema + items + images + private dependencies, all
       individually toggleable) or CSV (items only) -->
  <ExportEntitySidebar
    :is-open="exportModal.open"
    :entity-id="entityId"
    :entity-name="entity ? getTranslation(entity.name) : ''"
    :loading="exportModal.loading"
    :error="exportModal.error"
    :status="exportModal.status"
    :progress="exportModal.progress"
    @confirm="confirmExportEntity"
    @cancel="cancelExportEntity"
  />
 
  <FloatingPageActions :scroll-top-title="t('common.backToTop')" />
</template>
 
<script setup lang="ts">
// @implements UC-ITEM-001.1, UC-ITEM-002.1, UC-ITEM-003.1, UC-ITEM-004.1, UC-ITEM-005.1, UC-ITEM-006.1, UC-ITEM-007.1, UC-ITEM-008.1, UC-ITEM-010.1, UC-ENTITY-008.1, UC-CREDITS-002.1, UC-CREDITS-003.1, UC-COMMENT-002.1, UC-COMMENT-012.1, UC-CATALOG-006.1, UC-STORE-016.1, UC-SPACE-006.2, UC-SPACE-014.1, UC-ENTITY-004.1
import { ref, onMounted, computed, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import PageLayout from '@/components/PageLayout.vue'
import PackOrigin from '@/components/PackOrigin.vue'
import VirtualCardGrid from '@/components/VirtualCardGrid.vue'
import ItemFormSidebar from '@/components/ItemFormSidebar.vue'
import ItemCommentsSidebar from '@/components/ItemCommentsSidebar.vue'
import EntityEditSidebar from '@/components/EntityEditSidebar.vue'
import EntityItemCard from '@/components/EntityItemCard.vue'
import EntityItemHeader from '@/components/EntityItemHeader.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import ExportEntitySidebar from '@/components/ExportEntitySidebar.vue'
import FloatingPageActions from '@/components/FloatingPageActions.vue'
import SearchFilterHeader from '@/components/SearchFilterHeader.vue'
import SortControl from '@/components/SortControl.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import EmptyState from '@/components/EmptyState.vue'
import { useItemsStore, DEFAULT_ITEM_SORT, type ItemSort } from '@/stores/items'
import {
  LARGE_ENTITY_ITEM_THRESHOLD,
  SORTABLE_FIELD_TYPES,
  CREATED_AT_SORT_FIELD_ID
} from '@/utils/constants'
import { useEntitiesStore, type Entity, type EntityField } from '@/stores/entities'
import { useCommentManagement } from '@/composables/useCommentManagement'
import { useAuthStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { useDebouncedSearch } from '@/composables/useDebouncedSearch'
import { usePermissions } from '@/composables/usePermissions'
import { useFilteredCounts } from '@/composables/useFilteredCounts'
import {
  validateItemForm,
  ITEM_ERROR_CODE_TO_I18N_KEY,
  type FieldErrorMap
} from '@/utils/itemValidation'
import { useToastStore } from '@/stores/toast'
import { usePollUntilComplete } from '@/composables/usePollUntilComplete'
import { storeToRefs } from 'pinia'
import { getErrorMessage } from '@/utils/errors'
import { useFlowLink } from '@/composables/useFlowLink'
const route = useRoute()
const router = useRouter()
const { flowLink } = useFlowLink()
const itemsStore = useItemsStore()
const entitiesStore = useEntitiesStore()
const authStore = useAuthStore()
const toastStore = useToastStore()
const { getTranslation, defaultLanguage, enabledLanguages } = useLanguage()
const { t } = useUILanguage()
const { hasPermission } = usePermissions()
const { canManageComments } = useCommentManagement()
const { loading, filteredTotal, total: storeTotal } = storeToRefs(itemsStore)
 
const entityId = computed(() => route.params.entityId as string)
 
// A public entity of another flow is readable by any signed-in user, even one
// without an active flow — no role applies (see hasEntityReadPermission in
// flows-api's auth-helper).
const isPublicFromOtherFlow = computed(
  () => entity.value?.visibility === 'public' && entity.value.flowId !== authStore.currentFlow
)
// Listing may be denied while creating is still allowed — skip the fetch to
// avoid a guaranteed 403 and show a neutral message instead of an error.
// Same entity-scoped permission the items/list Lambda enforces.
const canListItems = computed(
  () =>
    isPublicFromOtherFlow.value ||
    hasPermission(`entities-${entityId.value}:items:list`, entity.value)
)
// Outside any flow (UC-CATALOG-006.1) an entity can only come from the Catalog
const backToCatalog = computed(
  () => route.query.source === 'catalog' || route.name === 'flowless-entity-items'
)
const backLink = computed(() => flowLink(backToCatalog.value ? 'catalog' : 'entities'))
const backLabel = computed(() =>
  backToCatalog.value
    ? t('navigation.catalog')
    : t('common.backTo').replace('{name}', t('navigation.entities'))
)
const { searchQuery, appliedQuery, runSearchNow } = useDebouncedSearch(async (query) => {
  try {
    await itemsStore.fetchItems(entityId.value, true, query)
    pageError.value = ''
  } catch (err: any) {
    pageError.value = getErrorMessage(err, 'Failed to load items', t)
  }
})
 
const { filteredCount, totalCount } = useFilteredCounts(
  filteredTotal,
  storeTotal,
  computed(() => itemsStore.items.length)
)
const filteredItems = computed(() => itemsStore.items)
 
// Sorting is only offered when the current candidate set (the whole entity
// if unfiltered, or the matched/filtered count otherwise) is within the same
// threshold the backend uses to decide whether it can afford to fetch
// everything into memory and sort — see flows-api's LARGE_ENTITY_ITEM_THRESHOLD.
// Uses the store's raw `filteredTotal` rather than useFilteredCounts's floored
// `filteredCount` to avoid a flicker right at the threshold (that floor uses
// the local items length, which lags behind the true count while paging).
const isSortable = computed(() => filteredTotal.value <= LARGE_ENTITY_ITEM_THRESHOLD)
const sortableFields = computed(() =>
  (entity.value?.fields || []).filter((field) =>
    SORTABLE_FIELD_TYPES.includes(field.type as (typeof SORTABLE_FIELD_TYPES)[number])
  )
)
const sortSelectOptions = computed(() => [
  { value: CREATED_AT_SORT_FIELD_ID, label: t('item.sortByCreatedDate') },
  ...sortableFields.value.map((field) => ({
    value: field.fieldId!,
    label: getTranslation(field.name),
    disabled: !isSortable.value
  }))
])
// createdAt sort is index-backed on the server and always available,
// unlike a real text field which needs `isSortable` (see above).
const isCurrentSortAlwaysAvailable = computed(
  () => itemsStore.sort?.fieldId === CREATED_AT_SORT_FIELD_ID
)
 
// Cycles a table-header click through asc -> desc -> back to the default
// (newest-first by creation date) rather than a true "no sort" state, since
// there's no unsorted state exposed anywhere in the UI anymore.
function cycleSortDirection(current: ItemSort | null, fieldId: string): ItemSort {
  if (!current || current.fieldId !== fieldId) return { fieldId, direction: 'asc' }
  if (current.direction === 'asc') return { fieldId, direction: 'desc' }
  return DEFAULT_ITEM_SORT
}
 
async function applySort(newSort: ItemSort | null) {
  Iif (newSort && newSort.fieldId !== CREATED_AT_SORT_FIELD_ID && !isSortable.value) return
  try {
    await itemsStore.fetchItems(entityId.value, true, undefined, undefined, newSort)
    pageError.value = ''
  } catch (err: any) {
    pageError.value = getErrorMessage(err, 'Failed to load items', t)
  }
}
 
function handleHeaderSort(fieldId: string) {
  applySort(cycleSortDirection(itemsStore.sort, fieldId))
}
 
function handleGridSortFieldChange(fieldId: string) {
  applySort({ fieldId, direction: fieldId === CREATED_AT_SORT_FIELD_ID ? 'desc' : 'asc' })
}
 
function handleGridSortDirectionToggle() {
  Iif (!itemsStore.sort) return
  applySort({
    fieldId: itemsStore.sort.fieldId,
    direction: itemsStore.sort.direction === 'asc' ? 'desc' : 'asc'
  })
}
 
// Computed: check if current user can modify items (create/edit/delete)
// Can modify if: entity belongs to current flow OR entity not yet loaded (loading state).
// Never without an active flow: items are always written by a flow.
const entityEditSidebar = ref<InstanceType<typeof EntityEditSidebar> | null>(null)
// Same gate as the Edit button of the entity's card on the Entities page
const canEditEntity = computed(
  () =>
    !!entity.value &&
    !!authStore.currentFlow &&
    entity.value.flowId === authStore.currentFlow &&
    hasPermission(`entities-${entityId.value}:update`, entity.value)
)
const canModifyItems = computed(() => {
  if (!authStore.currentFlow) return false
  return entity.value === null || entity.value?.flowId === authStore.currentFlow
})
 
// Synchronous setup before first render — avoid any reactive flip
const _currentEntityId = route.params.entityId as string
const _cachedEntity = entitiesStore.entities.find((e) => e.id === _currentEntityId) ?? null
 
// If items in the store belong to a DIFFERENT entity, clear them now (synchronously)
// so the first render never shows stale data from a previous entity visit.
const _itemsMatchEntity =
  itemsStore.items.length > 0 && itemsStore.items[0]?.entityId === _currentEntityId
if (!_itemsMatchEntity && itemsStore.items.length > 0) {
  itemsStore.$patch({
    items: [],
    hasMore: true,
    nextToken: null,
    filteredTotal: 0,
    total: 0,
    searchQuery: '',
    sort: DEFAULT_ITEM_SORT
  })
}
 
const entity = ref<Entity | null>(_cachedEntity)
// Show spinner unless we already have items for this exact entity (same-entity revisit)
const initialLoading = ref(!_itemsMatchEntity)
 
const canUseTableView = computed(() => (entity.value?.fields?.length ?? 0) > 0)
 
const VIEW_MODE_STORAGE_KEY = 'browsway.entityItems.viewMode'
type ViewMode = 'grid' | 'table'
 
function loadStoredViewMode(): ViewMode {
  Iif (typeof window === 'undefined') return 'grid'
  return window.localStorage.getItem(VIEW_MODE_STORAGE_KEY) === 'table' ? 'table' : 'grid'
}
 
const viewMode = ref<ViewMode>(loadStoredViewMode())
const isTableView = computed(() => viewMode.value === 'table' && canUseTableView.value)
const scrollbarWidth = ref(0)
 
watch(viewMode, (mode) => {
  Iif (typeof window === 'undefined') return
  window.localStorage.setItem(VIEW_MODE_STORAGE_KEY, mode)
})
 
// Fall back to the grid when the current entity's form doesn't support a table layout.
watch(canUseTableView, (allowed) => {
  Iif (!allowed) viewMode.value = 'grid'
})
const itemForm = ref<Record<string, any>>({})
const showItemDialog = ref(false)
const editingItemId = ref<string | null>(null)
// The version of the item being edited, so a save can't overwrite a newer one
const editingItemUpdatedAt = ref<string | null>(null)
// Generated up front so image fields uploaded during creation are keyed by
// the item's real, final id from the start — sent to the API as `id` on
// create — instead of a placeholder that would need reconciling afterward.
const newItemId = ref<string>('')
const currentFormLanguage = ref(defaultLanguage.value)
const formLoading = ref(false)
const formError = ref('')
const fieldErrors = ref<FieldErrorMap>({})
const pageError = ref('')
 
// An email of a workflow transition links to one item, in its flow:
// /flows/:slug/entities/:entityId?item=… (UC-WORKFLOW-011.1) — the URL makes
// that flow the tab's active one, so the item opens as from its Entities page.
async function openLinkedItem() {
  const itemId = route.query.item
  if (typeof itemId !== 'string') return
  const { item: _item, ...query } = route.query
  router.replace({ query })
  try {
    startEdit(await itemsStore.fetchItem(entityId.value, itemId))
  } catch (err) {
    console.error('Failed to open the linked item:', err)
    toastStore.error(t('item.linkedItemNotFound'))
  }
}
 
// A report in the admin Reports tab links to an item's comments:
// ?comments=<itemId> opens its comments panel (UC-REPORT-004.1)
function openLinkedComments() {
  const itemId = route.query.comments
  if (typeof itemId !== 'string' || !itemId) return
  const { comments: _comments, ...query } = route.query
  router.replace({ query })
  commentsItemId.value = itemId
}
 
// The form a space page's "create" button asks for (UC-SPACE-014.1): its
// fields, then the mandatory ones it leaves out, so the item can be created
const createFormId = ref<string | null>(null)
// Where to go back once the item is created or the form closed: a space page
const returnTo = ref<string | null>(null)
 
const formFields = computed(() => {
  const fields = entity.value?.fields || []
  const form = createFormId.value
    ? entity.value?.forms?.find((f: { id: string }) => f.id === createFormId.value)
    : undefined
  if (!form || editingItemId.value) return fields
  const placed = [...form.fields].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
  const inForm = placed
    .map((p) => fields.find((field) => field.fieldId === p.fieldId))
    .filter((field): field is EntityField => !!field)
  const missing = fields.filter((field) => field.mandatory && !inForm.includes(field))
  return [...inForm, ...missing]
})
 
function goBackToSpace() {
  const target = returnTo.value
  returnTo.value = null
  createFormId.value = null
  if (target) router.push(target)
}
 
// The Members page creates a member's membership item here
// (UC-SPACE-006.2): ?new=1&set.<fieldId>=<userId> opens the create form with
// that user field filled. Only user fields can be set this way. A space page
// (UC-SPACE-014.1) adds `form=<formId>` and `return=/space/...`.
function openPrefilledCreate() {
  if (route.query.new !== '1') return
  const query: Record<string, any> = {}
  const prefill: Record<string, string> = {}
  for (const [key, value] of Object.entries(route.query)) {
    if (key.startsWith('set.') && typeof value === 'string') prefill[key.slice(4)] = value
    else if (key === 'form' && typeof value === 'string') createFormId.value = value
    else if (key === 'return' && typeof value === 'string') {
      // Only back to a space page: never an open redirect
      if (/^\/space\/[a-z0-9-]+(\/[a-z0-9-]+)?$/.test(value)) returnTo.value = value
    } else if (key !== 'new') query[key] = value
  }
  router.replace({ query })
  if (!canModifyItems.value) {
    goBackToSpace()
    return
  }
  startCreate()
  for (const field of entity.value?.fields || []) {
    const value = prefill[getFieldKey(field)]
    if (field.type !== 'user' || !value) continue
    itemForm.value[getFieldKey(field)] = field.reference?.multiple ? [value] : value
  }
}
 
onMounted(async () => {
  try {
    const fetchedEntity = await entitiesStore.fetchEntity(entityId.value)
    if (fetchedEntity) {
      entity.value = fetchedEntity
    }
    pageError.value = ''
  } catch (err: any) {
    pageError.value = getErrorMessage(err, 'Failed to load entity')
  } finally {
    if (canListItems.value) {
      await runSearchNow()
    }
    initialLoading.value = false
  }
  await openLinkedItem()
  openLinkedComments()
  openPrefilledCreate()
})
 
// Helper to get stable field key for data storage
function getFieldKey(field: { fieldId?: string; name: string | Record<string, string> }): string {
  return field.fieldId!
}
 
function startCreate() {
  if (!canModifyItems.value) return
  showItemDialog.value = true
  editingItemId.value = null
  newItemId.value = crypto.randomUUID()
 
  // Initialize itemForm with default values based on field types
  itemForm.value = {}
  entity.value?.fields.forEach((field) => {
    const key = getFieldKey(field)
    const fieldType = field.type || 'text'
 
    if (fieldType === 'text' || fieldType === 'textarea') {
      itemForm.value[key] = {}
    } else if (fieldType === 'boolean') {
      itemForm.value[key] = false
    } else if (fieldType === 'number') {
      itemForm.value[key] = 0
    } else {
      itemForm.value[key] = null
    }
  })
 
  formError.value = ''
  fieldErrors.value = {}
}
 
function startEdit(item: any) {
  if (!canModifyItems.value) return
  showItemDialog.value = true
  editingItemId.value = item.id
  editingItemUpdatedAt.value = item.updatedAt ?? null
 
  // Copy item data to form and initialize missing fields with proper defaults
  itemForm.value = { ...item }
 
  // Initialize missing fields based on field definitions
  entity.value?.fields.forEach((field) => {
    const key = getFieldKey(field)
    const fieldType = field.type || 'text'
 
    // Only initialize if field is missing or undefined
    if (itemForm.value[key] === undefined) {
      if (fieldType === 'text' || fieldType === 'textarea') {
        itemForm.value[key] = {}
      } else if (fieldType === 'boolean') {
        itemForm.value[key] = false
      } else if (fieldType === 'number') {
        itemForm.value[key] = 0
      } else {
        itemForm.value[key] = null
      }
    }
  })
 
  formError.value = ''
  fieldErrors.value = {}
}
 
function cancelItemForm() {
  showItemDialog.value = false
  editingItemId.value = null
  newItemId.value = ''
  itemForm.value = {}
  formError.value = ''
  fieldErrors.value = {}
  goBackToSpace()
}
 
async function saveItem() {
  formLoading.value = true
  formError.value = ''
  fieldErrors.value = {}
 
  // Client-side validation (mirrors backend rules: mandatory + type/shape).
  // Checks every field, not just the first invalid one, so all problems
  // surface at once. This is a UX convenience only — the backend remains the
  // source of truth and is always re-checked below.
  const validationErrors = validateItemForm(entity.value?.fields || [], itemForm.value)
  if (Object.keys(validationErrors).length > 0) {
    fieldErrors.value = validationErrors
    formError.value = t('item.formHasErrors')
    formLoading.value = false
    return
  }
 
  const isEditing = !!editingItemId.value
 
  try {
    if (editingItemId.value) {
      await itemsStore.updateItem(
        entityId.value,
        editingItemId.value,
        itemForm.value,
        editingItemUpdatedAt.value
      )
    } else {
      await itemsStore.createItem(entityId.value, itemForm.value, newItemId.value)
    }
    cancelItemForm()
    toastStore.success(t(isEditing ? 'item.updateSuccess' : 'item.createSuccess'))
  } catch (err: any) {
    const errData = err.response?.data
    const i18nKey = errData?.error ? ITEM_ERROR_CODE_TO_I18N_KEY[errData.error] : undefined
 
    // Changed meanwhile (another user, an automatic transition): nothing is
    // overwritten; the list shows the new version, to reopen and edit again
    if (errData?.error === 'ITEM_MODIFIED' && editingItemId.value) {
      formError.value = t('item.modifiedMeanwhile')
      try {
        await itemsStore.refreshItem(entityId.value, editingItemId.value)
      } catch (refreshError) {
        console.error('Failed to reload the item:', refreshError)
      }
      return
    }
 
    if (i18nKey && errData?.fieldId) {
      fieldErrors.value = { [errData.fieldId]: i18nKey }
      formError.value = t('item.formHasErrors')
    } else {
      formError.value = getErrorMessage(
        err,
        isEditing ? 'Failed to update item' : 'Failed to create item',
        t
      )
    }
    toastStore.error(t(isEditing ? 'item.updateError' : 'item.createError'))
  } finally {
    formLoading.value = false
  }
}
 
const confirmDeleteItem = reactive({ open: false, itemId: '' })
 
function handleDeleteItem(itemId: string) {
  confirmDeleteItem.itemId = itemId
  confirmDeleteItem.open = true
}
 
async function doDeleteItem() {
  confirmDeleteItem.open = false
  try {
    await itemsStore.deleteItem(entityId.value, confirmDeleteItem.itemId)
    toastStore.success(t('item.deleteSuccess'))
  } catch (err: any) {
    formError.value = getErrorMessage(err, 'Failed to delete item')
    toastStore.error(t('item.deleteError'))
  }
}
 
async function handleLikeItem(item: Record<string, any>) {
  // Optimistic: flip the button immediately, roll it back if the request fails.
  itemsStore.markAsLiked(item.id)
  try {
    await itemsStore.likeItem(entityId.value, item.id)
    toastStore.success(t('item.like-success'))
  } catch (err) {
    itemsStore.markAsUnliked(item.id)
    toastStore.error(getErrorMessage(err, t('item.like-error')))
  }
}
 
// The item whose comments panel is open (null = closed).
const commentsItemId = ref<string | null>(null)
 
// The panel reports each change to the item's comment counter so the card
// updates without refetching the list.
function handleCommentCountChange(delta: number) {
  if (commentsItemId.value && delta !== 0) {
    itemsStore.adjustCommentCount(commentsItemId.value, delta)
  }
}
 
async function handleUnlikeItem(item: Record<string, any>) {
  itemsStore.markAsUnliked(item.id)
  try {
    await itemsStore.unlikeItem(entityId.value, item.id)
    toastStore.success(t('item.unlike-success'))
  } catch (err) {
    itemsStore.markAsLiked(item.id)
    toastStore.error(getErrorMessage(err, t('item.unlike-error')))
  }
}
 
const exportModal = reactive<{
  open: boolean
  loading: boolean
  error: string
  status?: 'pending' | 'processing' | 'completed' | 'failed'
  progress: { done: number; total: number } | null
}>({ open: false, loading: false, error: '', status: undefined, progress: null })
 
const exportJobPoll = usePollUntilComplete<{
  downloadUrl: string
  entityCount: number
  cyclesBroken: string[]
}>()
 
// Mirrored into exportModal (rather than binding exportJobPoll's refs
// directly) so the sidebar's props stay grouped with the rest of the
// modal's state, same as loading/error/open above.
watch(exportJobPoll.progress, (progress) => {
  exportModal.progress = progress
})
watch(exportJobPoll.status, (status) => {
  exportModal.status = status === 'idle' ? undefined : status
})
 
function handleExportEntity() {
  exportModal.error = ''
  exportModal.open = true
}
 
function cancelExportEntity() {
  exportJobPoll.stop()
  exportModal.open = false
}
 
async function confirmExportEntity(payload: {
  format: 'json' | 'csv'
  excludeEntityIds?: string[]
  excludeItemsEntityIds?: string[]
  excludeImagesEntityIds?: string[]
}) {
  Iif (!entity.value) return
 
  exportModal.loading = true
  exportModal.error = ''
  exportModal.status = undefined
  exportModal.progress = null
 
  try {
    const { jobId } = await entitiesStore.exportEntities([entityId.value], payload)
    // `loading` only covers submitting the job, not waiting for it to
    // finish — otherwise BaseFormSidebar refuses to close (see its
    // handleClose) for as long as the job is pending/processing, trapping
    // the user behind the sidebar's overlay while a job that can take a
    // while runs. Progress is still shown via `status`/`progress` below;
    // the user can close the sidebar or navigate elsewhere and the job
    // keeps running (see the comment below).
    exportModal.loading = false
    await exportJobPoll.start(() => entitiesStore.getExportJobStatus(jobId))
 
    if (exportJobPoll.status.value === 'completed' && exportJobPoll.result.value) {
      window.location.href = exportJobPoll.result.value.downloadUrl
      exportModal.open = false
      toastStore.success(t('entity.exportSuccess'))
    } else if (exportJobPoll.status.value === 'failed') {
      exportModal.error = exportJobPoll.error.value || 'Failed to export entity'
      toastStore.error(t('entity.exportError'))
    }
    // Any other status means polling was stopped early (the sidebar was
    // closed before the job settled) — nothing left to report.
  } catch (err: any) {
    exportModal.error = getErrorMessage(err, 'Failed to export entity')
    toastStore.error(t('entity.exportError'))
    exportModal.loading = false
  }
}
 
async function refreshItems() {
  searchQuery.value = appliedQuery.value
 
  try {
    const fetchedEntity = await entitiesStore.fetchEntity(entityId.value)
    if (fetchedEntity) {
      entity.value = fetchedEntity
    }
    pageError.value = ''
  } catch (err: any) {
    pageError.value = getErrorMessage(err, 'Failed to load entity')
  }
 
  if (canListItems.value) {
    await runSearchNow()
  }
}
</script>
 
<style scoped>
pre {
  font-size: 0.85rem;
  max-width: 400px;
  overflow-x: auto;
}
 
/* Mobile optimization */
@media (max-width: 767px) {
  .container-fluid {
    padding: 1rem;
  }
 
  .container-fluid > .row:first-child {
    flex-shrink: 0;
  }
 
  .display-6 {
    font-size: 1.5rem;
  }
 
  .card-header h5 {
    font-size: 1rem;
  }
 
  /* Make textarea and form buttons full width, but not icon buttons */
  .form-control {
    width: 100%;
  }
 
  /* Responsive table */
  .table-responsive {
    font-size: 0.85rem;
  }
 
  .table th,
  .table td {
    padding: 0.5rem;
  }
 
  /* Smaller code blocks on mobile */
  pre {
    font-size: 0.75rem;
    max-width: 250px;
  }
 
  /* Hide Created column on mobile */
  .table th:nth-child(3),
  .table td:nth-child(3) {
    display: none;
  }
}
</style>