<script setup>
import { computed, onMounted, onBeforeUnmount, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { homePath, loginPath } from '../lib/paths'
import { toApiUrl } from '../lib/runtime'
import { useToast } from '../composables/useToast'

const router = useRouter()
const auth = useAuthStore()
const toast = useToast()

const error = ref('')
const saving = ref(false)
const nickname = ref('')
const previewUrl = ref('')
const avatarFile = ref(null)
const removeAvatar = ref(false)
const fileInput = ref(null)

watch(error, (message) => {
  if (!message) return
  toast.error(message)
  error.value = ''
})

const avatarUrl = computed(() => {
  if (previewUrl.value) return previewUrl.value
  if (removeAvatar.value) return ''
  if (!auth.user?.avatarSrc) return ''
  return toApiUrl(auth.user.avatarSrc)
})

const authReady = computed(() => auth.hydrated)

const displayInitial = computed(() => {
  const email = auth.user?.email || 'U'
  return email[0].toUpperCase()
})

onMounted(async () => {
  if (!auth.hydrated) await auth.refresh()
  if (!auth.user) {
    router.replace(loginPath())
    return
  }
  nickname.value = auth.user?.nickname || ''
  removeAvatar.value = false
})

onBeforeUnmount(() => {
  if (previewUrl.value) URL.revokeObjectURL(previewUrl.value)
})

function openAvatarPicker() {
  fileInput.value?.click()
}

function onAvatarChange(e) {
  const file = e.target.files && e.target.files[0]
  if (!file) return

  error.value = ''
  removeAvatar.value = false
  avatarFile.value = file
  if (previewUrl.value) URL.revokeObjectURL(previewUrl.value)
  previewUrl.value = URL.createObjectURL(file)
}

function clearAvatar() {
  error.value = ''
  avatarFile.value = null
  removeAvatar.value = true
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value)
    previewUrl.value = ''
  }
  if (fileInput.value) fileInput.value.value = ''
}

async function saveProfile() {
  error.value = ''
  saving.value = true
  try {
    const fd = new FormData()
    fd.append('nickname', nickname.value)
    if (avatarFile.value) fd.append('avatar', avatarFile.value)
    if (removeAvatar.value) fd.append('removeAvatar', '1')

    const res = await fetch(toApiUrl('/api/auth/profile'), {
      method: 'POST',
      credentials: 'include',
      body: fd,
    })
    if (!res.ok) throw new Error('upload_failed')
    const data = await res.json()
    auth.user = data.user
    avatarFile.value = null
    removeAvatar.value = false
    if (previewUrl.value) {
      URL.revokeObjectURL(previewUrl.value)
      previewUrl.value = ''
    }
    if (fileInput.value) fileInput.value.value = ''
    toast.success('프로필을 저장했어요.')
  } catch (e2) {
    error.value = '프로필 저장에 실패했어요.'
  } finally {
    saving.value = false
  }
}

async function logout() {
  await auth.logout()
  toast.success('로그아웃했어요.')
  router.push(homePath())
}
</script>

<template>
  <section class="pageWrap">
    <header class="pageHead">
      <div class="pageHead__main">
        <div class="pageHead__eyebrow">Account</div>
        <h2 class="pageHead__title">설정</h2>
        <div class="pageHead__desc">계정 정보를 간결하게 정리하고, 프로필 이미지를 클릭해서 바로 변경할 수 있어요.</div>
      </div>
    </header>

    <section v-if="!authReady" class="settingsScreen settingsScreen--loading">
      <div class="settingsLoading">계정 정보를 불러오고 있어요.</div>
    </section>

    <section v-else-if="auth.user" class="settingsScreen">
      <div class="settingsIdentity">
        <div class="avatarButtonWrap">
          <button class="avatarButton" type="button" @click="openAvatarPicker">
            <img v-if="avatarUrl" :src="avatarUrl" class="avatarButton__image" alt="avatar" draggable="false" />
            <div v-else class="avatarButton__fallback">{{ displayInitial }}</div>
            <div class="avatarButton__overlay">
              <span>{{ avatarUrl ? '이미지 변경' : '이미지 추가' }}</span>
            </div>
          </button>
          <button
            v-if="avatarUrl || previewUrl"
            class="avatarButton__remove"
            type="button"
            aria-label="프로필 이미지 삭제"
            @click="clearAvatar"
          >
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <path d="M6 6l12 12M18 6L6 18" />
            </svg>
          </button>
        </div>

        <div class="identityMeta">
          <div class="identityMeta__eyebrow">Profile Photo</div>
          <div class="identityMeta__title">프로필 이미지</div>
          <div class="identityMeta__desc">아바타를 클릭해서 이미지를 추가하거나 교체할 수 있습니다.</div>
        </div>

        <input ref="fileInput" class="hiddenInput" type="file" accept="image/*" :disabled="saving" @change="onAvatarChange" />
      </div>

      <div class="settingsFields">
        <label class="field">
          <span class="field__label">닉네임</span>
          <input v-model="nickname" class="field__input" maxlength="40" placeholder="작성자 닉네임" />
          <span class="field__hint">티어표 작성자 이름으로 표시됩니다. {{ nickname.length }}/40자</span>
        </label>

        <label class="field">
          <span class="field__label">이메일</span>
          <input :value="auth.user.email" class="field__input field__input--readonly" readonly />
          <span class="field__hint">현재 로그인에 사용 중인 계정입니다.</span>
        </label>

        <div v-if="auth.user.isAdmin" class="roleBadge">Administrator</div>
      </div>

      <div class="settingsActions">
        <button class="primaryAction" :disabled="saving" @click="saveProfile">{{ saving ? '저장 중...' : '변경사항 저장' }}</button>
        <button class="secondaryAction" type="button" @click="logout">로그아웃</button>
      </div>
    </section>
  </section>
</template>

<style scoped>
.settingsScreen {
  display: grid;
  gap: 32px;
  max-width: 620px;
  padding-top: 4px;
}

.settingsScreen--loading {
  min-height: 240px;
  align-items: center;
}

.settingsLoading {
  color: var(--theme-text-muted);
  font-size: 15px;
}

.settingsIdentity {
  display: grid;
  grid-template-columns: 120px minmax(0, 1fr);
  gap: 24px;
  align-items: center;
}

.avatarButtonWrap {
  position: relative;
  width: 120px;
  height: 120px;
}

.avatarButton {
  position: relative;
  width: 120px;
  height: 120px;
  border: 1px solid var(--theme-border-strong);
  border-radius: 9999px;
  background: var(--theme-pill-bg);
  color: var(--theme-text);
  overflow: hidden;
  cursor: pointer;
  display: grid;
  place-items: center;
  box-shadow: var(--theme-card-shadow);
}

.avatarButton__image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatarButton__fallback {
  font-size: 34px;
  font-weight: 900;
  color: var(--theme-text);
}

.avatarButton__overlay {
  position: absolute;
  inset: auto 0 0 0;
  padding: 12px 10px;
  background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.72));
  font-size: 12px;
  font-weight: 700;
  color: var(--theme-text);
}

.avatarButton__remove {
  position: absolute;
  top: 0;
  right: 0;
  width: 30px;
  height: 30px;
  border: 0;
  border-radius: 999px;
  background: var(--theme-shell-bg);
  color: var(--theme-text);
  display: grid;
  place-items: center;
  cursor: pointer;
  z-index: 2;
  box-shadow: 0 8px 18px rgba(0, 0, 0, 0.28);
  backdrop-filter: blur(10px);
}

.avatarButton__remove svg {
  width: 14px;
  height: 14px;
  stroke: currentColor;
  stroke-width: 2.1;
  fill: none;
  stroke-linecap: round;
}

.avatarButton__remove:hover {
  background: rgba(190, 24, 24, 0.88);
  color: var(--theme-accent-text);
}

.identityMeta {
  display: grid;
  gap: 6px;
}

.identityMeta__eyebrow {
  font-size: 11px;
  letter-spacing: 0.12em;
  text-transform: uppercase;
  color: var(--theme-text-soft);
}

.identityMeta__title {
  font-size: 22px;
  font-weight: 700;
  letter-spacing: -0.03em;
}

.identityMeta__desc {
  color: var(--theme-text-muted);
  line-height: 1.6;
}


.hiddenInput {
  display: none;
}

.settingsFields {
  display: grid;
  gap: 20px;
}

.field {
  display: grid;
  gap: 8px;
}

.field__label {
  font-size: 13px;
  color: var(--theme-text-muted);
}

.field__input {
  width: 100%;
  padding: 14px 0;
  border: 0;
  border-bottom: 1px solid var(--theme-border-strong);
  background: transparent;
  color: var(--theme-text);
  outline: none;
  font-size: 18px;
  letter-spacing: -0.02em;
}

.field__input:focus {
  border-bottom-color: rgba(96, 165, 250, 0.9);
}

.field__input--readonly {
  color: var(--theme-text-muted);
}

.field__hint {
  font-size: 12px;
  color: var(--theme-text-soft);
}

.roleBadge {
  width: fit-content;
  padding: 6px 10px;
  border-radius: 999px;
  border: 1px solid rgba(96, 165, 250, 0.28);
  background: rgba(96, 165, 250, 0.1);
  color: var(--theme-text);
  font-size: 12px;
  font-weight: 700;
}

.settingsActions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  padding-top: 8px;
}

.primaryAction,
.secondaryAction {
  padding: 12px 18px;
  border-radius: 999px;
  font-weight: 700;
  cursor: pointer;
}

.primaryAction {
  border: 1px solid rgba(76, 133, 245, 0.96);
  background: var(--theme-accent-bg);
  color: var(--theme-accent-text);
}

.secondaryAction {
  border: 1px solid var(--theme-border-strong);
  background: var(--theme-surface-soft);
  color: var(--theme-text);
}

@media (max-width: 720px) {
  .settingsIdentity {
    grid-template-columns: 1fr;
  }

  .avatarButtonWrap {
    width: 108px;
    height: 108px;
  }

  .avatarButton {
    width: 108px;
    height: 108px;
  }
}
</style>
