<script setup>
const props = defineProps({
  initialPost: {
    type: Object,
    default: () => ({})
  },
  submitLabel: {
    type: String,
    default: '저장'
  },
  saving: {
    type: Boolean,
    default: false
  },
  canViewPost: {
    type: Boolean,
    default: false
  },
  publicUrl: {
    type: String,
    default: ''
  },
  deleting: {
    type: Boolean,
    default: false
  },
  showDelete: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['submit', 'preview', 'delete'])

const autosaveStoragePrefix = 'SORI_ADMIN_POST_AUTOSAVE'
const slugTouched = ref(Boolean(props.initialPost.slug))
const blockEditor = ref(null)
const mediaItems = ref([])
const isMediaPickerOpen = ref(false)
const mediaPickerTarget = ref('featuredImage')
const isLoadingMedia = ref(false)
const isUploadingFeaturedImage = ref(false)
const autosaveTimer = ref(null)
const autosaveNotice = ref(null)
const autosaveStatus = ref('')
const isRestoringAutosave = ref(false)
const isSettingsOpen = ref(true)
const tagInput = ref('')
const isTagInputComposing = ref(false)
const activeMediaPickerTab = ref('upload')
const selectedMediaPickerUrl = ref('')

/**
 * ISO 날짜를 datetime-local 입력값으로 변환
 * @param {string} value - ISO 날짜 문자열
 * @returns {string} datetime-local 입력값
 */
function toDateTimeLocalValue(value) {
  if (!value) {
    return ''
  }

  const date = new Date(value)

  if (Number.isNaN(date.getTime())) {
    return ''
  }

  const offsetDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000)

  return offsetDate.toISOString().slice(0, 16)
}

/**
 * datetime-local 입력값을 ISO 문자열로 변환
 * @param {string} value - datetime-local 입력값
 * @returns {string | null} ISO 날짜 문자열
 */
function toIsoDateTime(value) {
  if (!value) {
    return null
  }

  const date = new Date(value)

  if (Number.isNaN(date.getTime())) {
    return null
  }

  return date.toISOString()
}

const form = reactive({
  title: props.initialPost.title || '',
  slug: props.initialPost.slug || '',
  excerpt: props.initialPost.excerpt || '',
  content: props.initialPost.content || '',
  featuredImage: props.initialPost.featuredImage || '',
  seoTitle: props.initialPost.seoTitle || '',
  seoDescription: props.initialPost.seoDescription || '',
  noindex: Boolean(props.initialPost.noindex),
  status: props.initialPost.status || 'draft',
  publishedAt: toDateTimeLocalValue(props.initialPost.publishedAt),
  tagsText: props.initialPost.tags?.join(', ') || ''
})

const autosaveKey = computed(() => `${autosaveStoragePrefix}:${props.initialPost.id || 'new'}`)
const postUrlLabel = computed(() => form.slug || toSlug(form.title) || '')
const postUrlHint = computed(() => props.publicUrl || (postUrlLabel.value ? `/post/${postUrlLabel.value}/` : '/post/'))

/**
 * 한글 음절 1자를 영문 표기로 변환
 * @param {string} char - 변환할 문자
 * @returns {string} 영문 표기
 */
const romanizeHangulSyllable = (char) => {
  const syllableCode = char.charCodeAt(0)
  const hangulBase = 0xac00
  const hangulLast = 0xd7a3
  if (syllableCode < hangulBase || syllableCode > hangulLast) {
    return char
  }

  const choseong = ['g', 'kk', 'n', 'd', 'tt', 'r', 'm', 'b', 'pp', 's', 'ss', '', 'j', 'jj', 'ch', 'k', 't', 'p', 'h']
  const jungseong = ['a', 'ae', 'ya', 'yae', 'eo', 'e', 'yeo', 'ye', 'o', 'wa', 'wae', 'oe', 'yo', 'u', 'wo', 'we', 'wi', 'yu', 'eu', 'ui', 'i']
  const jongseong = ['', 'k', 'k', 'ks', 'n', 'nj', 'nh', 't', 'l', 'lk', 'lm', 'lb', 'ls', 'lt', 'lp', 'lh', 'm', 'p', 'ps', 't', 't', 'ng', 't', 't', 'k', 't', 'p', 'h']

  const offset = syllableCode - hangulBase
  const choseongIndex = Math.floor(offset / 588)
  const jungseongIndex = Math.floor((offset % 588) / 28)
  const jongseongIndex = offset % 28

  return `${choseong[choseongIndex]}${jungseong[jungseongIndex]}${jongseong[jongseongIndex]}`
}

/**
 * 문자열을 URL 슬러그로 변환
 * @param {string} value - 원본 문자열
 * @returns {string} 슬러그
 */
const toSlug = (value) => value
  .normalize('NFC')
  .split('')
  .map((char) => romanizeHangulSyllable(char))
  .join('')
  .trim()
  .toLowerCase()
  .replace(/[^a-z0-9\s-]/g, '')
  .replace(/\s+/g, '-')
  .replace(/-+/g, '-')
  .replace(/^-|-$/g, '')

watch(() => form.title, (title) => {
  if (!slugTouched.value) {
    form.slug = toSlug(title)
  }
})

/**
 * 슬러그 직접 입력 상태 표시
 * @returns {void}
 */
const touchSlug = () => {
  slugTouched.value = true
  form.slug = toSlug(form.slug)
}

/**
 * 쉼표 구분 태그 문자열을 슬러그 배열로 변환
 * @param {string} value - 태그 입력 문자열
 * @returns {Array<string>} 태그 슬러그 목록
 */
const parseTags = (value) => [...new Set(value
  .split(',')
  .map((tag) => toSlug(tag))
  .filter(Boolean))]

const selectedTags = computed(() => parseTags(form.tagsText))

/**
 * 예약 발행 여부 확인
 * @returns {boolean} 예약 발행 여부
 */
const isScheduledPost = () => {
  const publishedAt = toIsoDateTime(form.publishedAt)

  return form.status === 'published' && Boolean(publishedAt) && new Date(publishedAt) > new Date()
}

const editorStatusLabel = computed(() => {
  if (autosaveStatus.value) {
    return autosaveStatus.value
  }

  if (form.status === 'published') {
    return isScheduledPost() ? '예약 발행' : '발행됨'
  }

  if (form.status === 'private') {
    return '비공개'
  }

  return '초안'
})

/**
 * 게시물 입력값 생성
 * @returns {Object} 게시물 입력값
 */
const createPostPayload = () => {
  const publishedAt = form.status === 'published'
    ? toIsoDateTime(form.publishedAt) || props.initialPost.publishedAt || new Date().toISOString()
    : null

  return {
    title: form.title.trim(),
    slug: toSlug(form.slug || form.title),
    excerpt: form.excerpt.trim(),
    content: form.content,
    featuredImage: form.featuredImage.trim() || null,
    seoTitle: form.seoTitle.trim(),
    seoDescription: form.seoDescription.trim(),
    canonicalUrl: '',
    noindex: form.noindex,
    ogImage: null,
    status: form.status,
    publishedAt,
    tags: selectedTags.value
  }
}

/**
 * 자동 저장 데이터 생성
 * @returns {Object} 자동 저장 데이터
 */
const createAutosavePayload = () => ({
  title: form.title,
  slug: form.slug,
  excerpt: form.excerpt,
  content: form.content,
  featuredImage: form.featuredImage,
  seoTitle: form.seoTitle,
  seoDescription: form.seoDescription,
  noindex: form.noindex,
  status: form.status,
  publishedAt: form.publishedAt,
  tagsText: form.tagsText
})

/**
 * 자동 저장 데이터가 비어 있는지 확인
 * @param {Object} payload - 자동 저장 데이터
 * @returns {boolean} 비어 있는지 여부
 */
const isEmptyAutosavePayload = (payload) => ![
  payload.title,
  payload.slug,
  payload.excerpt,
  payload.content,
  payload.featuredImage,
  payload.seoTitle,
  payload.seoDescription,
  payload.tagsText
].some((value) => String(value || '').trim())

/**
 * 자동 저장 시각 표시 문자열 반환
 * @param {number} savedAt - 저장 시각
 * @returns {string} 표시 문자열
 */
const formatAutosaveTime = (savedAt) => new Intl.DateTimeFormat('ko-KR', {
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit'
}).format(new Date(savedAt))

/**
 * 자동 저장본을 로컬 저장소에 기록
 * @returns {void}
 */
const saveAutosave = () => {
  if (!import.meta.client || isRestoringAutosave.value) {
    return
  }

  const payload = createAutosavePayload()

  if (isEmptyAutosavePayload(payload)) {
    localStorage.removeItem(autosaveKey.value)
    autosaveStatus.value = ''
    return
  }

  const savedAt = Date.now()
  localStorage.setItem(autosaveKey.value, JSON.stringify({
    savedAt,
    payload
  }))
  autosaveStatus.value = `${formatAutosaveTime(savedAt)} 자동 저장됨`
}

/**
 * 자동 저장 예약
 * @returns {void}
 */
const scheduleAutosave = () => {
  if (!import.meta.client || isRestoringAutosave.value) {
    return
  }

  window.clearTimeout(autosaveTimer.value)
  autosaveTimer.value = window.setTimeout(saveAutosave, 900)
}

/**
 * 자동 저장본을 입력 폼에 복원
 * @returns {void}
 */
const restoreAutosave = () => {
  if (!autosaveNotice.value?.payload) {
    return
  }

  isRestoringAutosave.value = true
  Object.assign(form, autosaveNotice.value.payload)
  slugTouched.value = Boolean(form.slug)
  autosaveStatus.value = `${formatAutosaveTime(autosaveNotice.value.savedAt)} 자동 저장본 복원됨`
  autosaveNotice.value = null

  nextTick(() => {
    isRestoringAutosave.value = false
    scheduleAutosave()
  })
}

/**
 * 자동 저장본을 삭제
 * @returns {void}
 */
const discardAutosave = () => {
  if (!import.meta.client) {
    return
  }

  localStorage.removeItem(autosaveKey.value)
  autosaveNotice.value = null
  autosaveStatus.value = ''
}

/**
 * 미디어 라이브러리 목록 조회
 * @returns {Promise<void>}
 */
const fetchMediaItems = async () => {
  isLoadingMedia.value = true

  try {
    mediaItems.value = await $fetch('/admin/api/media')
  } finally {
    isLoadingMedia.value = false
  }
}

/**
 * 대표 이미지 선택 창 열기
 * @returns {Promise<void>}
 */
const openMediaPicker = async (target = 'featuredImage') => {
  mediaPickerTarget.value = target
  activeMediaPickerTab.value = 'upload'
  selectedMediaPickerUrl.value = form[target] || ''
  isMediaPickerOpen.value = true
  await fetchMediaItems()
}

/**
 * 대표 이미지 선택 창 닫기
 * @returns {void}
 */
const closeMediaPicker = () => {
  isMediaPickerOpen.value = false
}

/**
 * 대표 이미지 선택 상태 변경
 * @param {Object} item - 미디어 항목
 * @returns {void}
 */
const selectPickedImage = (item) => {
  selectedMediaPickerUrl.value = item.url
}

/**
 * 선택한 대표 이미지 적용
 * @returns {void}
 */
const applyPickedImage = () => {
  if (!selectedMediaPickerUrl.value) {
    return
  }

  form[mediaPickerTarget.value] = selectedMediaPickerUrl.value
  closeMediaPicker()
}

/**
 * 대표 이미지 삭제
 * @returns {void}
 */
const removeFeaturedImage = () => {
  form.featuredImage = ''
}

/**
 * 태그 입력값을 배지 목록에 추가
 * @returns {void}
 */
const addTagFromInput = () => {
  const nextTag = toSlug(tagInput.value)

  if (!nextTag) {
    tagInput.value = ''
    return
  }

  form.tagsText = [...new Set([...selectedTags.value, nextTag])].join(', ')
  tagInput.value = ''
}

/**
 * 태그 배지 삭제
 * @param {string} tag - 삭제할 태그
 * @returns {void}
 */
const removeTag = (tag) => {
  form.tagsText = selectedTags.value.filter((item) => item !== tag).join(', ')
}

/**
 * 태그 입력 키 처리
 * @param {KeyboardEvent} event - 키보드 이벤트
 * @returns {void}
 */
const handleTagKeydown = (event) => {
  if (event.isComposing || isTagInputComposing.value || event.keyCode === 229) {
    return
  }

  if (event.key === 'Enter' || event.key === ',') {
    event.preventDefault()
    addTagFromInput()
    return
  }

  if (event.key === 'Backspace' && !tagInput.value && selectedTags.value.length) {
    event.preventDefault()
    removeTag(selectedTags.value.at(-1))
  }
}

/**
 * 대표 이미지 파일 업로드
 * @param {File} file - 업로드 파일
 * @returns {Promise<void>}
 */
const uploadFeaturedImageFile = async (file) => {
  const formData = new FormData()
  formData.append('files', file)
  isUploadingFeaturedImage.value = true

  try {
    const result = await $fetch('/admin/api/uploads', {
      method: 'POST',
      body: formData
    })
    selectedMediaPickerUrl.value = result.files?.[0]?.url || ''
    await fetchMediaItems()
    activeMediaPickerTab.value = 'library'
  } finally {
    isUploadingFeaturedImage.value = false
  }
}

/**
 * 대표 이미지 파일 입력 처리
 * @param {Event} event - 파일 입력 이벤트
 * @returns {Promise<void>}
 */
const uploadFeaturedImage = async (event) => {
  const files = event.target.files

  if (!files?.length) {
    return
  }

  try {
    await uploadFeaturedImageFile(files[0])
  } finally {
    event.target.value = ''
  }
}

/**
 * 대표 이미지 드롭 업로드
 * @param {DragEvent} event - 드롭 이벤트
 * @returns {Promise<void>}
 */
const dropFeaturedImage = async (event) => {
  const files = event.dataTransfer?.files

  if (!files?.length) {
    return
  }

  await uploadFeaturedImageFile(files[0])
}

/**
 * 제목 입력 후 본문 에디터로 이동
 * @returns {void}
 */
const focusContentEditor = () => {
  blockEditor.value?.focusFirstBlock()
}

/**
 * 게시물 입력값 제출
 * @returns {void}
 */
const submitPost = () => {
  emit('submit', createPostPayload())
}

/**
 * 게시물 미리보기 요청
 * @returns {void}
 */
const previewPost = () => {
  emit('preview', createPostPayload())
}

/**
 * 게시물 삭제 요청
 * @returns {void}
 */
const deletePost = () => {
  emit('delete')
}

/**
 * 설정 패널 표시 상태 전환
 * @returns {void}
 */
const toggleSettingsPanel = () => {
  isSettingsOpen.value = !isSettingsOpen.value
}

watch(form, scheduleAutosave, { deep: true })

onMounted(() => {
  const savedRaw = localStorage.getItem(autosaveKey.value)

  if (!savedRaw) {
    return
  }

  try {
    const saved = JSON.parse(savedRaw)

    if (saved?.payload && !isEmptyAutosavePayload(saved.payload)) {
      autosaveNotice.value = saved
      autosaveStatus.value = `${formatAutosaveTime(saved.savedAt)} 자동 저장본 있음`
    }
  } catch {
    localStorage.removeItem(autosaveKey.value)
  }
})

onBeforeUnmount(() => {
  if (import.meta.client) {
    window.clearTimeout(autosaveTimer.value)
  }
})

defineExpose({
  clearAutosave: discardAutosave
})
</script>

<template>
  <form class="admin-post-form flex h-screen min-h-screen overflow-hidden bg-white" @submit.prevent="submitPost">
    <div class="admin-post-form__workspace flex min-w-0 flex-1 flex-col bg-white">
      <header class="admin-post-form__toolbar flex h-[56px] shrink-0 items-center bg-white px-8">
        <div class="admin-post-form__toolbar-inner flex h-[34px] min-w-0 flex-1 items-center justify-between">
          <div class="admin-post-form__toolbar-left flex h-full min-w-0 items-center gap-3">
            <NuxtLink class="admin-post-form__toolbar-link inline-flex items-center gap-2 rounded px-2 py-1.5 text-sm font-medium text-[#394047] transition-colors hover:bg-[#eff1f2] hover:text-black" to="/admin/posts">
              <span class="admin-post-form__toolbar-back text-lg leading-none" aria-hidden="true">&lt;</span>
              <span>Posts</span>
            </NuxtLink>
            <span class="admin-post-form__toolbar-status truncate rounded px-2 py-1.5 text-sm text-[#8e9cac]">
              {{ editorStatusLabel }}
            </span>
          </div>
          <div class="admin-post-form__toolbar-actions flex h-full shrink-0 items-center gap-2">
            <button
              class="admin-post-form__toolbar-preview rounded px-3 py-1.5 text-sm font-bold text-[#394047] transition-colors hover:bg-[#eff1f2] hover:text-black"
              type="button"
              @click="previewPost"
            >
              미리보기
            </button>
            <button
              class="admin-post-form__toolbar-submit rounded px-3 py-1.5 text-sm font-bold text-[#2bba3c] transition-colors hover:bg-[#eaf8ec] hover:text-[#159624] disabled:opacity-50"
              type="submit"
              :disabled="saving"
            >
              {{ saving ? '저장 중' : submitLabel }}
            </button>
            <button
              class="admin-post-form__settings-toggle grid size-[34px] place-items-center rounded text-[#394047] transition-colors hover:bg-[#eff1f2] hover:text-black"
              type="button"
              :aria-pressed="isSettingsOpen"
              aria-label="게시물 설정 패널 전환"
              @click="toggleSettingsPanel"
            >
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
                <path d="M14 2.16699C14.3242 2.16699 14.4998 2.39365 14.5 2.57129V13.4287C14.5 13.606 14.3242 13.834 14 13.834H11.5V2.16699H14ZM2 2.16699H10.5V13.834H2C1.6756 13.834 1.5 13.6064 1.5 13.4287V2.57129C1.50024 2.39409 1.67607 2.16699 2 2.16699Z" stroke="currentColor" />
              </svg>
            </button>
          </div>
        </div>
      </header>

      <main class="admin-post-form__editor-scroll min-h-0 flex-1 overflow-y-auto">
        <section class="admin-post-form__content mx-auto w-full max-w-[804px] px-8 pb-16 pt-32">
        <div class="admin-post-form__feature-block mb-9">
          <figure v-if="form.featuredImage" class="admin-post-form__featured-editor group relative overflow-hidden bg-white">
            <img class="admin-post-form__featured-editor-image aspect-[16/9] w-full bg-surface object-cover" :src="form.featuredImage" alt="">
            <figcaption class="admin-post-form__featured-editor-actions pointer-events-none absolute inset-0 flex items-end justify-end gap-2 bg-gradient-to-t from-black/40 via-black/5 to-transparent p-4 opacity-0 transition-opacity duration-150 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100">
              <button class="admin-post-form__featured-change rounded bg-white/95 px-3 py-1.5 text-xs font-semibold text-[#15171a] shadow-sm transition-colors hover:bg-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white" type="button" @click="openMediaPicker('featuredImage')">
                변경
              </button>
              <button class="admin-post-form__featured-remove rounded bg-[#fff1f2]/95 px-3 py-1.5 text-xs font-semibold text-red-700 shadow-sm transition-colors hover:bg-white focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white" type="button" @click="removeFeaturedImage">
                삭제
              </button>
            </figcaption>
          </figure>
          <div v-else class="admin-post-form__feature-empty flex h-6 items-start">
            <button class="admin-post-form__feature-add inline-flex items-center gap-1.5 rounded px-2 py-1 text-sm text-[#8e9cac] transition-colors hover:bg-[#eff1f2] hover:text-[#394047]" type="button" @click="openMediaPicker('featuredImage')">
              <span aria-hidden="true">+</span>
              <span>대표 이미지 추가</span>
            </button>
          </div>
        </div>

        <input
          v-model="form.title"
          class="admin-post-form__title-input mb-2 w-full border-0 bg-transparent px-0 py-0 text-5xl font-bold leading-tight text-ink outline-none placeholder:text-[#8e9cac]"
          type="text"
          placeholder="제목"
          required
          @keydown.enter.prevent="focusContentEditor"
        >

        <div
          v-if="autosaveNotice"
          class="admin-post-form__autosave-notice flex flex-wrap items-center justify-between gap-3 rounded border border-line bg-surface px-4 py-3 text-sm"
        >
          <p class="admin-post-form__autosave-message text-muted">
            {{ formatAutosaveTime(autosaveNotice.savedAt) }}에 저장된 작성 중 내용이 있습니다.
          </p>
          <div class="admin-post-form__autosave-actions flex gap-2">
            <button class="admin-post-form__autosave-restore rounded bg-[#15171a] px-3 py-1.5 text-xs font-semibold text-white transition-colors hover:bg-black" type="button" @click="restoreAutosave">
              복원
            </button>
            <button class="admin-post-form__autosave-discard rounded border border-line bg-white px-3 py-1.5 text-xs font-semibold transition-colors hover:bg-[#eff1f2]" type="button" @click="discardAutosave">
              삭제
            </button>
          </div>
        </div>

        <div class="admin-post-form__field admin-post-form__content-editor text-sm">
          <AdminBlockEditor ref="blockEditor" v-model="form.content" />
        </div>
        </section>
      </main>
    </div>

    <aside
      class="admin-post-form__settings flex h-screen shrink-0 flex-col overflow-hidden border-[#e3e6e8] bg-white transition-[width,border-color] duration-300 ease-out"
      :class="isSettingsOpen ? 'w-[420px] border-l' : 'w-0 border-l-0'"
      :aria-hidden="!isSettingsOpen"
    >
      <div class="admin-post-form__settings-inner flex h-full w-[420px] flex-col">
        <div class="admin-post-form__settings-header flex h-[56px] shrink-0 items-center justify-between px-6">
          <h2 class="admin-post-form__settings-title text-xl font-bold text-black">
            게시물 설정
          </h2>
          <button class="admin-post-form__settings-close grid size-8 place-items-center rounded text-[#394047] transition-colors hover:bg-[#eff1f2] hover:text-black" type="button" aria-label="게시물 설정 닫기" @click="toggleSettingsPanel">
            <span aria-hidden="true">x</span>
          </button>
        </div>

        <div class="admin-post-form__settings-body grid flex-1 content-start gap-4 overflow-y-auto px-6 pb-8 pt-8">
        <div class="admin-post-form__field grid gap-1 text-sm">
          <div class="admin-post-form__post-url-header flex h-[22px] items-center justify-between">
            <span class="admin-post-form__label font-bold text-[#15171a]">Post URL</span>
            <NuxtLink
              v-if="canViewPost"
              class="admin-post-form__view-post inline-flex items-center gap-1 rounded px-3 py-1.5 text-xs text-[#8e9cac] transition-colors hover:bg-[#eff1f2] hover:text-[#394047]"
              :to="publicUrl"
              target="_blank"
            >
              <span>View Post</span>
              <span aria-hidden="true">↗</span>
            </NuxtLink>
          </div>
          <label class="admin-post-form__post-url-input flex h-[38px] items-center gap-2 rounded border border-[#e3e6e8] bg-[#eff1f2] px-3 py-1 transition-colors hover:border-[#c8ced3] focus-within:border-[#8e9cac]">
            <span class="admin-post-form__post-url-icon text-sm text-[#394047]" aria-hidden="true">⌘</span>
            <input
              v-model="form.slug"
              class="admin-post-form__input min-w-0 flex-1 border-0 bg-transparent p-0 text-sm text-black outline-none"
              type="text"
              pattern="[a-z0-9가-힣]+(-[a-z0-9가-힣]+)*"
              required
              @input="touchSlug"
            >
          </label>
          <p class="admin-post-form__post-url-hint text-xs text-[#7c8b9a]">
            {{ postUrlHint }}
          </p>
        </div>

        <label class="admin-post-form__field grid gap-2 text-sm">
          <span class="admin-post-form__label font-medium">상태</span>
          <select v-model="form.status" class="admin-post-form__select h-[38px] rounded border border-[#e3e6e8] bg-[#eff1f2] px-3 py-2 transition-colors hover:border-[#c8ced3] focus:border-[#8e9cac] focus:outline-none">
            <option value="draft">초안</option>
            <option value="published">발행</option>
            <option value="private">비공개</option>
          </select>
        </label>

        <label v-if="form.status === 'published'" class="admin-post-form__field grid gap-2 text-sm">
          <span class="admin-post-form__label font-medium">
            발행 시각
          </span>
          <input
            v-model="form.publishedAt"
            class="admin-post-form__input h-[38px] rounded border border-[#e3e6e8] bg-[#eff1f2] px-3 py-2 transition-colors hover:border-[#c8ced3] focus:border-[#8e9cac] focus:outline-none"
            type="datetime-local"
          >
          <span class="admin-post-form__hint text-xs text-muted">
            {{ isScheduledPost() ? '미래 시각이면 예약 발행으로 저장됩니다.' : '비워두면 저장 시점으로 발행됩니다.' }}
          </span>
        </label>

        <label class="admin-post-form__field grid gap-2 text-sm">
          <span class="admin-post-form__label font-medium">요약</span>
          <textarea
            v-model="form.excerpt"
            class="admin-post-form__textarea min-h-[108px] rounded border border-[#e3e6e8] bg-[#eff1f2] px-3 py-2 transition-colors hover:border-[#c8ced3] focus:border-[#8e9cac] focus:outline-none"
          />
        </label>

        <div class="admin-post-form__field grid gap-1 text-sm">
          <span class="admin-post-form__label h-[22px] font-bold text-[#15171a]">Tags</span>
          <label class="admin-post-form__tag-editor flex min-h-[38px] w-full items-center gap-2 rounded border border-[#e3e6e8] bg-[#eff1f2] px-3 py-1 transition-colors hover:border-[#c8ced3] focus-within:border-[#8e9cac]">
            <span
              v-for="tag in selectedTags"
              :key="tag"
              class="admin-post-form__tag-badge inline-flex h-6 shrink-0 items-center gap-1.5 rounded-[3px] bg-[#ecd2de] px-2 text-sm text-[#e04e87]"
            >
              <span>{{ tag }}</span>
              <button
                class="admin-post-form__tag-remove grid size-3 place-items-center rounded text-[#e04e87] transition-colors hover:bg-[#e7c3d2]"
                type="button"
                :aria-label="`${tag} 태그 삭제`"
                @click="removeTag(tag)"
              >
                <span aria-hidden="true">x</span>
              </button>
            </span>
            <input
              v-model="tagInput"
              class="admin-post-form__tag-input min-w-0 flex-1 border-0 bg-transparent p-0 text-sm text-black outline-none placeholder:text-[#8e9cac]"
              type="text"
              placeholder="태그 입력"
              @blur="addTagFromInput"
              @keydown="handleTagKeydown"
              @compositionstart="isTagInputComposing = true"
              @compositionend="isTagInputComposing = false"
            >
            <span class="admin-post-form__tag-chevron text-xs text-[#394047]" aria-hidden="true">⌄</span>
          </label>
        </div>

        <div class="admin-post-form__seo grid gap-3 border-t border-[#e3e6e8] pt-5 text-sm">
          <div>
            <h2 class="admin-post-form__section-title text-sm font-semibold text-ink">
              SEO
            </h2>
            <p class="admin-post-form__section-description mt-1 text-xs text-muted">
              검색 결과와 공유 미리보기에 사용할 기본 메타 정보를 설정합니다.
            </p>
          </div>

          <label class="admin-post-form__field grid gap-2">
            <span class="admin-post-form__label font-medium">SEO 제목</span>
            <input
              v-model="form.seoTitle"
              class="admin-post-form__input h-[38px] rounded border border-[#e3e6e8] bg-[#eff1f2] px-3 py-2 transition-colors hover:border-[#c8ced3] focus:border-[#8e9cac] focus:outline-none"
              type="text"
              maxlength="80"
              placeholder="비워두면 글 제목을 사용"
            >
            <span class="admin-post-form__hint text-xs text-muted">
              {{ form.seoTitle.length }}/80
            </span>
          </label>

          <label class="admin-post-form__field grid gap-2">
            <span class="admin-post-form__label font-medium">SEO 설명</span>
            <textarea
              v-model="form.seoDescription"
              class="admin-post-form__textarea min-h-[108px] rounded border border-[#e3e6e8] bg-[#eff1f2] px-3 py-2 transition-colors hover:border-[#c8ced3] focus:border-[#8e9cac] focus:outline-none"
              maxlength="180"
              placeholder="비워두면 요약을 사용"
            />
            <span class="admin-post-form__hint text-xs text-muted">
              {{ form.seoDescription.length }}/180
            </span>
          </label>

          <label class="admin-post-form__checkbox flex items-start gap-2 text-sm">
            <input
              v-model="form.noindex"
              class="admin-post-form__checkbox-input mt-1"
              type="checkbox"
            >
            <span>
              <span class="admin-post-form__label block font-medium">검색엔진 노출 제외</span>
              <span class="admin-post-form__hint mt-1 block text-xs text-muted">공개 글이어도 robots noindex 메타를 추가합니다.</span>
            </span>
          </label>
        </div>
        </div>
        <div v-if="showDelete" class="admin-post-form__settings-bottom shrink-0 border-t border-[#e3e6e8] px-8 py-6">
          <button
            class="admin-post-form__delete-post flex h-10 w-full items-center justify-center gap-2 rounded border border-[#d21a26] text-sm font-bold text-[#d21a26] transition-colors hover:bg-red-50 disabled:opacity-50"
            type="button"
            :disabled="deleting"
            @click="deletePost"
          >
            <span aria-hidden="true">⌫</span>
            <span>{{ deleting ? '삭제 중' : 'Delete post' }}</span>
          </button>
        </div>
      </div>
      </aside>

    <div
      v-if="isMediaPickerOpen"
      class="admin-post-form__media-picker fixed inset-0 z-50 grid place-items-center bg-black/40 px-5 py-8"
      role="dialog"
      aria-modal="true"
      @click.self="closeMediaPicker"
    >
      <section class="admin-post-form__media-picker-panel flex max-h-[86vh] min-h-[620px] w-full max-w-5xl flex-col overflow-hidden bg-white text-ink shadow-xl">
        <div class="admin-post-form__media-picker-header flex items-center justify-between border-b border-line px-5 py-4">
          <h2 class="admin-post-form__media-picker-title text-lg font-semibold">
            대표 이미지
          </h2>
          <button class="admin-post-form__media-picker-close rounded border border-line px-3 py-1.5 text-sm font-semibold transition-colors hover:bg-[#eff1f2]" type="button" @click="closeMediaPicker">
            닫기
          </button>
        </div>
        <div class="admin-post-form__media-picker-tabs flex border-b border-line px-5">
          <button
            class="admin-post-form__media-picker-tab border-b-2 px-3 py-3 text-sm font-semibold transition-colors"
            :class="activeMediaPickerTab === 'upload' ? 'border-[#15171a] text-[#15171a]' : 'border-transparent text-muted hover:text-[#15171a]'"
            type="button"
            @click="activeMediaPickerTab = 'upload'"
          >
            이미지 업로드
          </button>
          <button
            class="admin-post-form__media-picker-tab border-b-2 px-3 py-3 text-sm font-semibold transition-colors"
            :class="activeMediaPickerTab === 'library' ? 'border-[#15171a] text-[#15171a]' : 'border-transparent text-muted hover:text-[#15171a]'"
            type="button"
            @click="activeMediaPickerTab = 'library'"
          >
            미디어 라이브러리
          </button>
        </div>
        <div class="admin-post-form__media-picker-body flex-1 overflow-y-auto p-5">
          <div
            v-if="activeMediaPickerTab === 'upload'"
            class="admin-post-form__media-upload-zone grid min-h-[420px] place-items-center border border-dashed border-[#cfd5da] bg-white text-center"
            @dragover.prevent
            @drop.prevent="dropFeaturedImage"
          >
            <div class="admin-post-form__media-upload-inner grid gap-3">
              <p class="admin-post-form__media-upload-title text-lg font-semibold text-[#15171a]">
                파일을 끌어 업로드
              </p>
              <p class="admin-post-form__media-upload-or text-sm text-muted">
                또는
              </p>
              <label class="admin-post-form__media-upload-button mx-auto inline-flex h-10 cursor-pointer items-center justify-center rounded border border-[#2b78d0] px-8 text-sm font-semibold text-[#1f6fbf] transition-colors hover:bg-blue-50">
                {{ isUploadingFeaturedImage ? '업로드 중' : '파일 선택' }}
                <input class="sr-only" type="file" accept="image/*" @change="uploadFeaturedImage">
              </label>
            </div>
          </div>
          <template v-else>
            <p v-if="isLoadingMedia" class="admin-post-form__media-picker-loading text-sm text-muted">
              미디어를 불러오는 중입니다.
            </p>
            <div v-else-if="mediaItems.length" class="admin-post-form__media-picker-grid grid grid-cols-3 gap-2 sm:grid-cols-4 md:grid-cols-6">
              <button
                v-for="item in mediaItems"
                :key="item.url"
                class="admin-post-form__media-picker-item relative overflow-hidden border bg-white text-left transition hover:border-[#8e9cac] hover:shadow-sm"
                :class="selectedMediaPickerUrl === item.url ? 'border-[#15171a] ring-2 ring-[#15171a]' : 'border-line'"
                type="button"
                :aria-pressed="selectedMediaPickerUrl === item.url"
                @click="selectPickedImage(item)"
              >
                <img class="admin-post-form__media-picker-image aspect-square w-full bg-surface object-cover" :src="item.url" :alt="item.title">
                <span class="admin-post-form__media-picker-name block truncate px-2 py-1.5 text-xs font-semibold text-ink">{{ item.name }}</span>
                <span v-if="selectedMediaPickerUrl === item.url" class="admin-post-form__media-picker-selected absolute right-2 top-2 grid size-6 place-items-center rounded-full bg-[#15171a] text-white" aria-hidden="true">
                  <svg width="13" height="10" viewBox="0 0 13 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M1 5L4.5 8.5L12 1" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                  </svg>
                </span>
              </button>
            </div>
            <p v-else class="admin-post-form__media-picker-empty border border-dashed border-line p-8 text-center text-sm text-muted">
              선택할 미디어가 없습니다.
            </p>
          </template>
        </div>
        <div class="admin-post-form__media-picker-footer flex h-14 shrink-0 items-center justify-end border-t border-line px-5">
          <button
            class="admin-post-form__media-picker-confirm h-9 rounded bg-[#15171a] px-4 text-sm font-semibold text-white transition-colors hover:bg-black disabled:cursor-not-allowed disabled:bg-[#d7dce0] disabled:text-[#8e9cac]"
            type="button"
            :disabled="!selectedMediaPickerUrl"
            @click="applyPickedImage"
          >
            대표 이미지로 적용
          </button>
        </div>
      </section>
    </div>
  </form>
</template>
