<script setup>
import { computed, onMounted, onBeforeUnmount, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { api } from '../lib/api'
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 passwordSaving = ref(false)
const nickname = ref('')
const nicknameError = ref('')
const previewUrl = ref('')
const avatarFile = ref(null)
const removeAvatar = ref(false)
const fileInput = ref(null)
const currentPassword = ref('')
const nextPassword = ref('')
const nextPasswordConfirm = ref('')
const currentPasswordError = ref('')
const nextPasswordError = ref('')

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 clearProfileFieldErrors() {
  nicknameError.value = ''
}

function clearPasswordFieldErrors() {
  currentPasswordError.value = ''
  nextPasswordError.value = ''
}

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 = ''
  clearProfileFieldErrors()

  if (nickname.value.trim().length < 2) {
    nicknameError.value = '닉네임은 2자 이상 입력해주세요.'
    error.value = '닉네임을 확인해주세요.'
    return
  }

  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,
    })
    const data = await res.json()
    if (!res.ok) {
      const requestError = new Error('profile_update_failed')
      requestError.data = data
      requestError.status = res.status
      throw requestError
    }
    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) {
    const code = e2?.data?.error
    if (code === 'nickname_taken') {
      nicknameError.value = '이미 사용 중인 닉네임입니다.'
      error.value = '닉네임이 이미 사용 중이에요.'
    } else if (code === 'nickname_reserved') {
      nicknameError.value = '운영자/관리자처럼 혼동될 수 있는 닉네임은 사용할 수 없어요.'
      error.value = '사용할 수 없는 닉네임이에요.'
    } else {
      error.value = '프로필 저장에 실패했어요.'
    }
  } finally {
    saving.value = false
  }
}

async function savePassword() {
  error.value = ''
  clearPasswordFieldErrors()

  if (nextPassword.value.length < 6) {
    nextPasswordError.value = '새 비밀번호는 6자 이상 입력해주세요.'
    error.value = '새 비밀번호를 확인해주세요.'
    return
  }

  if (nextPassword.value !== nextPasswordConfirm.value) {
    nextPasswordError.value = '비밀번호 확인이 일치하지 않아요.'
    error.value = '비밀번호 확인이 일치하지 않아요.'
    return
  }

  passwordSaving.value = true
  try {
    const data = await api.changePassword({
      currentPassword: currentPassword.value,
      nextPassword: nextPassword.value,
    })
    auth.user = data.user
    currentPassword.value = ''
    nextPassword.value = ''
    nextPasswordConfirm.value = ''
    toast.success('비밀번호를 변경했어요.')
  } catch (e2) {
    if (e2?.data?.error === 'invalid_current_password') {
      currentPasswordError.value = '현재 비밀번호가 일치하지 않아요.'
      error.value = '현재 비밀번호가 일치하지 않아요.'
    } else {
      error.value = '비밀번호 변경에 실패했어요.'
    }
  } finally {
    passwordSaving.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="settingsGrid">
        <article class="settingsPanel">
          <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 v-if="nicknameError" class="field__error">{{ nicknameError }}</span>
              <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>
        </article>

        <article class="settingsPanel">
          <div class="identityMeta__eyebrow">Password</div>
          <div class="identityMeta__title">비밀번호 변경</div>
          <div class="identityMeta__desc">현재 비밀번호를 확인한 뒤 새 비밀번호로 바꿀 수 있어요.</div>

          <div class="settingsFields settingsFields--password">
            <label class="field">
              <span class="field__label">현재 비밀번호</span>
              <input
                v-model="currentPassword"
                class="field__input"
                type="password"
                autocomplete="current-password"
                maxlength="120"
                placeholder="현재 비밀번호"
              />
              <span v-if="currentPasswordError" class="field__error">{{ currentPasswordError }}</span>
            </label>

            <label class="field">
              <span class="field__label">새 비밀번호</span>
              <input
                v-model="nextPassword"
                class="field__input"
                type="password"
                autocomplete="new-password"
                maxlength="120"
                placeholder="새 비밀번호"
              />
              <span v-if="nextPasswordError" class="field__error">{{ nextPasswordError }}</span>
              <span class="field__hint">6~120자 입력 가능 · {{ nextPassword.length }}/120자</span>
            </label>

            <label class="field">
              <span class="field__label">새 비밀번호 확인</span>
              <input
                v-model="nextPasswordConfirm"
                class="field__input"
                type="password"
                autocomplete="new-password"
                maxlength="120"
                placeholder="새 비밀번호 확인"
              />
            </label>
          </div>

          <div class="settingsActions">
            <button class="primaryAction" type="button" :disabled="passwordSaving" @click="savePassword">
              {{ passwordSaving ? '변경 중...' : '비밀번호 변경' }}
            </button>
          </div>
        </article>
      </div>
    </section>
  </section>
</template>

<style scoped>
.settingsScreen {
  display: grid;
  gap: 24px;
  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;
}

.settingsGrid {
  display: grid;
  grid-template-columns: minmax(360px, 1fr) minmax(360px, 1fr);
  gap: 24px;
  align-items: start;
}

.settingsPanel {
  min-width: 0;
  padding: 28px;
  border: 1px solid var(--theme-border);
  border-radius: 28px;
  background: var(--theme-surface);
  box-shadow: var(--theme-card-shadow);
}

.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);
}

.field__error {
  font-size: 12px;
  color: #ff7b7b;
  font-weight: 700;
}

.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;
}

.settingsFields--password {
  padding-top: 24px;
}

.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) {
  .settingsGrid {
    grid-template-columns: minmax(0, 1fr);
  }

  .settingsPanel {
    padding: 22px;
    border-radius: 24px;
  }

  .settingsIdentity {
    grid-template-columns: 1fr;
  }

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

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