<script setup>
import { computed, onMounted, ref } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { authApi } from '@/api/authApi'
import { useDialog } from '@/composables/dialog'
import { avatarSrc, avatarInitial, fileToAvatarDataUrl } from '@/utils/avatar'

const auth = useAuthStore()
const router = useRouter()
const dialog = useDialog()

// 포인트(게시판 작성으로 수시 변동) — 진입 시 최신값 조회
const points = ref(auth.user?.points ?? 0)
onMounted(async () => {
  try {
    const res = await authApi.points()
    points.value = res.points ?? 0
    await auth.applyUser({ points: points.value })
  } catch {
    // 조회 실패 시 캐시값 유지
  }
})

const u = computed(() => auth.user || {})
const roleLabel = computed(() => (u.value.role === 'ADMIN' ? '관리자' : '일반회원'))
const isPremium = computed(() => auth.isPremium)
const planLabel = computed(() => (isPremium.value ? '유료 멤버십' : '무료'))

// 아바타: 사용자 지정 > 구글 > 이니셜
const avatar = computed(() => avatarSrc(u.value))
const initial = computed(() => avatarInitial(u.value))
const hasCustom = computed(() => !!u.value.profileImage)
const hasGoogle = computed(() => !!u.value.googlePicture)

const fileInput = ref(null)
const savingImage = ref(false)
const imgError = ref('')

function pickImage() {
  imgError.value = ''
  fileInput.value?.click()
}

async function onImageFile(e) {
  const file = e.target.files?.[0]
  e.target.value = '' // 같은 파일 다시 선택 가능하도록 초기화
  if (!file) return
  savingImage.value = true
  imgError.value = ''
  try {
    const dataUrl = await fileToAvatarDataUrl(file)
    const updated = await authApi.updateProfileImage(dataUrl)
    await auth.applyUser(updated)
  } catch (err) {
    imgError.value = err.response?.data?.message || '사진 변경에 실패했습니다.'
  } finally {
    savingImage.value = false
  }
}

async function removePhoto() {
  const msg = hasGoogle.value
    ? '등록한 사진을 삭제할까요?\n구글 계정 사진으로 표시됩니다.'
    : '등록한 사진을 삭제할까요?'
  if (!(await dialog.confirm(msg, { title: '사진 삭제', danger: true }))) return
  savingImage.value = true
  imgError.value = ''
  try {
    const updated = await authApi.updateProfileImage(null)
    await auth.applyUser(updated)
  } catch (err) {
    imgError.value = err.response?.data?.message || '사진 삭제에 실패했습니다.'
  } finally {
    savingImage.value = false
  }
}

function goEdit() {
  router.push('/settings/account/edit')
}
</script>

<template>
  <div class="account-info">

    <!-- 프로필 사진 -->
    <div class="avatar-block">
      <button type="button" class="avatar-btn" :disabled="savingImage" @click="pickImage" aria-label="프로필 사진 변경">
        <img v-if="avatar" :src="avatar" class="avatar-img" alt="프로필 사진" referrerpolicy="no-referrer" />
        <span v-else class="avatar-fallback">{{ initial }}</span>
        <span class="avatar-cam" aria-hidden="true">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z" />
            <circle cx="12" cy="13" r="4" />
          </svg>
        </span>
      </button>
      <div class="avatar-actions">
        <button type="button" class="link-btn" :disabled="savingImage" @click="pickImage">
          {{ savingImage ? '처리 중…' : '사진 변경' }}
        </button>
        <button v-if="hasCustom" type="button" class="link-btn muted" :disabled="savingImage" @click="removePhoto">
          삭제
        </button>
      </div>
      <p v-if="imgError" class="avatar-err">{{ imgError }}</p>
      <input ref="fileInput" type="file" accept="image/*" class="hidden-file" @change="onImageFile" />
    </div>

    <section class="card">
      <div class="row">
        <span class="k">이름</span>
        <span class="v">{{ u.name || '-' }}</span>
      </div>
      <div class="row">
        <span class="k">이메일</span>
        <span class="v">{{ u.email || '-' }}</span>
      </div>
      <div class="row">
        <span class="k">권한</span>
        <span class="v">{{ roleLabel }}</span>
      </div>
      <div class="row">
        <span class="k">멤버십</span>
        <span class="v">
          <span :class="{ premium: isPremium }">{{ planLabel }}</span>
          <RouterLink v-if="!isPremium" to="/upgrade" class="up-link">업그레이드 →</RouterLink>
        </span>
      </div>
      <div class="row">
        <span class="k">포인트</span>
        <span class="v"><span class="points">{{ points.toLocaleString('ko-KR') }} P</span></span>
      </div>
    </section>

    <button type="button" class="primary-btn" @click="goEdit">이름 변경</button>
  </div>
</template>

<style scoped>
.account-info {
  max-width: 560px;
  margin: 0 auto;
}
.back {
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  margin-bottom: 0.75rem;
  padding: 0.3rem 0.1rem;
  border: 0;
  background: transparent;
  color: var(--color-text);
  opacity: 0.75;
  cursor: pointer;
  font-size: 0.9rem;
}
.back:hover {
  opacity: 1;
}
.back svg {
  width: 18px;
  height: 18px;
}
.page-title {
  font-size: 1.4rem;
  margin-bottom: 1rem;
}
.card {
  background: var(--color-background-soft);
  border: 1px solid var(--color-border);
  border-radius: 10px;
  overflow: hidden;
}
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 0.95rem 1.1rem;
  border-bottom: 1px solid var(--color-border);
}
.row:last-child {
  border-bottom: 0;
}
.k {
  font-size: 0.88rem;
  opacity: 0.65;
}
.v {
  font-size: 0.95rem;
  font-weight: 600;
  text-align: right;
  word-break: break-all;
}
.v .premium {
  color: #b8860b;
}
.points {
  color: hsla(160, 100%, 37%, 1);
  font-weight: 700;
}
.up-link {
  margin-left: 0.5rem;
  font-size: 0.82rem;
  font-weight: 600;
  color: hsla(160, 100%, 37%, 1);
}
.avatar-block {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.6rem;
  margin-bottom: 1.25rem;
}
.avatar-btn {
  position: relative;
  width: 96px;
  height: 96px;
  border-radius: 50%;
  border: 1px solid var(--color-border);
  background: var(--color-background-soft);
  padding: 0;
  cursor: pointer;
  overflow: visible;
}
.avatar-btn:disabled {
  opacity: 0.6;
  cursor: default;
}
.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  display: block;
}
.avatar-fallback {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  font-size: 2.2rem;
  font-weight: 700;
  color: #fff;
  background: hsla(160, 100%, 37%, 1);
}
.avatar-cam {
  position: absolute;
  right: -2px;
  bottom: -2px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: hsla(160, 100%, 37%, 1);
  border: 2px solid var(--color-background);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}
.avatar-cam svg {
  width: 16px;
  height: 16px;
}
.avatar-actions {
  display: flex;
  gap: 0.85rem;
  align-items: center;
}
.link-btn {
  border: 0;
  background: transparent;
  color: hsla(160, 100%, 37%, 1);
  font-size: 0.9rem;
  font-weight: 600;
  cursor: pointer;
  padding: 0.2rem 0.1rem;
}
.link-btn.muted {
  color: var(--color-text);
  opacity: 0.6;
}
.link-btn:disabled {
  opacity: 0.5;
  cursor: default;
}
.avatar-err {
  font-size: 0.82rem;
  color: #c0392b;
  margin: 0;
}
.hidden-file {
  display: none;
}
.primary-btn {
  width: 100%;
  margin-top: 1.25rem;
  padding: 0.8rem 1rem;
  border: 1px solid hsla(160, 100%, 37%, 1);
  border-radius: 8px;
  background: hsla(160, 100%, 37%, 1);
  color: #fff;
  font-size: 0.98rem;
  font-weight: 600;
  cursor: pointer;
}
.primary-btn:hover {
  background: hsla(160, 100%, 32%, 1);
}
.hint {
  margin-top: 1.25rem;
  font-size: 0.85rem;
  opacity: 0.6;
  text-align: center;
}
</style>
