All files / src/components ImageField.vue

71.07% Statements 285/401
64.76% Branches 204/315
67.21% Functions 41/61
71.24% Lines 275/386

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  730x                                                                   21x   8x                                     21x                                   21x                                                                                             21x   8x                                     21x                                                                                                                                             21x 21x   21x                 21x                                                               303x 303x 303x 303x 303x                                             303x                         303x     303x   303x 303x 303x 303x 303x 303x 303x 303x       303x 303x       303x 303x       303x     303x   303x 2x 2x             303x                           303x 303x 303x 303x 303x   303x 54x 52x     2x     303x 9x 8x     1x 1x       1x 1x       1x 1x   1x       1x           303x 9x   9x                         303x 7x   7x                       303x 2x 2x 2x 2x 2x     303x                                             303x 1x 1x 1x 1x 1x   1x           303x           1x 1x 1x   1x 1x       1x                       1x 1x     1x       1x     303x 3x 3x 3x   3x 2x 2x 2x       303x 2x 2x 2x   2x 2x       303x 1x     303x 4x 1x     3x 2x     1x       1x         1x         303x   303x 2x 2x   2x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x             1x             303x                                                           303x                                               303x                               303x 8x 8x                                           303x         303x 1x             303x     303x 303x     303x     310x         310x   275x 275x 275x 275x     35x 35x 35x 28x   7x     32x 13x   25x               32x         303x   303x               303x                 310x     303x 1x 1x 1x 1x                         303x 2x 2x 1x 1x     1x 2x     1x 1x 1x 1x 1x     1x 1x                   303x         13x 13x   13x 13x   13x 2x 2x 1x 1x   1x 1x 1x       13x 13x         13x             13x     1x             1x     12x                           12x   1x           1x     11x                       11x 13x       11x       11x                 10x       303x 7x 7x   7x 1x 1x       6x 1x 1x     5x 5x         5x           4x     3x   2x 2x   7x         303x 4x 4x 4x   4x   5x 1x       4x 1x     3x 3x         3x           3x 3x   1x     2x     1x 4x 4x   3x 3x   4x         303x 2x 2x 2x 2x         303x 2x 4x 2x       303x   5x 1x     5x   3x 1x   2x 2x 2x 2x 1x   1x       3x       303x 1x                                                                                                                                                                                
<template>
  <div :class="{ 'image-field': !props.noWrapper }">
    <!-- Display Mode (single image) -->
    <div
      v-if="!isEditing && props.field.type === 'image' && loading"
      class="no-image text-muted small"
    >
      <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
      {{ t('common.loading') }}
    </div>
    <img
      v-else-if="!isEditing && props.field.type === 'image' && singleImageUrl"
      :src="singleImageUrl"
      :alt="fieldName"
      :class="{
        'img-thumbnail': !props.noThumbnail,
        'image-preview': props.clickable,
        'image-static': !props.clickable
      }"
      :style="
        props.noUpscale
          ? { maxWidth: '100%', width: 'auto', height: 'auto' }
          : { width: '100%', height: '100%', objectFit: props.objectFit }
      "
      @click="props.clickable && openImageModal()"
      @error="handleSingleImageError"
    />
    <div
      v-else-if="!isEditing && props.field.type === 'image' && !singleImageUrl"
      class="no-image text-muted small"
    >
      {{ t('common.noImage') }}
    </div>
 
    <!-- Display Mode (image set) -->
    <div v-else-if="!isEditing && props.field.type === 'image_set'" class="image-set-display">
      <div v-if="imageSetUrls.length > 0" class="d-flex flex-wrap gap-2">
        <div v-for="(url, index) in imageSetUrls" :key="index" class="image-preview">
          <img
            :src="url"
            :alt="`${fieldName} ${index + 1}`"
            class="img-thumbnail"
            @error="handleImageSetError(index)"
          />
        </div>
      </div>
      <div v-else-if="loading" class="no-image text-muted small">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.loading') }}
      </div>
      <div v-else class="no-image text-muted small">
        {{ t('common.noImages') }}
      </div>
    </div>
 
    <!-- Edit Mode (single image) -->
    <div v-else-if="isEditing && props.field.type === 'image'" class="image-edit">
      <div v-if="singleImageUrl" class="mb-2">
        <img
          :src="singleImageUrl"
          :alt="fieldName"
          class="img-thumbnail"
          style="max-width: 200px; cursor: pointer"
          @click.stop="openImageModal()"
          @error="handleSingleImageError"
        />
        <button type="button" class="btn btn-sm btn-danger ms-2" @click="removeImage">
          <font-awesome-icon icon="fa-solid fa-times" />
        </button>
      </div>
      <div v-else-if="loading && props.modelValue" class="text-muted small mb-2 image-loading">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.loading') }}
      </div>
      <div class="file-input-wrapper d-flex flex-wrap gap-2">
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          class="d-none"
          :disabled="uploading"
          name="image"
          @change="handleFileChange"
        />
        <button
          type="button"
          class="btn btn-sm btn-secondary"
          :disabled="uploading"
          @click="triggerFileInput"
        >
          {{ isCameraCapableDevice ? t('common.chooseFromGallery') : t('common.chooseFile') }}
        </button>
        <template v-if="isCameraCapableDevice">
          <input
            ref="cameraInput"
            type="file"
            accept="image/*"
            capture="environment"
            class="d-none"
            :disabled="uploading"
            name="image-camera"
            @change="handleFileChange"
          />
          <button
            type="button"
            class="btn btn-sm btn-secondary"
            :disabled="uploading"
            @click="triggerCameraInput"
          >
            <font-awesome-icon icon="fa-solid fa-camera" class="me-1" />
            {{ t('common.takePhoto') }}
          </button>
        </template>
      </div>
      <div v-if="uploading" class="text-muted small mt-1">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.uploading') }}
      </div>
    </div>
 
    <!-- Edit Mode (image set) -->
    <div v-else-if="isEditing && props.field.type === 'image_set'" class="image-set-edit">
      <div v-if="imageSetUrls.length > 0" class="d-flex flex-wrap gap-2 mb-2">
        <div v-for="(url, index) in imageSetUrls" :key="index" class="position-relative">
          <img
            :src="url"
            :alt="`${props.field.name} ${index + 1}`"
            class="img-thumbnail"
            style="max-width: 100px; cursor: pointer"
            @click.stop="openImageModal(index)"
            @error="handleImageSetError(index)"
          />
          <button
            type="button"
            class="btn btn-sm btn-danger"
            style="position: absolute; top: 8px; right: 8px; padding: 3px; font-size: 13px"
            @click="removeImageFromSet(index)"
          >
            <font-awesome-icon icon="fa-solid fa-times" />
          </button>
        </div>
      </div>
      <div class="file-input-wrapper d-flex flex-wrap gap-2">
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          multiple
          class="d-none"
          :disabled="uploading"
          name="images"
          @change="handleFileSetChange"
        />
        <button
          type="button"
          class="btn btn-sm btn-secondary"
          :disabled="
            uploading || !!(props.field.maxImages && imageSetUrls.length >= props.field.maxImages)
          "
          @click="triggerFileInput"
        >
          {{ isCameraCapableDevice ? t('common.chooseFromGallery') : t('common.chooseFile') }}
        </button>
        <template v-if="isCameraCapableDevice">
          <input
            ref="cameraInput"
            type="file"
            accept="image/*"
            capture="environment"
            class="d-none"
            :disabled="uploading"
            name="images-camera"
            @change="handleFileSetChange"
          />
          <button
            type="button"
            class="btn btn-sm btn-secondary"
            :disabled="
              uploading || !!(props.field.maxImages && imageSetUrls.length >= props.field.maxImages)
            "
            @click="triggerCameraInput"
          >
            <font-awesome-icon icon="fa-solid fa-camera" class="me-1" />
            {{ t('common.takePhoto') }}
          </button>
        </template>
      </div>
      <div v-if="uploading" class="text-muted small mt-1">
        <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
        {{ t('common.uploading') }}
      </div>
      <div v-if="props.field.maxImages" class="text-muted small mt-1">
        {{ t('common.maxImages').replace('{count}', String(props.field.maxImages)) }}
      </div>
    </div>
 
    <!-- Image Modal for full view -->
    <div v-if="showModal" class="image-modal" @click="closeImageModal">
      <div class="modal-content" @click.stop>
        <button
          type="button"
          class="btn-close"
          style="position: absolute; top: 10px; right: 10px; z-index: 1"
          @click="closeImageModal"
        />
        <img :src="modalImageUrl" :alt="fieldName" class="img-fluid" />
      </div>
    </div>
 
    <!-- Crop modal shown before upload when crop is enabled -->
    <!-- No backdrop-click-to-close: a stray click while dragging the cropper
         shouldn't discard the in-progress crop. -->
    <div v-if="showCropDialog" class="image-modal image-modal-static">
      <div class="modal-content crop-modal-content">
        <h6 class="mb-2">{{ t('common.cropImage') }}</h6>
 
        <div class="crop-cropper-wrapper">
          <Cropper
            ref="cropperRef"
            class="crop-cropper"
            :src="cropImageUrl"
            :stencil-props="{ aspectRatio: cropAspectRatio }"
          />
        </div>
 
        <div class="d-flex justify-content-end gap-2 mt-3">
          <button type="button" class="btn btn-sm btn-outline-secondary" @click="cancelCropDialog">
            {{ t('common.cancel') }}
          </button>
          <button type="button" class="btn btn-sm btn-primary" @click="applyCropDialog">
            {{ t('common.applyCrop') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
 
<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import {
  resolveImageUrl as resolveCachedImageUrl,
  invalidateImageUrl
} from '@/composables/useImageUrlCache'
import api from '@/services/api'
import type { EntityField } from '@/stores/entities'
import { Cropper } from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'
import { useToastStore } from '@/stores/toast'
import { ensureUuid } from '@/utils/uploadIds'
import { uploadToS3 } from '@/utils/s3Upload'
import { getErrorMessage } from '@/utils/errors'
 
const route = useRoute()
const authStore = useAuthStore()
const toastStore = useToastStore()
const { getTranslation } = useLanguage()
const { t } = useUILanguage()
 
interface Props {
  modelValue: string | string[] | null | undefined
  field: EntityField
  isEditing: boolean
  itemId?: string // Optional itemId prop, falls back to route params
  entityId?: string // Optional entityId prop, falls back to route params
  objectFit?: 'cover' | 'contain' | 'fill' | 'scale-down' // How to fit the image
  noThumbnail?: boolean // Remove Bootstrap thumbnail styling (border, padding)
  noUpscale?: boolean // Cap display size at the image's natural size instead of stretching to fill the container
  clickable?: boolean // Allow clicking to open modal
  noWrapper?: boolean // Remove the .image-field wrapper div
  uploadScope?: 'flow' | 'user' // 'user' uploads are not tied to a flow (e.g. profile picture)
  flowId?: string // Explicit flowId override; takes priority over authStore.currentFlow
  packId?: string // A pack's own picture (fieldId 'pack-picture') is keyed under the pack
  joinSlug?: string // A join form's image (UC-SPACE-020.1): uploaded to the requester's drafts
}
 
interface Emits {
  (e: 'update:modelValue', value: string | string[] | null): void
}
 
const props = withDefaults(defineProps<Props>(), {
  itemId: undefined,
  entityId: undefined,
  objectFit: 'cover',
  noThumbnail: false,
  noUpscale: false,
  clickable: true,
  noWrapper: false,
  uploadScope: 'flow',
  flowId: undefined,
  packId: undefined,
  joinSlug: undefined
})
const emit = defineEmits<Emits>()
 
// Computed property for field name (translated)
const fieldName = computed(() => getTranslation(props.field.name))
 
const fileInput = ref<HTMLInputElement | null>(null)
const cameraInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)
const loading = ref(true) // Start with true, updateImageUrls will set it to false
const showModal = ref(false)
const modalImageUrl = ref('')
const selectedFileName = ref('')
const selectedFileNames = ref<string[]>([])
 
// A dedicated camera-capture button only makes sense on touch/mobile devices —
// desktop browsers' file picker already exposes any attached camera.
const detectCameraCapableDevice = (): boolean => {
  Iif (typeof navigator === 'undefined') {
    return false
  }
 
  const uaData = (navigator as Navigator & { userAgentData?: { mobile?: boolean } }).userAgentData
  Iif (uaData && typeof uaData.mobile === 'boolean') {
    return uaData.mobile
  }
 
  return /Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent || '')
}
 
const isCameraCapableDevice = ref(detectCameraCapableDevice())
 
const getAuthUserId = (): string => {
  const candidate = authStore.userId
  return typeof candidate === 'string' && candidate.trim() ? candidate : ''
}
 
// Broader than uploadIds.ts's ensureUuid (which only accepts v4): the
// profile-picture branch below needs to recognize any well-formed UUID
// (v1-v8) already assigned to the user, not just freshly-generated v4 ones.
const UUID_GENERIC_REGEX =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
 
type ImageConstraints = {
  minWidth?: number
  maxWidth?: number
  minHeight?: number
  maxHeight?: number
  aspectRatio?: number
  aspectRatioLabel?: string
  resizeMaxWidth?: number
  resizeMaxHeight?: number
  cropEnabled: boolean
}
 
const showCropDialog = ref(false)
const cropImageUrl = ref('')
const cropSourceFile = ref<File | null>(null)
const cropperRef = ref<InstanceType<typeof Cropper> | null>(null)
let cropResolver: ((file: File | null) => void) | null = null
 
const normalizePositiveNumber = (value: unknown): number | undefined => {
  if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
    return undefined
  }
 
  return Math.round(value)
}
 
const parseAspectRatio = (value: unknown): { ratio?: number; label?: string } => {
  if (typeof value !== 'string') {
    return {}
  }
 
  const normalized = value.trim()
  Iif (!normalized) {
    return {}
  }
 
  const parts = normalized.split(':')
  Iif (parts.length !== 2) {
    return {}
  }
 
  const width = Number.parseFloat(parts[0])
  const height = Number.parseFloat(parts[1])
 
  Iif (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
    return {}
  }
 
  return {
    ratio: width / height,
    label: `${width}:${height}`
  }
}
 
const imageConstraints = computed<ImageConstraints>(() => {
  const parsedAspectRatio = parseAspectRatio(props.field.aspectRatio)
 
  return {
    minWidth: normalizePositiveNumber(props.field.minWidth),
    maxWidth: normalizePositiveNumber(props.field.maxWidth),
    minHeight: normalizePositiveNumber(props.field.minHeight),
    maxHeight: normalizePositiveNumber(props.field.maxHeight),
    aspectRatio: parsedAspectRatio.ratio,
    aspectRatioLabel: parsedAspectRatio.label,
    resizeMaxWidth: normalizePositiveNumber(props.field.resizeMaxWidth),
    resizeMaxHeight: normalizePositiveNumber(props.field.resizeMaxHeight),
    cropEnabled: !!props.field.cropEnabled
  }
})
 
const hasImageProcessingEnabled = computed(() => {
  const c = imageConstraints.value
 
  return !!(
    c.cropEnabled ||
    c.aspectRatio ||
    c.resizeMaxWidth ||
    c.resizeMaxHeight ||
    c.minWidth ||
    c.maxWidth ||
    c.minHeight ||
    c.maxHeight
  )
})
 
const fileToDataUrl = (file: File) =>
  new Promise<string>((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve((reader.result as string) || '')
    reader.onerror = () => reject(new Error('Failed to read image file'))
    reader.readAsDataURL(file)
  })
 
const loadImageElement = (source: Blob | string) =>
  new Promise<HTMLImageElement>((resolve, reject) => {
    const img = new Image()
    img.onload = () => resolve(img)
    img.onerror = () => reject(new Error('Failed to decode image'))
 
    if (typeof source === 'string') {
      img.src = source
      return
    }
 
    const objectUrl = URL.createObjectURL(source)
    img.onload = () => {
      URL.revokeObjectURL(objectUrl)
      resolve(img)
    }
    img.onerror = () => {
      URL.revokeObjectURL(objectUrl)
      reject(new Error('Failed to decode image'))
    }
    img.src = objectUrl
  })
 
const blobToFile = (blob: Blob, source: File, suffix = '') => {
  const dotIndex = source.name.lastIndexOf('.')
  const hasExt = dotIndex > 0
  const baseName = hasExt ? source.name.slice(0, dotIndex) : source.name
  const ext = hasExt ? source.name.slice(dotIndex) : ''
  const name = suffix ? `${baseName}-${suffix}${ext}` : source.name
 
  return new File([blob], name, {
    type: blob.type || source.type,
    lastModified: Date.now()
  })
}
 
const drawToCanvasBlob = async (
  image: CanvasImageSource,
  sourceRect: { sx: number; sy: number; sw: number; sh: number },
  outSize: { width: number; height: number },
  mimeType: string
): Promise<Blob> => {
  const canvas = document.createElement('canvas')
  canvas.width = outSize.width
  canvas.height = outSize.height
 
  const ctx = canvas.getContext('2d')
  Iif (!ctx) {
    throw new Error('Canvas is not available')
  }
 
  ctx.drawImage(
    image,
    sourceRect.sx,
    sourceRect.sy,
    sourceRect.sw,
    sourceRect.sh,
    0,
    0,
    outSize.width,
    outSize.height
  )
 
  const blob = await new Promise<Blob | null>((resolve) => {
    canvas.toBlob((result) => resolve(result), mimeType, 0.92)
  })
 
  Iif (!blob) {
    throw new Error('Failed to generate resized image')
  }
 
  return blob
}
 
const closeCropDialog = (result: File | null) => {
  showCropDialog.value = false
  cropImageUrl.value = ''
  cropSourceFile.value = null
 
  if (cropResolver) {
    const resolver = cropResolver
    cropResolver = null
    resolver(result)
  }
}
 
const openCropDialog = async (file: File): Promise<File | null> => {
  cropSourceFile.value = file
  cropImageUrl.value = await fileToDataUrl(file)
  showCropDialog.value = true
 
  return await new Promise<File | null>((resolve) => {
    cropResolver = resolve
  })
}
 
const cancelCropDialog = () => {
  closeCropDialog(null)
}
 
const getCropTargetAspectRatio = (constraints: ImageConstraints): number => {
  if (constraints.aspectRatio) {
    return constraints.aspectRatio
  }
 
  if (constraints.resizeMaxWidth && constraints.resizeMaxHeight) {
    return constraints.resizeMaxWidth / constraints.resizeMaxHeight
  }
 
  Iif (constraints.maxWidth && constraints.maxHeight) {
    return constraints.maxWidth / constraints.maxHeight
  }
 
  Iif (constraints.minWidth && constraints.minHeight) {
    return constraints.minWidth / constraints.minHeight
  }
 
  // Crop mode without ratio constraints should still produce a visible crop.
  return 1
}
 
// Aspect ratio enforced on the cropper's selection stencil, derived from the
// field's crop/resize/dimension constraints.
const cropAspectRatio = computed(() => getCropTargetAspectRatio(imageConstraints.value))
 
const applyCropDialog = async () => {
  const source = cropSourceFile.value
  const canvas = cropperRef.value?.getResult().canvas
 
  if (!source || !canvas) {
    closeCropDialog(null)
    return
  }
 
  try {
    const c = imageConstraints.value
    let outWidth = canvas.width
    let outHeight = canvas.height
    Eif (c.resizeMaxWidth || c.resizeMaxHeight) {
      const scaleX = c.resizeMaxWidth ? c.resizeMaxWidth / outWidth : 1
      const scaleY = c.resizeMaxHeight ? c.resizeMaxHeight / outHeight : 1
      const scale = Math.min(1, scaleX, scaleY)
      outWidth = Math.max(1, Math.round(outWidth * scale))
      outHeight = Math.max(1, Math.round(outHeight * scale))
    }
 
    const blob = await drawToCanvasBlob(
      canvas,
      { sx: 0, sy: 0, sw: canvas.width, sh: canvas.height },
      { width: outWidth, height: outHeight },
      source.type || 'image/jpeg'
    )
 
    closeCropDialog(blobToFile(blob, source, 'crop'))
  } catch (error) {
    console.error('Error applying crop:', error)
    closeCropDialog(null)
  }
}
 
const resizeImageIfNeeded = async (file: File): Promise<File> => {
  const c = imageConstraints.value
  if (!c.resizeMaxWidth && !c.resizeMaxHeight) {
    return file
  }
 
  const image = await loadImageElement(file)
  const sourceWidth = image.naturalWidth
  const sourceHeight = image.naturalHeight
 
  const scaleX = c.resizeMaxWidth ? c.resizeMaxWidth / sourceWidth : 1
  const scaleY = c.resizeMaxHeight ? c.resizeMaxHeight / sourceHeight : 1
  const scale = Math.min(1, scaleX, scaleY)
 
  if (scale >= 1) {
    return file
  }
 
  const outWidth = Math.max(1, Math.round(sourceWidth * scale))
  const outHeight = Math.max(1, Math.round(sourceHeight * scale))
  const blob = await drawToCanvasBlob(
    image,
    { sx: 0, sy: 0, sw: sourceWidth, sh: sourceHeight },
    { width: outWidth, height: outHeight },
    file.type || 'image/jpeg'
  )
 
  return blobToFile(blob, file, 'resized')
}
 
const validateImageDimensions = async (file: File): Promise<void> => {
  const c = imageConstraints.value
  if (!c.minWidth && !c.maxWidth && !c.minHeight && !c.maxHeight) {
    return
  }
 
  const image = await loadImageElement(file)
  const width = image.naturalWidth
  const height = image.naturalHeight
 
  if (c.minWidth && width < c.minWidth) {
    throw new Error(`Image width must be at least ${c.minWidth}px`)
  }
  if (c.maxWidth && width > c.maxWidth) {
    throw new Error(`Image width must be at most ${c.maxWidth}px`)
  }
  if (c.minHeight && height < c.minHeight) {
    throw new Error(`Image height must be at least ${c.minHeight}px`)
  }
  if (c.maxHeight && height > c.maxHeight) {
    throw new Error(`Image height must be at most ${c.maxHeight}px`)
  }
}
 
const validateAspectRatio = async (file: File): Promise<void> => {
  const c = imageConstraints.value
  if (!c.aspectRatio) {
    return
  }
 
  const image = await loadImageElement(file)
  const actualRatio = image.naturalWidth / image.naturalHeight
  const delta = Math.abs(actualRatio - c.aspectRatio)
 
  if (delta > 0.01) {
    const expected = c.aspectRatioLabel || props.field.aspectRatio || 'specified ratio'
    throw new Error(`Image aspect ratio must be ${expected}`)
  }
}
 
const processImageBeforeUpload = async (sourceFile: File): Promise<File | null> => {
  Eif (!hasImageProcessingEnabled.value) {
    return sourceFile
  }
 
  let file = sourceFile
  const c = imageConstraints.value
 
  if (c.cropEnabled) {
    const cropped = await openCropDialog(file)
    if (!cropped) {
      return null
    }
    file = cropped
  }
 
  file = await resizeImageIfNeeded(file)
  await validateImageDimensions(file)
  await validateAspectRatio(file)
 
  return file
}
 
// Function to trigger the hidden file input
const triggerFileInput = () => {
  fileInput.value?.click()
}
 
// Function to trigger the hidden camera-capture input
const triggerCameraInput = () => {
  cameraInput.value?.click()
}
 
// Get full S3 URL from key (with presigned URL for reading), via the shared
// module-level cache so member cards / entity cards / other ImageField
// instances don't re-fetch a presigned URL that's already warm.
// No valid URL — show empty state rather than triggering an ORB-blocked direct S3 request
const getS3Url = async (key: string): Promise<string> => resolveCachedImageUrl(key)
 
// Reactive refs for image URLs
const singleImageUrl = ref('')
const imageSetUrls = ref<string[]>([])
 
// Update URLs when modelValue changes
const updateImageUrls = async () => {
  // Check if there's anything to load
  const hasImageToLoad =
    (props.field.type === 'image' && props.modelValue && typeof props.modelValue === 'string') ||
    (props.field.type === 'image_set' &&
      Array.isArray(props.modelValue) &&
      props.modelValue.length > 0)
 
  if (!hasImageToLoad) {
    // No image to load, set loading to false immediately
    loading.value = false
    singleImageUrl.value = ''
    imageSetUrls.value = []
    return
  }
 
  loading.value = true
  try {
    if (props.field.type === 'image' && props.modelValue && typeof props.modelValue === 'string') {
      singleImageUrl.value = await getS3Url(props.modelValue)
    } else {
      singleImageUrl.value = ''
    }
 
    if (props.field.type === 'image_set' && Array.isArray(props.modelValue)) {
      imageSetUrls.value = await Promise.all(props.modelValue.map((key) => getS3Url(key)))
    } else {
      imageSetUrls.value = []
    }
  } catch (error) {
    console.error('Error loading image URLs:', error)
    // Clear URLs on error
    singleImageUrl.value = ''
    imageSetUrls.value = []
  } finally {
    loading.value = false
  }
}
 
// On img load error: clear stale cache entry and reload (once per key)
const retriedKeys = new Set<string>()
 
const handleSingleImageError = () => {
  const key = typeof props.modelValue === 'string' ? props.modelValue : null
  if (!key || retriedKeys.has(key)) return // already retried, don't loop
  retriedKeys.add(key)
  invalidateImageUrl(key)
  updateImageUrls()
}
 
const handleImageSetError = (index: number) => {
  const key = Array.isArray(props.modelValue) ? props.modelValue[index] : null
  if (!key || retriedKeys.has(key)) return
  retriedKeys.add(key)
  invalidateImageUrl(key)
  updateImageUrls()
}
 
// Watch for changes in modelValue and itemId
watch([() => props.modelValue, () => props.itemId], updateImageUrls, { immediate: true })
 
// Handle file change for single image
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  Eif (!target.files || target.files.length === 0) {
    selectedFileName.value = ''
    return
  }
 
  const file = target.files[0]
  if (file) {
    selectedFileName.value = file.name
    await uploadImage(file)
    // Reset after upload
    selectedFileName.value = ''
  }
}
 
// Handle file change for image set
const handleFileSetChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.files || target.files.length === 0) {
    selectedFileNames.value = []
    return
  }
 
  const files = Array.from(target.files)
  selectedFileNames.value = files.map((f) => f.name)
 
  // Check max images limit
  Eif (props.field.maxImages) {
    const currentCount = Array.isArray(props.modelValue) ? props.modelValue.length : 0
    const totalCount = currentCount + files.length
    Eif (totalCount > props.field.maxImages) {
      toastStore.error(
        t('field.maxImagesExceeded').replace('{count}', String(props.field.maxImages))
      )
      selectedFileNames.value = []
      return
    }
  }
 
  await uploadImages(files)
  // Reset after upload
  selectedFileNames.value = []
}
 
// Get presigned URL for S3 upload
const getPresignedUrl = async (
  fileName: string,
  fileType: string
): Promise<{ uploadUrl: string; uploadFields: Record<string, string>; key: string }> => {
  // Normalize IDs to UUIDs to satisfy API Gateway schema validation.
  const routeEntityId = route.params.entityId as string | undefined
  const routeItemId = route.params.itemId as string | undefined
 
  let entityIdSource = props.entityId || routeEntityId
  let itemIdSource = props.itemId || routeItemId
 
  if (props.field.fieldId === 'profile-picture') {
    const ownerIdCandidate = getAuthUserId() || itemIdSource || entityIdSource
    if (ownerIdCandidate && UUID_GENERIC_REGEX.test(ownerIdCandidate)) {
      entityIdSource = ownerIdCandidate
      itemIdSource = ownerIdCandidate
    } else {
      const stableFallbackId = ensureUuid(ownerIdCandidate)
      entityIdSource = stableFallbackId
      itemIdSource = stableFallbackId
    }
  }
 
  const entityId = ensureUuid(entityIdSource)
  const itemId = ensureUuid(itemIdSource)
 
  // Use fieldId as a stable S3 path segment; fall back to a slug derived from
  // the (English) field name so the path is always meaningful and deterministic
  const fieldIdentifier =
    props.field.fieldId ||
    fieldName.value
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-|-$/g, '') ||
    'field'
 
  if (props.joinSlug) {
    // The requester is not a member yet: the file goes to their drafts, for
    // this field of the space's join form (UC-SPACE-020.1)
    const response = await api.post('/v1/upload/presigned-url', {
      fileName,
      fileType,
      fieldName: props.field.fieldId,
      scope: 'membership-request',
      slug: props.joinSlug
    })
    return response.data
  }
 
  Iif (props.uploadScope === 'user') {
    // User-scoped uploads: not tied to any flow. The backend derives the userId
    // from the JWT claims server-side.
    const response = await api.post('/v1/upload/presigned-url', {
      fileName,
      fileType,
      entityId,
      itemId,
      fieldName: fieldIdentifier,
      scope: 'user'
    })
    return response.data
  }
 
  if (props.field.fieldId === 'pack-picture') {
    // A pack's picture is the pack's, not an entity's or a flow's (UC-STORE-014.1)
    const response = await api.post('/v1/upload/presigned-url', {
      fileName,
      fileType,
      packId: props.packId,
      fieldName: fieldIdentifier
    })
    return response.data
  }
 
  Iif (props.field.fieldId === 'entity-picture' || props.field.fieldId === 'entity-icon') {
    // The entity's own picture/icon isn't tied to any item or flow.
    const response = await api.post('/v1/upload/presigned-url', {
      fileName,
      fileType,
      entityId,
      fieldName: fieldIdentifier
    })
    return response.data
  }
 
  // Flow-scoped upload: resolve flowId with priority: explicit prop → authStore.
  let resolvedFlowId = props.flowId || authStore.currentFlow
  Iif (!resolvedFlowId) {
    await authStore.loadUser()
    resolvedFlowId = props.flowId || authStore.currentFlow
  }
  Iif (!resolvedFlowId) {
    throw new Error('Missing active flow context')
  }
 
  const response = await api.post('/v1/upload/presigned-url', {
    fileName,
    fileType,
    flowId: resolvedFlowId,
    entityId,
    itemId,
    fieldName: fieldIdentifier
  })
 
  return response.data
}
 
// Upload single image (to S3 via presigned URL)
const uploadImage = async (file: File) => {
  uploading.value = true
  try {
    // Validate file type
    if (!file.type.startsWith('image/')) {
      toastStore.error(t('field.imageTypeInvalid'))
      return
    }
 
    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      toastStore.error(t('field.imageSizeInvalid'))
      return
    }
 
    const processedFile = await processImageBeforeUpload(file)
    Iif (!processedFile) {
      return
    }
 
    // Get presigned URL
    const { uploadUrl, uploadFields, key } = await getPresignedUrl(
      processedFile.name,
      processedFile.type
    )
 
    // Upload to S3
    await uploadToS3(processedFile, uploadUrl, uploadFields)
 
    // Store the S3 key (not the full URL for security)
    emit('update:modelValue', key)
  } catch (error) {
    console.error('Error uploading image:', error)
    toastStore.error(getErrorMessage(error, t('field.imageUploadError'), t))
  } finally {
    uploading.value = false
  }
}
 
// Upload multiple images
const uploadImages = async (files: File[]) => {
  uploading.value = true
  try {
    const uploadedKeys: string[] = []
 
    for (const file of files) {
      // Validate file type
      if (!file.type.startsWith('image/')) {
        throw new Error(`${file.name} is not an image file`)
      }
 
      // Validate file size (max 5MB)
      if (file.size > 5 * 1024 * 1024) {
        throw new Error(`${file.name} is larger than 5MB`)
      }
 
      const processedFile = await processImageBeforeUpload(file)
      Iif (!processedFile) {
        continue
      }
 
      // Get presigned URL
      const { uploadUrl, uploadFields, key } = await getPresignedUrl(
        processedFile.name,
        processedFile.type
      )
 
      // Upload to S3
      try {
        await uploadToS3(processedFile, uploadUrl, uploadFields)
      } catch {
        throw new Error(`Failed to upload ${file.name}`)
      }
 
      uploadedKeys.push(key)
    }
 
    const currentImages = Array.isArray(props.modelValue) ? props.modelValue : []
    const newImages = [...currentImages, ...uploadedKeys]
    emit('update:modelValue', newImages)
  } catch (error: any) {
    console.error('Error uploading images:', error)
    toastStore.error(getErrorMessage(error, t('field.imagesUploadError'), t))
  } finally {
    uploading.value = false
  }
}
 
// Remove single image
const removeImage = () => {
  emit('update:modelValue', null)
  selectedFileName.value = ''
  Eif (fileInput.value) {
    fileInput.value.value = ''
  }
}
 
// Remove image from set
const removeImageFromSet = (index: number) => {
  const currentImages = Array.isArray(props.modelValue) ? props.modelValue : []
  const newImages = currentImages.filter((_, i) => i !== index)
  emit('update:modelValue', newImages.length > 0 ? newImages : null)
}
 
// Open image modal for full view
const openImageModal = async (indexOrEvent?: number | Event) => {
  // If it's an Event, ignore the parameter
  if (indexOrEvent && typeof indexOrEvent !== 'number') {
    indexOrEvent = undefined
  }
 
  if (props.field.type === 'image' && typeof props.modelValue === 'string') {
    // Only open modal if we have a valid image URL
    if (!singleImageUrl.value) {
      return
    }
    modalImageUrl.value = singleImageUrl.value
  } else Eif (props.field.type === 'image_set' && typeof indexOrEvent === 'number') {
    const url = imageSetUrls.value[indexOrEvent]
    if (url) {
      modalImageUrl.value = url
    } else {
      return
    }
  }
 
  showModal.value = true
}
 
// Close image modal
const closeImageModal = () => {
  showModal.value = false
  // Keep modalImageUrl for next open to avoid re-fetching
}
</script>
 
<style scoped>
.image-field {
  width: 100%;
}
 
.image-display,
.image-set-display {
  min-height: 40px;
}
 
.image-preview {
  cursor: pointer;
  transition: transform 0.2s;
  display: block;
}
 
.image-preview:hover {
  transform: scale(1.05);
}
 
.image-static {
  display: block;
}
 
.no-image {
  padding: 0.5rem;
  font-style: italic;
}
 
.image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  cursor: pointer;
}
 
.image-modal-static {
  cursor: default;
}
 
.modal-content {
  position: relative;
  width: auto;
  max-width: 90%;
  max-height: 90%;
  cursor: default;
}
 
.modal-content img {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}
 
.crop-modal-content {
  max-width: 760px;
  max-height: 90vh;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}
 
.crop-cropper-wrapper {
  flex: 1 1 auto;
  min-height: 200px;
  background: #0f1217;
  border-radius: 0.375rem;
  overflow: hidden;
}
 
.crop-cropper {
  width: 100%;
  height: 100%;
}
</style>