All files / src/components ImageField.vue

56.45% Statements 271/480
55.74% Branches 199/357
47.05% Functions 32/68
56.92% Lines 263/462

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193  313x                                                           6x   8x                                     6x                           6x                                 6x                     6x   12x                                     6x                                                                                                       6x 6x   6x                     6x                                           151x 151x 151x 151x                                   151x               151x     151x   151x 151x 151x 151x 151x 151x 151x   151x 19x 19x                   151x   2x 2x     151x 1x       1x 1x     151x   151x   151x 23x 4x     19x                             151x 151x 151x 151x 151x 151x 151x   151x                 151x 30x 30x           151x 5x 5x                                                   151x 5x   5x                         151x 5x   5x                       151x               151x                                             151x                         151x                                                                           151x                       151x                       151x                           151x       151x 2x       2x 1x     1x       1x         1x     151x                                                                                                               151x                                                           151x                                               151x                               151x 6x 6x                                           151x         151x 46x 46x 44x   19x 19x 1x 1x     18x 18x         6x 6x 151x     151x   46x 46x 1x       45x 45x 6x 6x 6x         45x 45x 2x 2x       43x   43x       151x 151x     151x     157x         157x   123x 123x 123x 123x     34x 34x 34x 25x   9x     34x 17x   25x               34x         151x   151x               151x                 157x     151x 1x 1x 1x 1x                         151x 2x 2x 1x 1x     1x 2x     1x 1x 1x 1x 1x 1x 1x                   151x       11x 11x       11x         11x 11x   11x 11x   11x 2x 2x 1x 1x   1x 1x 1x       11x 11x         11x             11x                   10x 2x                     10x       151x 5x 5x   5x 1x 1x       4x 1x 1x     3x 3x         3x     2x               2x 1x       1x   2x 2x 2x   5x         151x 4x 4x 4x   4x   5x 1x       4x 1x     3x 3x         3x     3x               3x 1x     2x     1x 4x 4x   3x 3x   4x         151x 2x 2x 2x 2x         151x 2x 4x 2x       151x   5x 1x     5x   3x 1x   2x 2x 2x 2x 1x   1x       3x       151x 1x         151x 6x   5x 5x   4x   4x   1x 1x   1x 1x       3x 2x 4x 2x 2x 2x     2x   2x               151x                                                                                                                                                                                                
<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="{ 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-outline-danger ms-2" @click="removeImage">
          <font-awesome-icon icon="fa-solid fa-trash" />
        </button>
      </div>
      <div class="file-input-wrapper">
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          class="d-none"
          :disabled="uploading"
          @change="handleFileChange"
        />
        <button
          type="button"
          class="btn btn-sm btn-outline-primary"
          :disabled="uploading"
          @click="triggerFileInput"
        >
          {{ t('common.chooseFile') }}
        </button>
        <span class="ms-2 text-muted small">
          {{ selectedFileName || t('common.noFileChosen') }}
        </span>
      </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 position-absolute top-0 end-0"
            style="padding: 0.1rem 0.3rem; font-size: 0.75rem"
            @click="removeImageFromSet(index)"
          >
            <font-awesome-icon icon="fa-solid fa-times" />
          </button>
        </div>
      </div>
      <div class="file-input-wrapper">
        <input
          ref="fileInput"
          type="file"
          accept="image/*"
          multiple
          class="d-none"
          :disabled="uploading"
          @change="handleFileSetChange"
        />
        <button
          type="button"
          class="btn btn-sm btn-outline-primary"
          :disabled="
            uploading || !!(props.field.maxImages && imageSetUrls.length >= props.field.maxImages)
          "
          @click="triggerFileInput"
        >
          {{ t('common.chooseFile') }}
        </button>
        <span v-if="selectedFileNames.length > 0" class="ms-2 text-muted small">
          {{ selectedFileNames.join(', ') }}
        </span>
        <span v-else class="ms-2 text-muted small">
          {{ t('common.noFileChosen') }}
        </span>
      </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 -->
    <div v-if="showCropDialog" class="image-modal" @click="cancelCropDialog">
      <div class="modal-content crop-modal-content" @click.stop>
        <h6 class="mb-2">{{ t('common.cropImage') }}</h6>
        <p class="text-muted small mb-3">{{ t('common.cropImageHint') }}</p>
 
        <div class="crop-image-wrapper">
          <img
            ref="cropImageRef"
            :src="cropImageUrl"
            :alt="fieldName"
            class="crop-preview-image"
            @click="onCropImageClick"
          />
          <div v-if="cropMarkerStyle" class="crop-focus-marker" :style="cropMarkerStyle" />
        </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 api from '@/services/api'
import type { EntityField } from '@/stores/entities'
 
const route = useRoute()
const authStore = useAuthStore()
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)
  clickable?: boolean // Allow clicking to open modal
  noWrapper?: boolean // Remove the .image-field wrapper div
}
 
interface Emits {
  (e: 'update:modelValue', value: string | string[] | null): void
}
 
const props = withDefaults(defineProps<Props>(), {
  itemId: undefined,
  entityId: undefined,
  objectFit: 'cover',
  noThumbnail: false,
  clickable: true,
  noWrapper: false
})
const emit = defineEmits<Emits>()
 
// Computed property for field name (translated)
const fieldName = computed(() => getTranslation(props.field.name))
 
const fileInput = 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[]>([])
 
const createTempUuid = (): string => {
  Eif (typeof globalThis.crypto?.randomUUID === 'function') {
    return globalThis.crypto.randomUUID()
  }
 
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = Math.floor(Math.random() * 16)
    const v = c === 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
 
const getAuthUserId = (): string => {
  const candidate =
    authStore.user?.attributes?.sub || authStore.user?.sub || authStore.user?.userId || ''
  return typeof candidate === 'string' && candidate.trim() ? candidate : ''
}
 
const isProfilePictureKey = (key: string): boolean => {
  Iif (!key) {
    return false
  }
 
  const parts = key.split('/')
  return parts[3] === 'profile-picture' || key.includes('/profile-picture/')
}
 
const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
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
 
const ensureUuid = (value: string | undefined): string => {
  if (value && UUID_V4_REGEX.test(value)) {
    return value
  }
 
  return createTempUuid()
}
 
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 cropImageRef = ref<HTMLImageElement | null>(null)
const cropFocusXRatio = ref(0.5)
const cropFocusYRatio = ref(0.5)
let cropResolver: ((file: File | null) => void) | null = null
 
const cropMarkerStyle = computed(() => {
  if (!showCropDialog.value) return null
 
  return {
    left: `${Math.max(0, Math.min(100, cropFocusXRatio.value * 100))}%`,
    top: `${Math.max(0, Math.min(100, cropFocusYRatio.value * 100))}%`
  }
})
 
const normalizePositiveNumber = (value: unknown): number | undefined => {
  Eif (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
    return undefined
  }
 
  return Math.round(value)
}
 
const parseAspectRatio = (value: unknown): { ratio?: number; label?: string } => {
  Eif (typeof value !== 'string') {
    return {}
  }
 
  const normalized = value.trim()
  if (!normalized) {
    return {}
  }
 
  const parts = normalized.split(':')
  if (parts.length !== 2) {
    return {}
  }
 
  const width = Number.parseFloat(parts[0])
  const height = Number.parseFloat(parts[1])
 
  if (!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')
  if (!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)
  })
 
  if (!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)
  cropFocusXRatio.value = 0.5
  cropFocusYRatio.value = 0.5
  showCropDialog.value = true
 
  return await new Promise<File | null>((resolve) => {
    cropResolver = resolve
  })
}
 
const onCropImageClick = (event: MouseEvent) => {
  const target = cropImageRef.value
  if (!target) return
 
  const rect = target.getBoundingClientRect()
  if (rect.width <= 0 || rect.height <= 0) return
 
  const xRatio = (event.clientX - rect.left) / rect.width
  const yRatio = (event.clientY - rect.top) / rect.height
 
  cropFocusXRatio.value = Math.max(0, Math.min(1, xRatio))
  cropFocusYRatio.value = Math.max(0, Math.min(1, yRatio))
}
 
const cancelCropDialog = () => {
  closeCropDialog(null)
}
 
const getCropTargetAspectRatio = (constraints: ImageConstraints): number => {
  Iif (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
}
 
const applyCropDialog = async () => {
  if (!cropSourceFile.value) {
    closeCropDialog(null)
    return
  }
 
  try {
    const source = cropSourceFile.value
    const image = await loadImageElement(source)
    const sourceWidth = image.naturalWidth
    const sourceHeight = image.naturalHeight
 
    const c = imageConstraints.value
    const targetAspectRatio = getCropTargetAspectRatio(c)
 
    const sourceAspectRatio = sourceWidth / sourceHeight
    let cropWidth = sourceWidth
    let cropHeight = sourceHeight
 
    if (sourceAspectRatio > targetAspectRatio) {
      cropWidth = Math.round(sourceHeight * targetAspectRatio)
      cropHeight = sourceHeight
    } else {
      cropWidth = sourceWidth
      cropHeight = Math.round(sourceWidth / targetAspectRatio)
    }
 
    const focalX = cropFocusXRatio.value * sourceWidth
    const focalY = cropFocusYRatio.value * sourceHeight
    const sx = Math.max(0, Math.min(sourceWidth - cropWidth, Math.round(focalX - cropWidth / 2)))
    const sy = Math.max(0, Math.min(sourceHeight - cropHeight, Math.round(focalY - cropHeight / 2)))
 
    let outWidth = cropWidth
    let outHeight = cropHeight
    if (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(
      image,
      { sx, sy, sw: cropWidth, sh: cropHeight },
      { 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()
}
 
// Get presigned read URL from API
const getPresignedReadUrl = async (key: string): Promise<string> => {
  try {
    const response = await api.post('/v1/upload/presigned-read-url', { key })
    return response.data.readUrl
  } catch (error) {
    const status = (error as any)?.response?.status
    if (status === 404 && isProfilePictureKey(key)) {
      console.warn('Profile picture read URL unavailable for key:', key)
      return ''
    }
 
    console.error('Error getting presigned read URL for key:', key, error)
    return '' // Return empty string on error
  }
}
 
// Cache for presigned URLs with TTL (Lambda URLs expire in 1 hour — refresh at 55 min)
const PRESIGNED_URL_TTL_MS = 55 * 60 * 1000
const FAILED_URL_TTL_MS = 60 * 1000
const urlCache = ref<Map<string, { url: string; expiresAt: number }>>(new Map())
 
// Get full S3 URL from key (with presigned URL for reading)
const getS3Url = async (key: string): Promise<string> => {
  // Check cache with TTL
  const cached = urlCache.value.get(key)
  if (cached && Date.now() < cached.expiresAt) {
    return cached.url
  }
 
  // If key contains temp- prefix, replace it with real itemId if available
  let finalKey = key
  if (key.includes('temp-') && props.itemId) {
    const tempPrefix = key.split('/')[2] // flow/entity/temp-id/field/file
    Eif (tempPrefix && tempPrefix.startsWith('temp-')) {
      finalKey = key.replace(`/${tempPrefix}/`, `/${props.itemId}/`)
    }
  }
 
  // Get presigned read URL
  const presignedUrl = await getPresignedReadUrl(finalKey)
  if (presignedUrl) {
    urlCache.value.set(key, { url: presignedUrl, expiresAt: Date.now() + PRESIGNED_URL_TTL_MS })
    return presignedUrl
  }
 
  // Cache failed lookups briefly to avoid request spam while backend catches up.
  urlCache.value.set(key, { url: '', expiresAt: Date.now() + FAILED_URL_TTL_MS })
 
  return '' // No valid URL — show empty state rather than triggering an ORB-blocked direct S3 request
}
 
// 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)
  urlCache.value.delete(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)
  urlCache.value.delete(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) {
      alert(`Maximum ${props.field.maxImages} images allowed`)
      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; key: string }> => {
  let flowId = authStore.currentFlow
  Iif (!flowId) {
    await authStore.loadUser()
    flowId = authStore.currentFlow
  }
  Iif (!flowId) {
    throw new Error('Missing active flow context')
  }
 
  // 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'
 
  const response = await api.post('/v1/upload/presigned-url', {
    fileName,
    contentType: fileType,
    fileType,
    flowId,
    entityId,
    itemId,
    fieldName: fieldIdentifier
  })
 
  if (props.field.fieldId === 'profile-picture') {
    console.warn('[profile-picture] presigned-url payload/result', {
      flowId,
      fieldName: fieldIdentifier,
      entityIdSource,
      itemIdSource,
      resolvedEntityId: entityId,
      resolvedItemId: itemId,
      returnedKey: response.data?.key
    })
  }
 
  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/')) {
      alert('Please select an image file')
      return
    }
 
    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      alert('Image size must be less than 5MB')
      return
    }
 
    const processedFile = await processImageBeforeUpload(file)
    Iif (!processedFile) {
      return
    }
 
    // Get presigned URL
    const { uploadUrl, key } = await getPresignedUrl(processedFile.name, processedFile.type)
 
    // Upload to S3
    const uploadResponse = await fetch(uploadUrl, {
      method: 'PUT',
      body: processedFile,
      headers: {
        'Content-Type': processedFile.type
      }
    })
 
    if (!uploadResponse.ok) {
      throw new Error('Failed to upload to S3')
    }
 
    // Store the S3 key (not the full URL for security)
    emit('update:modelValue', key)
  } catch (error) {
    console.error('Error uploading image:', error)
    const apiError = (error as any)?.response?.data?.error
    alert(apiError || 'Failed to upload image')
  } 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, key } = await getPresignedUrl(processedFile.name, processedFile.type)
 
      // Upload to S3
      const uploadResponse = await fetch(uploadUrl, {
        method: 'PUT',
        body: processedFile,
        headers: {
          'Content-Type': processedFile.type
        }
      })
 
      if (!uploadResponse.ok) {
        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)
    alert(error?.response?.data?.error || error.message || 'Failed to upload images')
  } 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
}
 
// Expose method to migrate images when real itemId becomes available
const migrateImagesToRealItemId = async (realItemId: string) => {
  if (!realItemId) return
 
  const currentValue = props.modelValue
  if (!currentValue) return
 
  try {
    // For single image
    if (typeof currentValue === 'string' && currentValue.includes('temp-')) {
      // Extract temp ID from the key
      const tempPrefix = currentValue.split('/')[2] // flow/entity/temp-id/field/file
      Eif (tempPrefix && tempPrefix.startsWith('temp-')) {
        // Create new key with real itemId
        const newKey = currentValue.replace(`/${tempPrefix}/`, `/${realItemId}/`)
        emit('update:modelValue', newKey)
      }
    }
    // For image sets
    else if (Array.isArray(currentValue)) {
      const migratedKeys = currentValue.map((key) => {
        if (key.includes('temp-')) {
          const tempPrefix = key.split('/')[2]
          Eif (tempPrefix && tempPrefix.startsWith('temp-')) {
            return key.replace(`/${tempPrefix}/`, `/${realItemId}/`)
          }
        }
        return key
      })
      emit('update:modelValue', migratedKeys)
    }
  } catch (error) {
    console.error('Error migrating images:', error)
  }
}
 
// Expose the migration method
defineExpose({
  migrateImagesToRealItemId
})
</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;
}
 
.modal-content {
  position: relative;
  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;
  width: min(90vw, 760px);
  padding: 1rem;
}
 
.crop-image-wrapper {
  position: relative;
  width: 100%;
  max-height: 65vh;
  overflow: hidden;
  background: #0f1217;
  border-radius: 0.375rem;
}
 
.crop-preview-image {
  width: 100%;
  max-height: 65vh;
  object-fit: contain;
  cursor: crosshair;
  display: block;
}
 
.crop-focus-marker {
  position: absolute;
  width: 16px;
  height: 16px;
  border: 2px solid #ffffff;
  border-radius: 50%;
  background: rgba(97, 85, 129, 0.45);
  transform: translate(-50%, -50%);
  pointer-events: none;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.4);
}
</style>