<script setup>
definePageMeta({
  layout: 'admin'
})

const saving = ref(false)
const errorMessage = ref('')
const postForm = ref(null)
const toast = ref(null)
let toastTimer = null

/**
 * 저장 상태 토스트 표시
 * @param {'success'|'error'|'info'} type - 토스트 타입
 * @param {string} message - 표시 메시지
 * @returns {void}
 */
const showToast = (type, message) => {
  window.clearTimeout(toastTimer)
  toast.value = { type, message }
  toastTimer = window.setTimeout(() => {
    toast.value = null
  }, 3200)
}

/**
 * 새 게시물 미리보기
 * @param {Object} payload - 게시물 입력값
 * @returns {void}
 */
const previewPost = (payload) => {
  localStorage.setItem('SORI_ADMIN_POST_PREVIEW', JSON.stringify({
    ...payload,
    previewedAt: new Date().toISOString()
  }))
  window.open('/admin/posts/preview', '_blank', 'noopener,noreferrer')
}

/**
 * 새 게시물 저장
 * @param {Object} payload - 게시물 입력값
 * @returns {Promise<void>} 저장 결과
 */
const savePost = async (payload) => {
  saving.value = true
  errorMessage.value = ''
  showToast('info', '글을 저장하는 중입니다.')

  try {
    const post = await $fetch('/admin/api/posts', {
      method: 'POST',
      body: payload
    })

    postForm.value?.clearAutosave()
    sessionStorage.setItem('SORI_ADMIN_POST_TOAST', JSON.stringify({
      type: 'success',
      message: '글이 저장되었습니다.'
    }))
    await navigateTo(`/admin/posts/${post.id}`)
  } catch (error) {
    errorMessage.value = error?.data?.message || '글을 저장하지 못했습니다.'
    showToast('error', errorMessage.value)
  } finally {
    saving.value = false
  }
}

onBeforeUnmount(() => {
  window.clearTimeout(toastTimer)
})
</script>

<template>
  <section class="admin-post-editor bg-white">
    <p v-if="errorMessage" class="admin-post-editor__error mx-6 mt-6 rounded border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
      {{ errorMessage }}
    </p>
    <AdminPostForm ref="postForm" submit-label="글 저장" :saving="saving" @submit="savePost" @preview="previewPost" />
    <div
      v-if="toast"
      class="admin-post-editor__toast fixed right-5 top-5 z-50 rounded border px-4 py-3 text-sm font-semibold shadow-lg"
      :class="{
        'border-green-200 bg-green-50 text-green-800': toast.type === 'success',
        'border-red-200 bg-red-50 text-red-800': toast.type === 'error',
        'border-line bg-white text-ink': toast.type === 'info'
      }"
      role="status"
    >
      {{ toast.message }}
    </div>
  </section>
</template>
