All files / src/views UserProfilePage.vue

92.66% Statements 240/259
91.19% Branches 176/193
69.38% Functions 34/49
92.4% Lines 231/250

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    1x   1x 1x 1x 1x       1x   1x                                             1x       1x       1x               3x                                                 1x 1x                                                         1x 1x                             1x                                 1x 1x                                         1x                     1x 1x           972x               3x                 1x 1x 1x                               1x 1x 1x 1x       1x       1x 1x 1x 1x 1x   1928x                 1x         1x           1x 1x 1x                         160x               1x   1x                           1x                             324x     1x 1x 1x 1x                     1x                     1x                     1x         1x                                           1x 3x                                                                                     77x 77x 77x 77x 77x 77x 77x 77x   77x 77x 77x 77x 77x 77x 77x 77x 77x 77x     77x         77x   77x   77x 82x 80x 82x 1x   79x       2x 2x 2x 1x   1x 1x   2x     77x     3x 2x 2x 2x 2x 2x 1x   1x 1x 1x   2x       77x 77x 77x     77x 77x 77x 77x   152x     3x 3x       4x   4x 1x 1x     3x   2x 2x 2x 2x 1x 1x 1x 1x   1x   2x       77x         77x 77x   77x 85x       3x   2x 2x 2x 1x 1x 1x 1x   1x   2x       77x 972x 1929x       77x   77x 77x     77x 77x 77x 77x     77x 77x 77x   77x 77x 77x   77x 77x 77x 77x 77x 77x   77x 77x 77x 77x                   3x 3x   3x 3x   3x           2x       3x 1x           2x   2x 2x 1x   1x       2x         2x           1x 1x   3x         2x 1x 1x         1x 1x       3x 3x 2x 2x         7x   4x 4x     1x 1x 1x 1x 1x       8x   8x   6x   6x   5x 3x 3x   1x         6x 6x   6x 3x         7x 7x 7x   7x               3x 3x 3x 3x 2x   1x 1x   1x 1x   3x         1x                                                                                                                                                                                                                                                              
<template>
  <PageLayout :title="t('profile.title')" class="profile-page" scrollable>
    <div class="row">
      <!-- Account Information Card -->
      <div class="col-xl-4 mb-3">
        <div class="card h-100">
          <div class="card-body">
            <h5 class="card-title">
              <font-awesome-icon icon="fa-solid fa-user" class="me-2 text-success" />
              {{ t('profile.accountInformation') }}
            </h5>
            <div class="mb-2">
              <label for="profile-name" class="text-muted small">{{ t('profile.name') }}</label>
              <div class="name-group">
                <input
                  id="profile-name"
                  class="form-control name-group-input"
                  type="text"
                  maxlength="100"
                  :value="nameDraft"
                  @input="onNameInput"
                />
                <button
                  class="btn btn-sm btn-outline-success name-group-save"
                  type="button"
                  :disabled="!canSaveName || isSavingName"
                  @click="saveName"
                >
                  {{ t('common.save') }}
                </button>
              </div>
              <div v-if="nameError" class="form-text text-danger">
                {{ nameError }}
              </div>
            </div>
            <div>
              <div class="text-muted small">{{ t('profile.email') }}</div>
              <div>{{ userStore.user?.attributes?.email || 'N/A' }}</div>
            </div>
 
            <div class="mt-3">
              <label for="profile-nickname" class="text-muted small">{{
                t('auth.nickname')
              }}</label>
              <div class="nickname-group">
                <span class="nickname-group-prefix" aria-hidden="true">@</span>
                <input
                  id="profile-nickname"
                  class="form-control nickname-group-input"
                  type="text"
                  maxlength="20"
                  :value="nicknameDraft"
                  @input="onNicknameInput"
                />
                <button
                  class="btn btn-sm btn-outline-success nickname-group-save"
                  type="button"
                  :disabled="!canSaveNickname || isSavingNickname"
                  @click="saveNickname"
                >
                  {{ t('common.save') }}
                </button>
              </div>
              <div v-if="nicknameStatus === 'checking'" class="form-text">
                {{ t('auth.nicknameChecking') }}
              </div>
              <div v-else-if="nicknameStatus === 'available'" class="form-text text-success">
                {{ t('auth.nicknameAvailable') }}
              </div>
              <div v-else-if="nicknameStatus === 'taken'" class="form-text text-danger">
                {{ t('auth.nicknameTaken') }}
              </div>
              <div v-else-if="nicknameStatus === 'invalid'" class="form-text text-danger">
                {{ t('auth.nicknameInvalid') }}
              </div>
            </div>
 
            <div class="mt-3">
              <div class="text-muted small mb-1">{{ t('profile.profilePictureOptional') }}</div>
              <ImageField
                :model-value="profilePicture"
                :field="{
                  name: t('profile.profilePicture'),
                  type: 'image',
                  fieldId: 'profile-picture',
                  minWidth: 100,
                  minHeight: 100,
                  aspectRatio: '1:1',
                  cropEnabled: true,
                  resizeMaxWidth: 500,
                  resizeMaxHeight: 500
                }"
                :is-editing="true"
                :entity-id="profileImageOwnerId || undefined"
                :item-id="profileImageOwnerId || undefined"
                :clickable="false"
                upload-scope="user"
                no-wrapper
                @update:model-value="updateProfilePicture"
              />
              <div v-if="isSavingProfilePicture" class="text-muted small mt-2">
                <font-awesome-icon icon="fa-solid fa-spinner" spin class="me-1" />
                {{ t('common.loading') }}
              </div>
            </div>
 
            <hr class="my-3" />
            <h6 class="mb-2">{{ t('profile.interfaceTheme') }}</h6>
            <p class="text-muted small mb-2">{{ t('profile.interfaceThemeDescription') }}</p>
            <div class="btn-group w-100" role="group" :aria-label="t('profile.interfaceTheme')">
              <button
                type="button"
                class="btn btn-sm"
                :class="themePreference === 'light' ? 'btn-primary' : 'btn-outline-secondary'"
                @click="updateThemePreference('light')"
              >
                <font-awesome-icon icon="fa-solid fa-sun" class="me-2" />
                {{ t('profile.interfaceThemeLight') }}
              </button>
              <button
                type="button"
                class="btn btn-sm"
                :class="themePreference === 'dark' ? 'btn-primary' : 'btn-outline-secondary'"
                @click="updateThemePreference('dark')"
              >
                <font-awesome-icon icon="fa-solid fa-moon" class="me-2" />
                {{ t('profile.interfaceThemeDark') }}
              </button>
              <button
                type="button"
                class="btn btn-sm"
                :class="themePreference === 'system' ? 'btn-primary' : 'btn-outline-secondary'"
                @click="updateThemePreference('system')"
              >
                <font-awesome-icon icon="fa-solid fa-laptop" class="me-2" />
                {{ t('profile.interfaceThemeSystem') }}
              </button>
            </div>
 
            <hr class="my-3" />
            <h6 class="mb-2">{{ t('profile.languageDisplay') }}</h6>
            <p class="text-muted small mb-2">{{ t('profile.languageDisplayDescription') }}</p>
            <div
              class="btn-group w-100 language-display-group"
              role="group"
              :aria-label="t('profile.languageDisplay')"
            >
              <button
                type="button"
                class="btn btn-sm"
                :class="flagPreference === 'flags' ? 'btn-primary' : 'btn-outline-secondary'"
                :aria-pressed="flagPreference === 'flags'"
                @click="setFlagPreference('flags')"
              >
                <font-awesome-icon icon="fa-solid fa-flag" class="me-2" />
                {{ t('profile.languageDisplayFlags') }}
              </button>
              <button
                type="button"
                class="btn btn-sm"
                :class="flagPreference === 'names' ? 'btn-primary' : 'btn-outline-secondary'"
                :aria-pressed="flagPreference === 'names'"
                @click="setFlagPreference('names')"
              >
                <font-awesome-icon icon="fa-solid fa-font" class="me-2" />
                {{ t('profile.languageDisplayNames') }}
              </button>
            </div>
            <p v-if="!canShowFlags" class="text-muted small mt-2 mb-0 flags-unsupported">
              {{ t('profile.languageDisplayUnsupported') }}
            </p>
 
            <hr class="my-3" />
            <h6 class="mb-2">{{ t('profile.whoCanMessageMe') }}</h6>
            <p class="text-muted small mb-2">{{ t('profile.whoCanMessageMeDescription') }}</p>
            <div
              class="btn-group w-100 dm-policy-group"
              role="group"
              :aria-label="t('profile.whoCanMessageMe')"
            >
              <button
                v-for="option in DM_POLICY_OPTIONS"
                :key="option.value"
                type="button"
                class="btn btn-sm"
                :class="dmPolicy === option.value ? 'btn-primary' : 'btn-outline-secondary'"
                :aria-pressed="dmPolicy === option.value"
                :disabled="isSavingDmPolicy"
                @click="updateDmPolicy(option.value)"
              >
                <font-awesome-icon :icon="option.icon" class="me-2" />
                {{ t(option.labelKey) }}
              </button>
            </div>
 
            <hr class="my-3" />
            <section data-tour="profile-walkthrough" class="walkthrough-setting">
              <h6 class="mb-2">{{ t('walkthrough.profileTitle') }}</h6>
              <p class="text-muted small mb-2">{{ t('walkthrough.profileDescription') }}</p>
              <p class="small mb-2 walkthrough-status">{{ walkthroughStatus }}</p>
              <button
                type="button"
                class="btn btn-sm btn-outline-secondary restart-walkthrough-btn"
                :disabled="isResettingWalkthrough"
                @click="restartWalkthrough"
              >
                <font-awesome-icon icon="fa-solid fa-rotate-left" class="me-2" />
                {{ t('walkthrough.restart') }}
              </button>
            </section>
          </div>
        </div>
      </div>
 
      <!-- Language Preferences Card -->
      <div class="col-xl-8 mb-3">
        <div class="card h-100">
          <div class="card-body">
            <h5 class="card-title mb-3">
              <font-awesome-icon icon="fa-solid fa-language" class="me-2 text-success" />
              {{ t('profile.contentLanguagePreferences') }}
            </h5>
            <p class="text-muted small mb-3">
              {{ t('profile.contentLanguageDescription') }}
            </p>
 
            <div class="row">
              <div class="col-md-6 mb-3">
                <h6 class="mb-2">{{ t('profile.availableLanguages') }}</h6>
                <p class="text-muted small mb-2">{{ t('profile.clickToAdd') }}</p>
                <div class="language-list-container">
                  <div v-if="!isLoadingPreferences">
                    <div
                      v-for="lang in availableLanguages"
                      :key="lang.code"
                      class="language-item available mb-1"
                      draggable="true"
                      @click="addLanguagePreference(lang.code)"
                      @dragstart="handleDragStart($event, lang.code, 'available')"
                    >
                      <span v-if="showFlags" class="me-2">{{ lang.flag }}</span>
                      <span class="flex-grow-1">{{ lang.nativeName }}</span>
                    </div>
                  </div>
                  <div v-else class="text-center py-4">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                      <span class="visually-hidden">{{ t('common.loading') }}</span>
                    </div>
                  </div>
                </div>
              </div>
 
              <div class="col-md-6 mb-3">
                <h6 class="mb-2">{{ t('profile.yourPreferenceOrder') }}</h6>
                <p class="text-muted small mb-2">
                  {{
                    preferences.length > 0
                      ? t('profile.dragToReorder')
                      : t('profile.addLanguagesToStart')
                  }}
                </p>
                <div
                  class="language-list-container preferences-container"
                  @drop="handleDrop($event)"
                  @dragover.prevent
                  @dragenter.prevent
                >
                  <div
                    v-for="(langCode, index) in preferences"
                    :key="langCode"
                    class="language-item preferred mb-1"
                    draggable="true"
                    @dragstart="handleDragStart($event, langCode, 'preferred')"
                    @dragover.prevent="handleDragOver($event, index)"
                  >
                    <span class="badge bg-success me-2">{{ index + 1 }}</span>
                    <span v-if="showFlags" class="me-2">{{ getLanguageInfo(langCode)?.flag }}</span>
                    <span class="flex-grow-1 me-2">{{
                      getLanguageInfo(langCode)?.nativeName
                    }}</span>
                    <button
                      class="btn btn-sm btn-danger p-0"
                      style="width: 20px; height: 20px; line-height: 1"
                      :title="t('profile.removeFromPreferences')"
                      @click="removeLanguagePreference(index)"
                    >
                      ×
                    </button>
                  </div>
                  <div v-if="isLoadingPreferences" class="text-center py-4">
                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                      <span class="visually-hidden">{{ t('common.loading') }}</span>
                    </div>
                  </div>
                  <div
                    v-else-if="preferences.length === 0"
                    class="text-muted fst-italic text-center py-4 no-preferences"
                  >
                    {{ t('profile.noPreferencesSet') }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
 
    <!-- Social: Followers / Following / Subscriptions / Blocked -->
    <div class="card mb-3">
      <div class="card-body">
        <ul class="nav nav-tabs mb-3">
          <li class="nav-item">
            <button
              type="button"
              class="nav-link"
              :class="{ active: activeSocialTab === 'followers' }"
              @click="activeSocialTab = 'followers'"
            >
              <font-awesome-icon icon="fa-solid fa-users" class="me-2" />
              {{ t('follows.followersTab') }}
            </button>
          </li>
          <li class="nav-item">
            <button
              type="button"
              class="nav-link"
              :class="{ active: activeSocialTab === 'following' }"
              @click="activeSocialTab = 'following'"
            >
              <font-awesome-icon icon="fa-solid fa-user-check" class="me-2" />
              {{ t('follows.followingTab') }}
            </button>
          </li>
          <li class="nav-item">
            <button
              type="button"
              class="nav-link"
              :class="{ active: activeSocialTab === 'subscriptions' }"
              @click="activeSocialTab = 'subscriptions'"
            >
              <font-awesome-icon icon="fa-solid fa-bell" class="me-2" />
              {{ t('follows.subscriptionsTab') }}
            </button>
          </li>
          <li class="nav-item">
            <button
              type="button"
              class="nav-link"
              :class="{ active: activeSocialTab === 'blocked' }"
              @click="activeSocialTab = 'blocked'"
            >
              <font-awesome-icon icon="fa-solid fa-user-slash" class="me-2" />
              {{ t('messages.blockedTab') }}
            </button>
          </li>
        </ul>
 
        <FollowersList v-if="activeSocialTab === 'followers'" :user-id="currentUserId" />
        <FollowingList v-else-if="activeSocialTab === 'following'" :user-id="currentUserId" />
        <EntitySubscriptionsList v-else-if="activeSocialTab === 'subscriptions'" />
        <BlockedUsersList v-else />
      </div>
    </div>
 
    <!-- Danger Zone -->
    <DangerZone class="mb-3">
      <DangerZoneAction
        :action-label="t('profile.deleteAccount')"
        :warning-text="t('profile.deleteAccountWarning')"
        :disabled="isDeletingAccount"
        :error="deleteAccountError"
        @action="confirmDeleteAccount.open = true"
      />
    </DangerZone>
  </PageLayout>
 
  <ConfirmModal
    :is-open="confirmDeleteAccount.open"
    :title="t('profile.deleteAccount')"
    :message="t('profile.deleteAccountWarning')"
    :confirm-label="isDeletingAccount ? t('profile.deletingAccount') : t('profile.deleteAccount')"
    :confirm-text="t('profile.deleteAccountConfirmText')"
    variant="danger"
    :busy="isDeletingAccount"
    @confirm="doDeleteAccount"
    @cancel="confirmDeleteAccount.open = false"
  />
</template>
 
<script setup lang="ts">
// @implements UC-AUTH-006.1, UC-AUTH-008.1, UC-PROFILE-001.1, UC-PROFILE-002.1, UC-PROFILE-003.1, UC-PROFILE-004.1, UC-PROFILE-005.1, UC-I18N-001.1, UC-I18N-009.1, UC-DM-008.1, UC-DM-009.1, UC-ONBOARD-004.1
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { updateUserAttributes } from 'aws-amplify/auth'
import PageLayout from '@/components/PageLayout.vue'
import ConfirmModal from '@/components/ConfirmModal.vue'
import DangerZone from '@/components/DangerZone.vue'
import DangerZoneAction from '@/components/DangerZoneAction.vue'
import ImageField from '@/components/ImageField.vue'
import FollowersList from '@/components/FollowersList.vue'
import FollowingList from '@/components/FollowingList.vue'
import EntitySubscriptionsList from '@/components/EntitySubscriptionsList.vue'
import BlockedUsersList from '@/components/BlockedUsersList.vue'
import { useAuthStore as useUserStore } from '@/stores/auth'
import { useLanguage } from '@/composables/useLanguage'
import { useUILanguage } from '@/composables/useUILanguage'
import { formatDate } from '@/utils/dateFormat'
import { useNicknameAvailability } from '@/composables/useNicknameAvailability'
import { useTheme, type ThemePreference } from '@/composables/useTheme'
import { useLanguageFlags } from '@/composables/useLanguageFlags'
import { CONTENT_LANGUAGES, getLanguageInfo } from '@/utils/languages'
import api from '@/services/api'
import { useToastStore } from '@/stores/toast'
import { useWalkthroughStore } from '@/stores/walkthrough'
 
const userStore = useUserStore()
const router = useRouter()
const toastStore = useToastStore()
const { getLanguagePreferences, setLanguagePreferences, initializePreferences } = useLanguage()
const { t, uiLanguage } = useUILanguage()
const { themePreference, setThemePreference } = useTheme()
const { canShowFlags, flagPreference, setFlagPreference, showFlags } = useLanguageFlags()
const walkthroughStore = useWalkthroughStore()
 
const preferences = ref<string[]>([])
const initialPreferences = ref<string[]>([])
const isLoadingPreferences = ref(true)
const draggedItem = ref<{ code: string; source: 'available' | 'preferred' } | null>(null)
const reorderingOccurred = ref(false)
const profilePicture = ref<string | null>(null)
const isSavingProfilePicture = ref(false)
const confirmDeleteAccount = reactive({ open: false })
const isDeletingAccount = ref(false)
const deleteAccountError = ref('')
 
type DmPolicy = 'everyone' | 'connections' | 'nobody'
const DM_POLICY_OPTIONS: { value: DmPolicy; labelKey: string; icon: string }[] = [
  { value: 'everyone', labelKey: 'profile.dmPolicyEveryone', icon: 'fa-solid fa-globe' },
  { value: 'connections', labelKey: 'profile.dmPolicyConnections', icon: 'fa-solid fa-users' },
  { value: 'nobody', labelKey: 'profile.dmPolicyNobody', icon: 'fa-solid fa-lock' }
]
const dmPolicy = ref<DmPolicy>('everyone')
 
const isResettingWalkthrough = ref(false)
 
const walkthroughStatus = computed(() => {
  if (walkthroughStore.dismissed) return t('walkthrough.statusDismissed')
  const until = walkthroughStore.snoozedUntil ? new Date(walkthroughStore.snoozedUntil) : null
  if (until && until.getTime() > Date.now()) {
    return t('walkthrough.statusSnoozed').replace('{date}', formatDate(until, uiLanguage.value))
  }
  return t('walkthrough.statusActive')
})
 
async function restartWalkthrough() {
  isResettingWalkthrough.value = true
  try {
    await walkthroughStore.reset()
    toastStore.success(t('walkthrough.restarted'))
  } catch (error) {
    console.error('Failed to reset walkthrough:', error)
    toastStore.error(t('walkthrough.restartError'))
  } finally {
    isResettingWalkthrough.value = false
  }
}
const isSavingDmPolicy = ref(false)
 
async function updateDmPolicy(value: DmPolicy) {
  if (value === dmPolicy.value) return
  const previous = dmPolicy.value
  dmPolicy.value = value
  isSavingDmPolicy.value = true
  try {
    await api.put('/v1/users/preferences', { dmPolicy: value })
    toastStore.success(t('profile.dmPolicySaved'))
  } catch (error) {
    console.error('Failed to save who can message me:', error)
    dmPolicy.value = previous
    toastStore.error(t('profile.dmPolicySaveError'))
  } finally {
    isSavingDmPolicy.value = false
  }
}
 
const activeSocialTab = ref<'followers' | 'following' | 'subscriptions' | 'blocked'>('followers')
const currentUserId = computed(
  () => userStore.user?.attributes?.sub || userStore.user?.sub || userStore.user?.userId || ''
)
 
const savedName = ref('')
const nameDraft = ref('')
const nameError = ref('')
const isSavingName = ref(false)
 
const canSaveName = computed(() => nameDraft.value !== savedName.value)
 
function onNameInput(event: Event) {
  nameDraft.value = (event.target as HTMLInputElement).value
  nameError.value = ''
}
 
async function saveName() {
  const trimmedName = nameDraft.value.trim()
 
  if (!trimmedName) {
    nameError.value = t('profile.nameEmptyError')
    return
  }
 
  if (trimmedName === savedName.value) return
 
  isSavingName.value = true
  nameError.value = ''
  try {
    await updateUserAttributes({ userAttributes: { name: trimmedName } })
    await userStore.loadUser(true)
    savedName.value = trimmedName
    nameDraft.value = trimmedName
    toastStore.success(t('profile.nameSaved'))
  } catch (error: any) {
    toastStore.error(error?.message || t('profile.nameSaveError'))
  } finally {
    isSavingName.value = false
  }
}
 
const savedNickname = ref<string | null>(null)
const {
  nickname: nicknameDraft,
  status: nicknameStatus,
  onNicknameInput
} = useNicknameAvailability(savedNickname)
const isSavingNickname = ref(false)
 
const canSaveNickname = computed(
  () => nicknameStatus.value === 'available' && nicknameDraft.value !== savedNickname.value
)
 
async function saveNickname() {
  if (!canSaveNickname.value) return
 
  isSavingNickname.value = true
  try {
    const response = await api.put('/v1/users/me/nickname', { nickname: nicknameDraft.value })
    savedNickname.value = response.data.nickname
    nicknameDraft.value = response.data.nickname
    nicknameStatus.value = 'idle'
    toastStore.success(t('profile.nicknameSaved'))
  } catch (error: any) {
    toastStore.error(error.response?.data?.error || t('profile.nicknameSaveError'))
  } finally {
    isSavingNickname.value = false
  }
}
 
const availableLanguages = computed(() => {
  return CONTENT_LANGUAGES.filter((lang) => !preferences.value.includes(lang.code)).sort((a, b) =>
    a.nativeName.localeCompare(b.nativeName)
  )
})
 
const profileImageOwnerId = computed(() => {
  const candidate =
    userStore.user?.attributes?.sub || userStore.user?.sub || userStore.user?.userId || ''
  return typeof candidate === 'string' && candidate.trim() ? candidate : ''
})
 
onMounted(async () => {
  const currentName = userStore.user?.attributes?.name?.trim() || ''
  nameDraft.value = currentName
  savedName.value = currentName
 
  // Load preferences from API first
  isLoadingPreferences.value = true
  await initializePreferences()
  isLoadingPreferences.value = false
 
  const saved = getLanguagePreferences()
  preferences.value = [...saved]
  initialPreferences.value = [...saved]
 
  try {
    const walkthroughToken = walkthroughStore.hydrationToken()
    const response = await api.get('/v1/users/preferences')
    profilePicture.value = response.data?.profilePicture || null
    Eif (!profilePicture.value && typeof window !== 'undefined') {
      profilePicture.value = localStorage.getItem('profilePictureKey') || null
    }
    savedNickname.value = response.data?.nickname || null
    nicknameDraft.value = savedNickname.value || ''
    dmPolicy.value = response.data?.dmPolicy || 'everyone'
    walkthroughStore.hydrate(response.data?.walkthrough, walkthroughToken)
  } catch (error) {
    console.warn('Failed to load profile picture preference:', error)
    if (typeof window !== 'undefined') {
      profilePicture.value = localStorage.getItem('profilePictureKey') || null
    }
  }
})
 
async function updateProfilePicture(value: string | string[] | null) {
  const normalizedValue = typeof value === 'string' ? value : null
  profilePicture.value = normalizedValue
 
  isSavingProfilePicture.value = true
  try {
    // Keep languagePreferences for backward compatibility with currently deployed API.
    const response = await api.put('/v1/users/preferences', {
      languagePreferences: preferences.value,
      profilePicture: normalizedValue
    })
 
    const persistedProfilePicture =
      typeof response.data?.profilePicture === 'string' || response.data?.profilePicture === null
        ? response.data.profilePicture
        : normalizedValue
 
    if (persistedProfilePicture !== normalizedValue) {
      console.warn('[profile-picture] API persisted a different key than requested', {
        requested: normalizedValue,
        persisted: persistedProfilePicture
      })
    }
 
    profilePicture.value = persistedProfilePicture
 
    Eif (typeof window !== 'undefined') {
      if (persistedProfilePicture) {
        localStorage.setItem('profilePictureKey', persistedProfilePicture)
      } else {
        localStorage.removeItem('profilePictureKey')
      }
    }
 
    console.warn('[profile-picture] saved', {
      requested: normalizedValue,
      persisted: persistedProfilePicture
    })
 
    toastStore.success(
      profilePicture.value !== null
        ? t('profile.profilePictureSaved')
        : t('profile.profilePictureRemoved')
    )
  } catch (error: any) {
    console.error('Failed to save profile picture preference:', error)
    toastStore.error(error.response?.data?.error || t('profile.profilePictureSaveError'))
  } finally {
    isSavingProfilePicture.value = false
  }
}
 
async function addLanguagePreference(langCode: string) {
  if (!preferences.value.includes(langCode)) {
    preferences.value.push(langCode)
    await autoSavePreferences()
  }
}
 
async function removeLanguagePreference(index: number) {
  preferences.value.splice(index, 1)
  await autoSavePreferences()
}
 
function handleDragStart(event: DragEvent, langCode: string, source: 'available' | 'preferred') {
  draggedItem.value = { code: langCode, source }
  if (event.dataTransfer) {
    event.dataTransfer.effectAllowed = 'move'
    event.dataTransfer.setData('text/plain', langCode)
  }
}
 
async function handleDragOver(_event: DragEvent, targetIndex: number) {
  if (!draggedItem.value || draggedItem.value.source !== 'preferred') return
 
  const currentIndex = preferences.value.indexOf(draggedItem.value.code)
  if (currentIndex === -1 || currentIndex === targetIndex) return
 
  // Reorder array
  const newPrefs = [...preferences.value]
  newPrefs.splice(currentIndex, 1)
  newPrefs.splice(targetIndex, 0, draggedItem.value.code)
  preferences.value = newPrefs
  reorderingOccurred.value = true
}
 
async function handleDrop(event: DragEvent) {
  event.preventDefault()
 
  if (!draggedItem.value) return
 
  let shouldSave = false
 
  if (draggedItem.value.source === 'available') {
    // Add to preferences if not already there
    if (!preferences.value.includes(draggedItem.value.code)) {
      preferences.value.push(draggedItem.value.code)
      shouldSave = true
    }
  } else Iif (reorderingOccurred.value) {
    // Save if reordering occurred in preferred list
    shouldSave = true
  }
 
  draggedItem.value = null
  reorderingOccurred.value = false
 
  if (shouldSave) {
    await autoSavePreferences()
  }
}
 
async function autoSavePreferences() {
  try {
    await setLanguagePreferences(preferences.value)
    initialPreferences.value = [...preferences.value]
 
    toastStore.success(t('profile.preferencesSaved'))
  } catch (error) {
    console.error('Failed to save preferences:', error)
    toastStore.error(t('profile.preferencesSaveError'))
  }
}
 
async function doDeleteAccount() {
  isDeletingAccount.value = true
  deleteAccountError.value = ''
  try {
    await userStore.deleteAccount()
    await router.push('/login')
  } catch (err: any) {
    console.error('[doDeleteAccount] error:', err)
    deleteAccountError.value =
      err.response?.data?.error || err.message || t('profile.deleteAccountError')
    toastStore.error(deleteAccountError.value)
    confirmDeleteAccount.open = false
  } finally {
    isDeletingAccount.value = false
  }
}
 
function updateThemePreference(preference: ThemePreference) {
  setThemePreference(preference)
}
</script>
 
<style scoped>
.profile-page {
  --profile-language-list-bg: #f8f9fa;
  --profile-preferences-bg: #f9fff1;
  --profile-preferences-border: #aafc74;
  --profile-preferred-border: #a6fc74;
  --profile-language-item-hover: #f0f9e8;
}
 
:global([data-bs-theme='dark'] .profile-page) {
  --profile-language-list-bg: #2b3138;
  --profile-preferences-bg: #3e4838;
  --profile-preferences-border: #bdfc74;
  --profile-preferred-border: #a6e27e;
  --profile-language-item-hover: #33452b;
}
 
.language-list-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid var(--bw-border);
  border-radius: 0.375rem;
  padding: 0.5rem;
  background-color: var(--profile-language-list-bg);
}
 
.preferences-container {
  background-color: var(--profile-preferences-bg);
  border-color: var(--profile-preferences-border);
}
 
.language-item {
  display: flex;
  align-items: center;
  padding: 0.5rem;
  background: var(--bw-surface);
  border: 1px solid var(--bw-border);
  border-radius: 0.375rem;
  cursor: move;
  transition: all 0.2s;
}
 
.language-item.available {
  cursor: pointer;
}
 
.language-item.available:hover {
  border-color: #689909;
  background-color: var(--profile-language-item-hover);
  transform: translateX(4px);
}
 
.language-item.preferred {
  border-color: var(--profile-preferred-border);
}
 
.language-item.preferred:hover {
  border-color: #689909;
  box-shadow: 0 2px 4px rgba(104, 153, 9, 0.1);
}
 
.name-group {
  display: flex;
  align-items: stretch;
  width: 100%;
}
 
.name-group-input,
.name-group-save {
  height: 31px;
}
 
.name-group-input {
  border-radius: 0.25rem 0 0 0.25rem;
}
 
.name-group-save {
  border-radius: 0 0.25rem 0.25rem 0;
  margin-bottom: 0;
  white-space: nowrap;
}
 
.nickname-group {
  display: flex;
  align-items: stretch;
  width: 100%;
}
 
.nickname-group-prefix,
.nickname-group-input,
.nickname-group-save {
  height: 31px;
}
 
.nickname-group-prefix {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 31px;
  flex-shrink: 0;
  border: 1px solid var(--bw-border);
  border-right: 0;
  border-radius: 0.25rem 0 0 0.25rem;
  background: var(--bw-surface-muted);
  color: var(--bw-text-muted);
  font-size: 0.875rem;
}
 
.nickname-group-input {
  border-radius: 0;
  min-width: 0;
}
 
.nickname-group-input:focus {
  z-index: 2;
}
 
.nickname-group-save {
  border-radius: 0 0.25rem 0.25rem 0;
  margin-bottom: 0;
  white-space: nowrap;
}
</style>