<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import AdminDashboard from './components/AdminDashboard.vue'
import AuthDialog from './components/AuthDialog.vue'
import GuideTooltip from './components/GuideTooltip.vue'
import GoalsDashboard from './components/GoalsDashboard.vue'
import MiniCalendar from './components/MiniCalendar.vue'
import PlannerPage from './components/PlannerPage.vue'
import SettingsDashboard from './components/SettingsDashboard.vue'
import StatsDashboard from './components/StatsDashboard.vue'
import {
  deleteAdminUser,
  fetchAdminOverview,
  fetchAdminUserDetail,
  revokeAdminUserSessions,
  updateAdminUserStatus,
} from './lib/adminApi'
import {
  clearAuthState,
  confirmVerification,
  deleteAccount,
  fetchCurrentUser,
  logout as logoutRequest,
  confirmPasswordReset,
  login,
  persistAuthState,
  readAuthState,
  requestPasswordReset,
  requestVerification,
  signup,
  updatePassword,
  updateProfile,
} from './lib/authClient'
import { toUserFacingApiError } from './lib/apiBase'
import { createGoal, deleteGoal, fetchGoals, updateGoal } from './lib/goalsApi'
import { deletePlannerEntry, fetchPlannerEntries, savePlannerEntry } from './lib/plannerApi'
import {
  createInitialPlannerRecords,
  persistPlannerState,
  restorePlannerUiState,
} from './lib/plannerStorage'

const GUIDE_TOOLTIP_STORAGE_KEY = 'ten-minute-guide-tooltips-hidden'
const DDAY_DISABLED_STORAGE_KEY = 'ten-minute-dday-disabled-dates'
const CARRYOVER_CHECK_POLICY_STORAGE_KEY = 'ten-minute-carryover-check-policy'
const CARRYOVER_CHECK_POLICIES = ['ask', 'all', 'current']
const screenMode = ref('planner')
const viewMode = ref('focus')
const printLayout = ref('single')
const printDialogOpen = ref(false)
const demoMode = ref(false)
const demoDayOffset = ref(0)
const authDialogOpen = ref(false)
const authMode = ref('login')
const authBusy = ref(false)
const authMessage = ref('')
const authToken = ref('')
const authPersist = ref(false)
const currentUser = ref(null)
const goals = ref([])
const goalQuery = ref('')
const goalBusy = ref(false)
const goalMessage = ref('')
const editingGoalId = ref(null)
const syncStatus = ref('local')
const syncMessage = ref('')
const syncToastVisible = ref(false)
const selectedDate = ref(new Date())
const calendarViewDate = ref(new Date(selectedDate.value))
const windowWidth = ref(typeof window === 'undefined' ? 1920 : window.innerWidth)
const leftPanelOpen = ref(false)
const rightPanelOpen = ref(false)
const statsRangeStart = ref(toKey(new Date(new Date().setDate(new Date().getDate() - 6))))
const statsRangeEnd = ref(toKey(new Date()))
const printRangeStart = ref(toKey(new Date()))
const printRangeEnd = ref(toKey(new Date()))
const printRangeLayout = ref('single')
const authForm = reactive({
  nickname: '',
  email: '',
  password: '',
  resetToken: '',
  newPassword: '',
  rememberSession: false,
})
const goalForm = reactive({
  title: '',
  targetDate: '',
  activeFrom: '',
  activeUntil: '',
})
const profileForm = reactive({
  nickname: '',
  email: '',
})
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
})
const accountDeleteForm = reactive({
  currentPassword: '',
})
const profileBusy = ref(false)
const passwordBusy = ref(false)
const profileMessage = ref('')
const passwordMessage = ref('')
const accountDeleteBusy = ref(false)
const accountDeleteMessage = ref('')
const carryoverMessage = ref('')
const timetableCopyMessage = ref('')
const carryoverCheckPolicy = ref(readCarryoverCheckPolicy())
const carryoverCheckPrompt = ref(null)
const guideTooltipResetMessage = ref('')
const hiddenGuideTooltips = ref(readHiddenGuideTooltips())
const ddayDisabledDateKeys = ref(readDdayDisabledDateKeys())
const adminBusy = ref(false)
const adminActionUserId = ref(null)
const adminDetailBusy = ref(false)
const adminMessage = ref('')
const adminOverview = ref({
  totalUsers: 0,
  totalAdmins: 0,
  disabledUsers: 0,
  verifiedUsers: 0,
  activeUsers30d: 0,
  newUsers7d: 0,
  totalPlannerEntries: 0,
  totalGoals: 0,
})
const adminUsers = ref([])
const adminRecentLogins = ref([])
const adminSelectedUserId = ref(null)
const adminUserDetail = ref(null)
const timetableCopyForm = reactive({
  sourceDate: toKey(new Date()),
  targetDate: toKey(new Date()),
})

const hours = [
  '6', '7', '8', '9', '10', '11', '12',
  '1', '2', '3', '4', '5',
  '6', '7', '8', '9', '10', '11', '12',
  '1', '2', '3', '4', '5',
]

const timetableCellCount = hours.length * 6
let printPageStyleElement = null
let isHydratingRemoteRecords = false
const syncTimers = new Map()
let syncToastTimer = null

function readHiddenGuideTooltips() {
  if (typeof window === 'undefined') {
    return []
  }

  try {
    const value = JSON.parse(window.localStorage.getItem(GUIDE_TOOLTIP_STORAGE_KEY) ?? '[]')
    return Array.isArray(value) ? value : []
  } catch (error) {
    return []
  }
}

function persistHiddenGuideTooltips() {
  if (typeof window === 'undefined') {
    return
  }

  window.localStorage.setItem(GUIDE_TOOLTIP_STORAGE_KEY, JSON.stringify(hiddenGuideTooltips.value))
}

function isGuideTooltipVisible(id) {
  return !hiddenGuideTooltips.value.includes(id)
}

function dismissGuideTooltip(id) {
  if (hiddenGuideTooltips.value.includes(id)) {
    return
  }

  hiddenGuideTooltips.value = [...hiddenGuideTooltips.value, id]
  guideTooltipResetMessage.value = ''
  persistHiddenGuideTooltips()
}

function resetGuideTooltips() {
  hiddenGuideTooltips.value = []
  guideTooltipResetMessage.value = '가이드 툴팁을 다시 볼 수 있게 했습니다.'
  persistHiddenGuideTooltips()
}

function readCarryoverCheckPolicy() {
  if (typeof window === 'undefined') {
    return 'ask'
  }

  const value = window.localStorage.getItem(CARRYOVER_CHECK_POLICY_STORAGE_KEY)
  return CARRYOVER_CHECK_POLICIES.includes(value) ? value : 'ask'
}

function updateCarryoverCheckPolicy(value) {
  carryoverCheckPolicy.value = CARRYOVER_CHECK_POLICIES.includes(value) ? value : 'ask'

  if (typeof window !== 'undefined') {
    window.localStorage.setItem(CARRYOVER_CHECK_POLICY_STORAGE_KEY, carryoverCheckPolicy.value)
  }
}

function readDdayDisabledDateKeys() {
  if (typeof window === 'undefined') {
    return []
  }

  try {
    const value = JSON.parse(window.localStorage.getItem(DDAY_DISABLED_STORAGE_KEY) ?? '[]')
    return Array.isArray(value) ? value : []
  } catch (error) {
    return []
  }
}

function persistDdayDisabledDateKeys() {
  if (typeof window === 'undefined') {
    return
  }

  window.localStorage.setItem(DDAY_DISABLED_STORAGE_KEY, JSON.stringify(ddayDisabledDateKeys.value))
}

function isDdayDisabledForDate(dateKey) {
  return ddayDisabledDateKeys.value.includes(dateKey)
}

function setDdayDisabledForDate(dateKey, disabled) {
  if (disabled) {
    if (!ddayDisabledDateKeys.value.includes(dateKey)) {
      ddayDisabledDateKeys.value = [...ddayDisabledDateKeys.value, dateKey]
    }
  } else {
    ddayDisabledDateKeys.value = ddayDisabledDateKeys.value.filter((key) => key !== dateKey)
  }

  persistDdayDisabledDateKeys()
}

function createEmptyTimetable() {
  return Array.from({ length: timetableCellCount }, () => false)
}

function createTaskLabel(index) {
  return `${index + 1}`.padStart(2, '0')
}

function createTimetableFromRanges(ranges) {
  const timetable = createEmptyTimetable()

  ranges.forEach(([start, end]) => {
    for (let index = start; index <= end; index += 1) {
      timetable[index] = true
    }
  })

  return timetable
}

const plannerSeed = {
  '2026-04-21': {
    dday: 'D-12 LAUNCH',
    comment: '집중 작업 3개만 남기고, 10분 단위로 흐름을 끊지 않기.',
    tasks: [
      { label: '', title: '홈 화면 정보 구조 정리', checked: true },
      { label: '', title: '플래너 페이지 헤더 상태 연결', checked: true },
      { label: '', title: '타임테이블 액티브 블록 설계' },
      { label: '', title: '우측 캘린더 빠른 이동 구현' },
      { label: '', title: '전날 요약 영역 문구 다듬기' },
      { label: '', title: '다음날 할 일 자동 제안 시나리오' },
      { label: '', title: '통계 카드 레이아웃 정리' },
      { label: '', title: '모바일 스택 레이아웃 점검' },
      { label: '', title: '체크박스 인터랙션 연결' },
      { label: '', title: '페이지 넘김 애니메이션 방향 검토' },
      { label: '', title: 'Tailwind 토큰 정리' },
      { label: '', title: 'Vue 컴포넌트 분리 기준 정하기' },
      { label: '', title: '빈 상태 문구 작성' },
      { label: '', title: '주간 리듬 회고 메모 추가' },
      { label: '', title: '디자인 QA 체크리스트 정리' },
    ],
    memo: [
      { label: '', text: '오른쪽 패널은 정보 확인과 이동이 한 번에 되도록 유지.' },
      { label: '', text: '2페이지 보기는 비교용으로 남기고 기본값은 집중 보기로 사용.' },
      { label: '', text: '작업 흐름이 끊기지 않도록 클릭 포인트를 줄이기.' },
    ],
    prevSummary: [
      '어제 완료한 핵심 3개 보기',
      '이전 체크 누적률 78%',
      '막힌 작업 메모 바로 이어보기',
    ],
    nextFocus: [
      '내일 첫 집중 블록 예약',
      '다음날 핵심 3개 자동 복사',
      '미완료 작업만 재정렬',
    ],
    timetable: createTimetableFromRanges([
      [6, 13],
      [24, 32],
      [42, 47],
    ]),
  },
  '2026-04-22': {
    dday: 'D-11 LAUNCH',
    comment: '초반 90분은 구현, 후반은 문장과 사용성 정리에 사용.',
    tasks: [
      { label: '', title: '통계 섹션 수치 실제 계산 연결', checked: true },
      { label: '', title: '날짜 선택 시 상태 동기화' },
      { label: '', title: '다음날 할 일 템플릿 개선' },
      { label: '', title: '2페이지 보기 비교 카피 작성' },
      { label: '', title: '주간 흐름 카드 추가' },
      { label: '', title: '메모 영역 편집 UX 개선' },
      { label: '', title: '프린트 스타일 초안 점검' },
      { label: '', title: '색 대비 보정' },
      { label: '', title: '우측 패널 축약 버전 검토' },
      { label: '', title: '마감용 체크리스트 분리' },
      { label: '', title: '키보드 탐색 흐름 다듬기' },
      { label: '', title: '데이터 구조 문서화' },
      { label: '', title: '테스트 날짜 더미 세트 늘리기' },
      { label: '', title: '브랜드 푸터 위치 확정' },
      { label: '', title: '빈 상태 일러스트 여부 결정' },
    ],
    memo: [
      { label: '', text: '한 화면에 모든 정보를 모으되 시선 이동은 짧게.' },
      { label: '', text: '캘린더는 검색보다 빠른 이동 장치로 동작해야 함.' },
      { label: '', text: '실행 화면은 다이어리 같고, 인터랙션은 앱처럼.' },
    ],
    prevSummary: [
      '이전날 메모 3줄 이어보기',
      '전날 타임블록 밀도 확인',
      '완료율 기준 다음 일정 추천',
    ],
    nextFocus: [
      '다음날 오전 블록 추천',
      '오늘 미완료 작업 넘기기',
      '이번 주 누적 시간 요약',
    ],
    timetable: createTimetableFromRanges([
      [3, 8],
      [18, 23],
      [54, 62],
    ]),
  },
}

function toKey(date) {
  const year = date.getFullYear()
  const month = `${date.getMonth() + 1}`.padStart(2, '0')
  const day = `${date.getDate()}`.padStart(2, '0')
  return `${year}-${month}-${day}`
}

function toDateValue(value, fallback = new Date()) {
  const nextDate = new Date(value)
  return Number.isNaN(nextDate.getTime()) ? new Date(fallback) : nextDate
}

function startOfDay(date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate())
}

function buildFallbackRecord(date) {
  return {
    comment: '',
    goalEnabled: false,
    selectedGoalId: null,
    tasks: Array.from({ length: 15 }, (_, index) => ({
      label: '',
      title: '',
      checked: false,
    })),
    memo: Array.from({ length: 3 }, () => ({
      label: '',
      text: '',
    })),
    prevSummary: ['이전 기록 없음', '새로운 흐름 시작', ''],
    nextFocus: ['다음 집중 블록 준비', '내일의 핵심 3개 정하기', ''],
    timetable: createEmptyTimetable(),
  }
}

function createDemoDate(offset) {
  const date = new Date()
  date.setDate(date.getDate() + offset)
  return date
}

function createDemoRecord(offset) {
  const variants = {
    '-1': {
      comment: '어제는 오전 집중이 좋았고, 오후에는 미뤄둔 메모를 정리했다. 오늘은 남은 작업을 가볍게 이어가기.',
      tasks: [
        ['01', '주간 목표 다시 읽기', true],
        ['02', '블로그 초안 20분 정리', true],
        ['03', '메일 답장 3개 처리', true],
        ['04', '내일 첫 작업 후보 적기', false],
        ['05', '잠들기 전 회고 한 줄 남기기', false],
      ],
      memo: [
        ['NOTE', '오전에는 알림을 끄면 집중이 훨씬 오래 간다.'],
        ['IDEA', '할 일은 적게 쓰고, 시간표는 솔직하게 남기기.'],
        ['NEXT', '내일은 첫 칸에 가장 부담 없는 작업을 넣어두기.'],
      ],
      timetable: createTimetableFromRanges([[6, 11], [24, 29], [78, 83]]),
    },
    0: {
      comment: '오늘은 큰 계획보다 10분 단위로 시작하는 감각을 유지한다. 끝내지 못한 일은 내일 첫 작업으로 넘긴다.',
      tasks: [
        ['01', '가장 작은 작업 하나 먼저 끝내기', true],
        ['02', '집중 시간 30분 확보하기', true],
        ['03', '플래너 코멘트 한 줄 남기기', false],
        ['04', '저녁 전에 미완료 항목 정리', false],
        ['05', '내일 첫 작업 예약하기', false],
      ],
      memo: [
        ['FOCUS', '완벽한 하루보다 다시 이어갈 수 있는 하루가 목표.'],
        ['RULE', '10분만 시작하고, 더 할 수 있으면 한 칸 더 칠하기.'],
        ['MOOD', '오늘은 가볍게, 하지만 기록은 남기기.'],
      ],
      timetable: createTimetableFromRanges([[12, 17], [36, 44], [90, 95]]),
    },
    1: {
      comment: '내일은 아침 첫 칸에 부담 없는 작업을 놓고 시작한다. 오늘 남긴 흐름을 끊지 않는 것이 목표.',
      tasks: [
        ['01', '오늘 미완료 항목 하나 이어서 보기', false],
        ['02', '오전 집중 블록 2칸 채우기', false],
        ['03', '중요하지 않은 일 1개 덜어내기', false],
        ['04', '짧은 회고 문장 남기기', false],
        ['05', '다음날 첫 작업 적어두기', false],
      ],
      memo: [
        ['PLAN', '시작 작업은 작게, 마감 작업은 분명하게.'],
        ['CHECK', '완료보다 흐름 유지가 우선인 날.'],
        ['SPACE', '비워둔 칸은 실패가 아니라 여유로 보기.'],
      ],
      timetable: createTimetableFromRanges([[8, 13], [48, 53]]),
    },
  }
  const variant = variants[offset] ?? variants[0]
  const record = buildFallbackRecord(createDemoDate(offset))

  record.comment = variant.comment
  record.tasks = record.tasks.map((task, index) => {
    const sample = variant.tasks[index]

    return sample
      ? { label: sample[0], title: sample[1], checked: Boolean(sample[2]) }
      : task
  })
  record.memo = record.memo.map((item, index) => {
    const sample = variant.memo[index]

    return sample
      ? { label: sample[0], text: sample[1] }
      : item
  })
  record.timetable = variant.timetable

  return record
}

function normalizeRecord(record) {
  return {
    ...record,
    goalEnabled: record.goalEnabled !== false,
    selectedGoalId: record.selectedGoalId ?? null,
    tasks: record.tasks.map((task, index) => ({
      label: task.label ?? task.id ?? '',
      title: task.title ?? '',
      checked: Boolean(task.checked),
      carryoverFrom: task.carryoverFrom ?? null,
    })),
    memo: record.memo.map((item) => {
      if (typeof item === 'string') {
        return {
          label: '',
          text: item,
        }
      }

      return {
        label: item.label ?? '',
        text: item.text ?? '',
      }
    }),
    timetable: Array.isArray(record.timetable) && record.timetable.length === timetableCellCount
      ? [...record.timetable]
      : createEmptyTimetable(),
  }
}

const plannerRecords = reactive(createInitialPlannerRecords(plannerSeed, normalizeRecord))

restorePlannerUiState({
  selectedDate,
  calendarViewDate,
  statsRangeStart,
  statsRangeEnd,
  toDateValue,
})

function getPlannerRecord(date) {
  const key = toKey(date)

  if (!plannerRecords[key]) {
    plannerRecords[key] = buildFallbackRecord(date)
  }

  return plannerRecords[key]
}

const planner = computed(() => getPlannerRecord(selectedDate.value))

const secondaryDate = computed(() => {
  const next = new Date(selectedDate.value)
  next.setDate(next.getDate() + 1)
  return next
})

const secondaryPlanner = computed(() => getPlannerRecord(secondaryDate.value))

function getDateDisplay(date) {
  const main = `${date.getFullYear()}. ${`${date.getMonth() + 1}`.padStart(2, '0')}. ${`${date.getDate()}`.padStart(2, '0')}.`
  const weekdayMap = ['(일)', '(월)', '(화)', '(수)', '(목)', '(금)', '(토)']
  const weekday = weekdayMap[date.getDay()]
  const weekdayTone =
    date.getDay() === 0 ? 'text-red-500' : date.getDay() === 6 ? 'text-blue-500' : 'text-ink'

  return {
    main,
    weekday,
    weekdayTone,
  }
}

const selectedDateDisplay = computed(() => getDateDisplay(selectedDate.value))
const secondaryDateDisplay = computed(() => getDateDisplay(secondaryDate.value))
const demoDate = computed(() => createDemoDate(demoDayOffset.value))
const demoDateDisplay = computed(() => getDateDisplay(demoDate.value))
const demoPlanner = computed(() => createDemoRecord(demoDayOffset.value))
const demoDday = computed(() => {
  const offset = demoDayOffset.value

  if (offset < 0) {
    return 'D-8 나만의 루틴 만들기'
  }

  if (offset > 0) {
    return 'D-6 나만의 루틴 만들기'
  }

  return 'D-7 나만의 루틴 만들기'
})

const monthLabel = computed(() =>
  `${calendarViewDate.value.getMonth() + 1}`.padStart(2, '0'),
)

const yearLabel = computed(() => `${calendarViewDate.value.getFullYear()}`)

const calendarDays = computed(() => {
  const base = calendarViewDate.value
  const first = new Date(base.getFullYear(), base.getMonth(), 1)
  const start = new Date(first)
  start.setDate(first.getDate() - first.getDay())

  return Array.from({ length: 42 }, (_, index) => {
    const date = new Date(start)
    date.setDate(start.getDate() + index)
    return {
      key: toKey(date),
      label: date.getDate(),
      date,
      isCurrentMonth: date.getMonth() === base.getMonth(),
    }
  })
})

const normalizedPrintRange = computed(() => {
  const startKey = printRangeStart.value || toKey(selectedDate.value)
  const endKey = printRangeEnd.value || startKey

  if (startKey <= endKey) {
    return { startKey, endKey }
  }

  return { startKey: endKey, endKey: startKey }
})

const printDateKeys = computed(() => {
  const dateKeys = []
  const currentDate = startOfDay(toDateValue(normalizedPrintRange.value.startKey))
  const endDate = startOfDay(toDateValue(normalizedPrintRange.value.endKey))

  while (currentDate <= endDate) {
    dateKeys.push(toKey(currentDate))
    currentDate.setDate(currentDate.getDate() + 1)
  }

  return dateKeys
})

const printPages = computed(() =>
  printDateKeys.value.map((dateKey) => createPrintPage(dateKey)),
)

const printPapers = computed(() => {
  if (printLayout.value === 'single') {
    return printPages.value.map((page) => [page])
  }

  const papers = []

  for (let index = 0; index < printPages.value.length; index += 2) {
    papers.push(printPages.value.slice(index, index + 2))
  }

  return papers
})

const printPageCountLabel = computed(() => {
  const dayCount = printDateKeys.value.length
  const paperCount = printRangeLayout.value === 'double' ? Math.ceil(dayCount / 2) : dayCount
  const layoutLabel = printRangeLayout.value === 'double' ? '2페이지씩' : '1페이지씩'

  return `${dayCount}일치 / ${paperCount}장 (${layoutLabel})`
})

const markedDateKeys = computed(() =>
  Object.entries(plannerRecords)
    .filter(([, record]) => hasPlannerContent(record))
    .map(([key]) => key),
)

const isAuthenticated = computed(() => Boolean(authToken.value && currentUser.value))
const isAdmin = computed(() => currentUser.value?.role === 'admin')
const authSessionInfo = computed(() => ({
  storageLabel: authPersist.value ? '이 기기에서 로그인 유지 중' : '브라우저를 닫으면 로그아웃',
  storageDescription: authPersist.value
    ? '현재 기기에서는 localStorage에 로그인 상태를 저장합니다.'
    : '현재 기기에서는 sessionStorage에만 로그인 상태를 유지합니다.',
  lastLoginLabel: formatSessionDate(currentUser.value?.lastLoginAt),
  verificationLabel: currentUser.value?.role === 'admin'
    ? '관리자 기본 계정'
    : currentUser.value?.emailVerifiedAt
      ? '이메일 인증 완료'
      : '이메일 인증 필요',
}))
const showVerificationResend = computed(() => {
  if (authMode.value !== 'login') {
    return false
  }

  if (!authForm.email.includes('@')) {
    return false
  }

  return authMessage.value.includes('이메일 인증을 완료한 뒤 로그인해 주세요.')
})
const filteredGoals = computed(() => {
  const query = goalQuery.value.trim().toLowerCase()
  return goals.value.filter((goal) => {
    if (!query) {
      return true
    }

    return goal.title.toLowerCase().includes(query)
  })
})
const activePlannerGoals = computed(() =>
  goals.value
    .filter((goal) => {
      if (!goal.activeFrom || !goal.activeUntil) {
        return false
      }

      const selectedKey = toKey(selectedDate.value)
      return selectedKey >= goal.activeFrom && selectedKey <= goal.activeUntil
    })
    .sort((left, right) => {
      const leftDistance = Math.abs(startOfDay(toDateValue(left.targetDate)).getTime() - startOfDay(selectedDate.value).getTime())
      const rightDistance = Math.abs(startOfDay(toDateValue(right.targetDate)).getTime() - startOfDay(selectedDate.value).getTime())
      return leftDistance - rightDistance
    }),
)
const plannerGoal = computed(() => activePlannerGoals.value[0] ?? null)
const selectedDateKey = computed(() => toKey(selectedDate.value))
const plannerGoalToggleOn = computed(() =>
  Boolean(plannerGoal.value) && !isDdayDisabledForDate(selectedDateKey.value),
)
const plannerDday = computed(() => {
  if (!plannerGoalToggleOn.value || !plannerGoal.value) {
    return ''
  }

  const targetDate = startOfDay(toDateValue(plannerGoal.value.targetDate))
  const currentDate = startOfDay(selectedDate.value)
  const diffDays = Math.round((targetDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000))
  const badge =
    diffDays === 0 ? 'D-DAY' : diffDays > 0 ? `D-${diffDays}` : `D+${Math.abs(diffDays)}`

  return `${badge} ${plannerGoal.value.title}`
})
const showPlannerDday = computed(() =>
  plannerGoalToggleOn.value && Boolean(plannerGoal.value),
)
const hasActiveGoalForSelectedDate = computed(() => Boolean(plannerGoal.value))

const filledTasks = computed(() =>
  planner.value.tasks.filter((task) => task.title.trim()),
)
const completedTasks = computed(() =>
  filledTasks.value.filter((task) => task.checked).length,
)
const incompleteTasks = computed(() =>
  planner.value.tasks.filter((task) => task.title.trim() && !task.checked),
)
const completionRate = computed(() => {
  if (filledTasks.value.length === 0) {
    return 0
  }

  return Math.round((completedTasks.value / filledTasks.value.length) * 100)
})

function formatTotalTime(record) {
  const activeCellCount = record.timetable.filter(Boolean).length
  const totalMinutes = activeCellCount * 10
  const hoursPart = `${Math.floor(totalMinutes / 60)}`.padStart(2, '0')
  const minutesPart = `${totalMinutes % 60}`.padStart(2, '0')

  return `${hoursPart}H ${minutesPart}M`
}

function formatMinutesKorean(totalMinutes) {
  const hoursPart = `${Math.floor(totalMinutes / 60)}`.padStart(2, '0')
  const minutesPart = `${totalMinutes % 60}`.padStart(2, '0')
  return `${hoursPart}시간 ${minutesPart}분`
}

function formatTotalTimeKorean(record) {
  return formatMinutesKorean(record.timetable.filter(Boolean).length * 10)
}

function getFocusedMinutes(record) {
  return record.timetable.filter(Boolean).length * 10
}

function getCompletionRate(record) {
  const activeTasks = record.tasks.filter((task) => task.title.trim())

  if (activeTasks.length === 0) {
    return 0
  }

  const doneTasks = activeTasks.filter((task) => task.checked).length
  return Math.round((doneTasks / activeTasks.length) * 100)
}

function shiftDate(amount) {
  const next = new Date(selectedDate.value)
  next.setDate(next.getDate() + amount)
  selectedDate.value = next
  calendarViewDate.value = new Date(next)
  carryoverMessage.value = ''
  timetableCopyMessage.value = ''
}

function shiftCalendarMonth(amount) {
  const next = new Date(calendarViewDate.value)
  next.setMonth(next.getMonth() + amount)
  calendarViewDate.value = next
}

function shiftCalendarYear(amount) {
  const next = new Date(calendarViewDate.value)
  next.setFullYear(next.getFullYear() + amount)
  calendarViewDate.value = next
}

function selectDate(date) {
  selectedDate.value = new Date(date)
  calendarViewDate.value = new Date(date)
  carryoverMessage.value = ''
  timetableCopyMessage.value = ''
}

function updateComment(record, value) {
  record.comment = value
  schedulePlannerSyncForRecord(record)
}

function updateGoalEnabled(record, value) {
  if (value && !hasActiveGoalForSelectedDate.value) {
    return
  }

  setDdayDisabledForDate(selectedDateKey.value, !value)
  record.goalEnabled = value

  if (hasPlannerContent(record)) {
    schedulePlannerSyncForRecord(record)
  }
}

function updateTaskLabel(record, { index, value }) {
  record.tasks[index].label = value
  schedulePlannerSyncForRecord(record)
}

function updateTaskTitle(record, { index, value }) {
  record.tasks[index].title = value

  if (!value.trim()) {
    record.tasks[index].carryoverFrom = null
  }

  schedulePlannerSyncForRecord(record)
}

function toggleTask(record, index) {
  const task = record.tasks[index]
  const nextChecked = !task.checked

  if (nextChecked && task.carryoverFrom) {
    if (carryoverCheckPolicy.value === 'all') {
      completeCarryoverTaskChain(record, index)
      return
    }

    if (carryoverCheckPolicy.value === 'ask') {
      carryoverCheckPrompt.value = {
        record,
        index,
        taskTitle: task.title,
        originKey: task.carryoverFrom,
      }
      return
    }
  }

  task.checked = nextChecked
  schedulePlannerSyncForRecord(record)
}

function completeCarryoverTaskCurrent(record, index) {
  record.tasks[index].checked = true
  schedulePlannerSyncForRecord(record)
}

function completeCarryoverTaskChain(record, index) {
  const task = record.tasks[index]
  const originKey = task.carryoverFrom
  const recordKey = findRecordKey(record)

  task.checked = true
  schedulePlannerSyncForRecord(record)

  if (!originKey || !recordKey) {
    return
  }

  Object.entries(plannerRecords).forEach(([key, candidateRecord]) => {
    if (key < originKey || key >= recordKey) {
      return
    }

    const matchingTask = candidateRecord.tasks.find((candidateTask) =>
      candidateTask.title === task.title
      && (candidateTask.carryoverFrom === originKey || key === originKey),
    )

    if (matchingTask) {
      matchingTask.checked = true
      schedulePlannerSync(key)
    }
  })
}

function answerCarryoverCheckPrompt(scope, rememberPolicy = null) {
  const prompt = carryoverCheckPrompt.value

  if (!prompt) {
    return
  }

  if (rememberPolicy) {
    updateCarryoverCheckPolicy(rememberPolicy)
  }

  if (scope === 'all') {
    completeCarryoverTaskChain(prompt.record, prompt.index)
  } else {
    completeCarryoverTaskCurrent(prompt.record, prompt.index)
  }

  carryoverCheckPrompt.value = null
}

function closeCarryoverCheckPrompt() {
  carryoverCheckPrompt.value = null
}

function handleGlobalKeydown(event) {
  if (event.key === 'Escape' && printDialogOpen.value) {
    event.preventDefault()
    closePrintDialog()
    return
  }

  if (event.key === 'Escape' && carryoverCheckPrompt.value) {
    event.preventDefault()
    closeCarryoverCheckPrompt()
  }
}

function clearTasks(record, indexes) {
  indexes.forEach((index) => {
    if (!record.tasks[index]) {
      return
    }

    record.tasks[index].title = ''
    record.tasks[index].checked = false
    record.tasks[index].carryoverFrom = null
  })
  schedulePlannerSyncForRecord(record)
}

function carryIncompleteTasksToNextDay() {
  const tasksToCarry = incompleteTasks.value.map((task) => ({
    label: task.label,
    title: task.title,
    checked: false,
    carryoverFrom: task.carryoverFrom ?? selectedDateKey.value,
  }))

  if (tasksToCarry.length === 0) {
    carryoverMessage.value = '이월할 미완료 항목이 없습니다.'
    return
  }

  const targetRecord = secondaryPlanner.value
  const emptyIndexes = targetRecord.tasks
    .map((task, index) => ({ task, index }))
    .filter(({ task }) => !task.title.trim())
    .map(({ index }) => index)
  const copyCount = Math.min(tasksToCarry.length, emptyIndexes.length)

  if (copyCount === 0) {
    carryoverMessage.value = '다음 날짜에 비어 있는 할 일 칸이 없습니다.'
    return
  }

  for (let index = 0; index < copyCount; index += 1) {
    const task = tasksToCarry[index]
    targetRecord.tasks[emptyIndexes[index]] = {
      ...task,
      checked: false,
    }
  }

  schedulePlannerSyncForRecord(targetRecord)

  const nextDateLabel = createDateLabel(toKey(secondaryDate.value))
  carryoverMessage.value =
    copyCount === tasksToCarry.length
      ? `${nextDateLabel} 빈칸에 미완료 ${copyCount}개를 이월했습니다.`
      : `${nextDateLabel} 빈칸 ${copyCount}개까지만 이월했습니다.`
}

function useSelectedDateAsTimetableSource() {
  timetableCopyForm.sourceDate = selectedDateKey.value
  timetableCopyMessage.value = ''
}

function useSelectedDateAsTimetableTarget() {
  timetableCopyForm.targetDate = selectedDateKey.value
  timetableCopyMessage.value = ''
}

function copyTimetableBetweenDates() {
  const sourceKey = timetableCopyForm.sourceDate
  const targetKey = timetableCopyForm.targetDate

  if (!sourceKey || !targetKey) {
    timetableCopyMessage.value = '복사할 날짜와 붙여넣을 날짜를 모두 선택해 주세요.'
    return
  }

  const sourceRecord = getPlannerRecord(toDateValue(sourceKey))
  const targetRecord = getPlannerRecord(toDateValue(targetKey))
  const nextTimetable = [...sourceRecord.timetable]

  targetRecord.timetable = nextTimetable
  schedulePlannerSyncForRecord(targetRecord)

  const sourceDateLabel = createDateLabel(sourceKey)
  const targetDateLabel = createDateLabel(targetKey)

  timetableCopyMessage.value = nextTimetable.some(Boolean)
    ? `${sourceDateLabel} 타임테이블을 ${targetDateLabel}에 복사했습니다.`
    : `${sourceDateLabel} 타임테이블이 비어 있어 ${targetDateLabel}도 비웠습니다.`
}

function updateMemo(record, { index, value }) {
  record.memo[index].text = value
  schedulePlannerSyncForRecord(record)
}

function updateMemoLabel(record, { index, value }) {
  record.memo[index].label = value
  schedulePlannerSyncForRecord(record)
}

function updateTimetable(record, nextTimetable) {
  record.timetable = nextTimetable
  schedulePlannerSyncForRecord(record)
}

function hasPlannerContent(record) {
  return Boolean(
    record.comment.trim() ||
    record.tasks.some((task) => task.title.trim() || task.checked) ||
    record.memo.some((item) => item.label.trim() || item.text.trim()) ||
    record.timetable.some(Boolean),
  )
}

const plannerEntries = computed(() =>
  Object.entries(plannerRecords)
    .filter(([, record]) => hasPlannerContent(record))
    .sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
)

const normalizedStatsRange = computed(() => {
  const todayKey = toKey(new Date())
  const startKey = statsRangeStart.value || todayKey
  const endKey = statsRangeEnd.value || todayKey

  if (startKey <= endKey) {
    return { startKey, endKey }
  }

  return { startKey: endKey, endKey: startKey }
})

const rangeEntries = computed(() =>
  plannerEntries.value.filter(([key]) =>
    key >= normalizedStatsRange.value.startKey && key <= normalizedStatsRange.value.endKey,
  ),
)

const totalFocusedMinutes = computed(() =>
  rangeEntries.value.reduce((total, [, record]) => total + getFocusedMinutes(record), 0),
)

const totalRecordedTasks = computed(() =>
  rangeEntries.value.reduce(
    (total, [, record]) => total + record.tasks.filter((task) => task.title.trim()).length,
    0,
  ),
)

const completedRecordedTasks = computed(() =>
  rangeEntries.value.reduce(
    (total, [, record]) => total + record.tasks.filter((task) => task.title.trim() && task.checked).length,
    0,
  ),
)

const aggregateCompletionRate = computed(() => {
  if (totalRecordedTasks.value === 0) {
    return 0
  }

  return Math.round((completedRecordedTasks.value / totalRecordedTasks.value) * 100)
})

const overviewCards = computed(() => [
  {
    label: 'TOTAL FOCUSED',
    value: formatMinutesKorean(totalFocusedMinutes.value),
    caption: '지금까지 기록된 전체 집중 시간',
  },
  {
    label: 'AVERAGE COMPLETION',
    value: `${aggregateCompletionRate.value}%`,
    caption: '입력된 할 일 기준 전체 평균 완료율',
  },
  {
    label: 'RECORDED DAYS',
    value: `${rangeEntries.value.length}일`,
    caption: '기록이 남아 있는 날짜 수',
  },
  {
    label: 'COMPLETED TASKS',
    value: `${completedRecordedTasks.value} / ${totalRecordedTasks.value || 0}`,
    caption: '완료된 할 일과 전체 입력된 할 일 수',
  },
])

function formatMinutes(totalMinutes) {
  const hoursPart = Math.floor(totalMinutes / 60)
  const minutesPart = totalMinutes % 60
  return `${hoursPart}H ${`${minutesPart}`.padStart(2, '0')}M`
}

function createDateLabel(dateKey) {
  const date = toDateValue(dateKey)
  const display = getDateDisplay(date)
  return `${display.main} ${display.weekday}`
}

function findPlannerGoalForDate(dateKey) {
  const activeGoals = goals.value
    .filter((goal) => {
      if (!goal.activeFrom || !goal.activeUntil) {
        return false
      }

      return dateKey >= goal.activeFrom && dateKey <= goal.activeUntil
    })
    .sort((left, right) => {
      const currentDate = startOfDay(toDateValue(dateKey))
      const leftDistance = Math.abs(startOfDay(toDateValue(left.targetDate)).getTime() - currentDate.getTime())
      const rightDistance = Math.abs(startOfDay(toDateValue(right.targetDate)).getTime() - currentDate.getTime())
      return leftDistance - rightDistance
    })

  return activeGoals[0] ?? null
}

function createPlannerDdayForDate(dateKey) {
  if (isDdayDisabledForDate(dateKey)) {
    return ''
  }

  const goal = findPlannerGoalForDate(dateKey)

  if (!goal) {
    return ''
  }

  const targetDate = startOfDay(toDateValue(goal.targetDate))
  const currentDate = startOfDay(toDateValue(dateKey))
  const diffDays = Math.round((targetDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000))
  const badge =
    diffDays === 0 ? 'D-DAY' : diffDays > 0 ? `D-${diffDays}` : `D+${Math.abs(diffDays)}`

  return `${badge} ${goal.title}`
}

function createPrintPage(dateKey) {
  const date = toDateValue(dateKey)

  return {
    key: dateKey,
    display: getDateDisplay(date),
    record: getPlannerRecord(date),
    dday: createPlannerDdayForDate(dateKey),
  }
}

const weeklyRecords = computed(() => {
  const entries = rangeEntries.value.map(([key, record]) => {
    const date = toDateValue(key)
    const weekdayShort = ['일', '월', '화', '수', '목', '금', '토'][date.getDay()]
    const focusedMinutes = getFocusedMinutes(record)
    const activeTasks = record.tasks.filter((task) => task.title.trim())
    const doneTasks = activeTasks.filter((task) => task.checked)

    return {
      key,
      weekday: weekdayShort,
      dateLabel: `${`${date.getMonth() + 1}`.padStart(2, '0')}.${`${date.getDate()}`.padStart(2, '0')}`,
      focusedMinutes,
      focusedTime: formatMinutesKorean(focusedMinutes),
      completedTasks: doneTasks.length,
      totalTasks: activeTasks.length,
    }
  })

  if (entries.length === 0) {
    return []
  }

  const maxMinutes = Math.max(...entries.map((entry) => entry.focusedMinutes), 60)

  return entries.map((entry) => ({
    ...entry,
    barHeight: Math.max(12, Math.round((entry.focusedMinutes / maxMinutes) * 100)),
  }))
})

const recentRecords = computed(() =>
  [...rangeEntries.value]
    .sort(([leftKey], [rightKey]) => rightKey.localeCompare(leftKey))
    .slice(0, 5)
    .map(([key, record]) => ({
      key,
      dateLabel: createDateLabel(key),
      comment: record.comment.trim(),
      focusedTime: formatTotalTimeKorean(record),
      completionRate: getCompletionRate(record),
    })),
)

const bestDay = computed(() => {
  if (rangeEntries.value.length === 0) {
    return null
  }

  const [bestKey, bestRecord] = [...rangeEntries.value].reduce((bestEntry, currentEntry) => {
    const [, bestRecordValue] = bestEntry
    const [, currentRecordValue] = currentEntry

    return getFocusedMinutes(currentRecordValue) > getFocusedMinutes(bestRecordValue) ? currentEntry : bestEntry
  })

  return {
    dateLabel: createDateLabel(bestKey),
    summary: `${formatTotalTimeKorean(bestRecord)} 집중, 완료율 ${getCompletionRate(bestRecord)}%, 코멘트 "${
      bestRecord.comment.trim() || '없음'
    }"`,
  }
})

const previousRecordedEntry = computed(() => {
  const selectedKey = toKey(selectedDate.value)

  return [...plannerEntries.value]
    .filter(([key]) => key < selectedKey)
    .sort(([leftKey], [rightKey]) => rightKey.localeCompare(leftKey))[0] ?? null
})

const prevSnapshotItems = computed(() => {
  if (!previousRecordedEntry.value) {
    return [
      '이전 기록 없음',
      '첫 기록을 쌓아보세요.',
      '오늘부터 흐름을 만들 수 있습니다.',
    ]
  }

  const [entryKey, entryRecord] = previousRecordedEntry.value
  const completedCount = entryRecord.tasks.filter((task) => task.title.trim() && task.checked).length
  const previousComment = entryRecord.comment.trim()
  const previousTopTask = entryRecord.tasks.find((task) => task.title.trim())

  return [
    `${createDateLabel(entryKey)} 기록`,
    `${formatTotalTimeKorean(entryRecord)} 집중 / 완료 ${completedCount}개`,
    previousComment || (previousTopTask ? `주요 작업: ${previousTopTask.title}` : '남겨진 코멘트 없음'),
  ]
})

const readNextItems = computed(() => {
  const nextDayFirstTask = secondaryPlanner.value.tasks.find((task) => task.title.trim())
  const carryTask = incompleteTasks.value[0]?.title

  return [
    nextDayFirstTask
      ? `내일 첫 작업: ${nextDayFirstTask.title}`
      : carryTask
        ? `내일 이어갈 첫 작업: ${carryTask}`
        : '내일 첫 작업은 아직 비어 있습니다.',
    incompleteTasks.value.length > 0
      ? `아직 처리되지 않은 할 일이 ${incompleteTasks.value.length}개 있습니다.`
      : '오늘 할 일은 모두 처리되었습니다.',
  ]
})

const nextDaySummary = computed(() => {
  const nextDayFirstTask = secondaryPlanner.value.tasks.find((task) => task.title.trim())

  if (!hasPlannerContent(secondaryPlanner.value)) {
    return '등록된 일정이 없습니다.'
  }

  if (!nextDayFirstTask) {
    return '등록된 일정이 없습니다.'
  }

  return `내일의 첫 작업은 "${nextDayFirstTask.title}" 입니다.`
})

const isWideFocusSidebar = computed(() => windowWidth.value >= 1620)
const isOverlayFocusSidebar = computed(() => windowWidth.value < 1280)
const showInlineLeftSidebar = computed(() => windowWidth.value >= 1280)
const isCompactMobile = computed(() => windowWidth.value < 800)
const showInlineFocusSidebar = computed(() => !isOverlayFocusSidebar.value)
const focusSidebarOuterClass = computed(() =>
  showInlineFocusSidebar.value
    ? isWideFocusSidebar.value
      ? 'xl:w-[640px]'
      : 'xl:w-full xl:max-w-[360px]'
    : '',
)
const focusSidebarGridClass = computed(() =>
  isWideFocusSidebar.value
    ? '2xl:grid-cols-[280px_minmax(0,1fr)] 2xl:items-start'
    : 'grid-cols-1',
)
const spreadScale = computed(() => {
  const reservedWidth = windowWidth.value >= 1280 ? 532 : 120
  const availableWidth = Math.max(windowWidth.value - reservedWidth, 980)
  const baseWidth = 1548
  const nextScale = Math.min(1, availableWidth / baseWidth)

  return Number(Math.max(nextScale, 0.86).toFixed(3))
})
const spreadCanvasStyle = computed(() => {
  const scale = spreadScale.value
  return {
    width: `${1548 * scale}px`,
    minWidth: `${1548 * scale}px`,
  }
})
const spreadPageFrameStyle = computed(() => {
  const scale = spreadScale.value
  return {
    width: `${762 * scale}px`,
    height: `${1118 * scale}px`,
  }
})
const spreadPageStyle = computed(() => ({
  width: '762px',
  maxWidth: 'none',
  transform: `scale(${spreadScale.value})`,
  transformOrigin: 'top left',
}))

watch(
  [plannerRecords, selectedDate, calendarViewDate, statsRangeStart, statsRangeEnd],
  () => {
    persistPlannerState({
      plannerRecords,
      selectedDate: selectedDate.value,
      calendarViewDate: calendarViewDate.value,
      statsRangeStart: normalizedStatsRange.value.startKey,
      statsRangeEnd: normalizedStatsRange.value.endKey,
      includeRecords: !isAuthenticated.value,
    })
  },
  { deep: true },
)

watch(
  [selectedDate, plannerGoal],
  () => {
    if (plannerGoal.value && planner.value.goalEnabled === false && !isDdayDisabledForDate(selectedDateKey.value)) {
      planner.value.goalEnabled = true

      if (hasPlannerContent(planner.value)) {
        schedulePlannerSyncForRecord(planner.value)
      }
    }
  },
)

watch(
  selectedDateKey,
  (nextKey, previousKey) => {
    if (!timetableCopyForm.targetDate || timetableCopyForm.targetDate === previousKey) {
      timetableCopyForm.targetDate = nextKey
    }

    if (!timetableCopyForm.sourceDate) {
      timetableCopyForm.sourceDate = nextKey
    }
  },
)

function fillTaskLabelsWithNumbers(record) {
  record.tasks.forEach((task, index) => {
    task.label = createTaskLabel(index)
  })
  schedulePlannerSyncForRecord(record)
}

function clearTaskLabels(record) {
  record.tasks.forEach((task) => {
    task.label = ''
  })
  schedulePlannerSyncForRecord(record)
}

function areTaskLabelsNumbered(record) {
  return record.tasks.every((task, index) => task.label === createTaskLabel(index))
}

function updateWindowWidth() {
  windowWidth.value = window.innerWidth

  if (windowWidth.value >= 1280) {
    leftPanelOpen.value = false
    rightPanelOpen.value = false
  }
}

function openLeftPanel() {
  leftPanelOpen.value = true
}

function closeLeftPanel() {
  leftPanelOpen.value = false
}

function openRightPanel() {
  rightPanelOpen.value = true
}

function closeRightPanel() {
  rightPanelOpen.value = false
}

function openPrintDialog() {
  const selectedKey = toKey(selectedDate.value)
  printRangeStart.value = selectedKey
  printRangeEnd.value = selectedKey
  printRangeLayout.value = viewMode.value === 'spread' ? 'double' : 'single'
  printDialogOpen.value = true
  closeLeftPanel()
}

function closePrintDialog() {
  printDialogOpen.value = false
}

function applyStatsQuickRange(days) {
  const endDate = new Date()
  const startDate = new Date(endDate)
  startDate.setDate(endDate.getDate() - (days - 1))
  statsRangeStart.value = toKey(startDate)
  statsRangeEnd.value = toKey(endDate)
}

function setScreenMode(mode) {
  if (mode === 'admin' && !isAdmin.value) {
    return
  }

  screenMode.value = mode

  if (mode === 'stats') {
    statsRangeEnd.value = toKey(new Date())
  }

  if (mode === 'admin') {
    void loadAdminDashboard()
  }

  closeLeftPanel()
}

function setViewMode(mode) {
  viewMode.value = mode
  closeLeftPanel()
}

function setSyncFeedback(status, message, options = {}) {
  const {
    visible = true,
    duration = 1600,
    sticky = false,
  } = options

  syncStatus.value = status
  syncMessage.value = message

  if (syncToastTimer) {
    window.clearTimeout(syncToastTimer)
    syncToastTimer = null
  }

  syncToastVisible.value = visible

  if (visible && !sticky) {
    syncToastTimer = window.setTimeout(() => {
      syncToastVisible.value = false
    }, duration)
  }
}

function getTodayKey() {
  return toKey(new Date())
}

function findOverlappingGoal({ activeFrom, activeUntil, excludeGoalId = null }) {
  if (!activeFrom || !activeUntil) {
    return null
  }

  return goals.value.find((goal) => {
    if (excludeGoalId && goal.id === excludeGoalId) {
      return false
    }

    if (!goal.activeFrom || !goal.activeUntil) {
      return false
    }

    return activeFrom <= goal.activeUntil && activeUntil >= goal.activeFrom
  }) ?? null
}

function resetAuthForm() {
  authForm.nickname = ''
  authForm.email = ''
  authForm.password = ''
  authForm.resetToken = ''
  authForm.newPassword = ''
  authForm.rememberSession = false
}

function resetGoalForm() {
  goalForm.title = ''
  goalForm.targetDate = ''
  goalForm.activeFrom = getTodayKey()
  goalForm.activeUntil = ''
  editingGoalId.value = null
}

function syncProfileForm() {
  profileForm.nickname = currentUser.value?.nickname ?? ''
  profileForm.email = currentUser.value?.email ?? ''
}

function formatSessionDate(value) {
  if (!value) {
    return '기록이 없습니다.'
  }

  const date = new Date(value)

  if (Number.isNaN(date.getTime())) {
    return '기록이 없습니다.'
  }

  return `${date.getFullYear()}. ${`${date.getMonth() + 1}`.padStart(2, '0')}. ${`${date.getDate()}`.padStart(2, '0')} ${`${date.getHours()}`.padStart(2, '0')}:${`${date.getMinutes()}`.padStart(2, '0')}`
}

function resetPasswordForm() {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

function resetAccountDeleteForm() {
  accountDeleteForm.currentPassword = ''
}

function openAuthDialog(mode = 'login') {
  authMode.value = mode
  authMessage.value = ''
  authDialogOpen.value = true
}

function openPasswordResetFromUrl() {
  if (typeof window === 'undefined') {
    return
  }

  const url = new URL(window.location.href)

  if (!url.pathname.includes('reset-password')) {
    return
  }

  const token = url.searchParams.get('token') ?? ''

  if (!token) {
    return
  }

  authForm.resetToken = token
  authMode.value = 'reset-confirm'
  authMessage.value = ''
  authDialogOpen.value = true
}

async function openVerificationFromUrl() {
  if (typeof window === 'undefined') {
    return
  }

  const url = new URL(window.location.href)

  if (!url.pathname.includes('verify-email')) {
    return
  }

  const token = url.searchParams.get('token') ?? ''

  if (!token) {
    authMode.value = 'login'
    authMessage.value = '이메일 인증 링크가 올바르지 않습니다.'
    authDialogOpen.value = true
    return
  }

  authBusy.value = true
  authMode.value = 'login'
  authDialogOpen.value = true

  try {
    const result = await confirmVerification({ token })
    authMessage.value = result.message || '이메일 인증이 완료되었습니다. 이제 로그인할 수 있습니다.'
    url.pathname = '/'
    url.search = ''
    window.history.replaceState({}, '', url.toString())
  } catch (error) {
    authMessage.value = toUserFacingApiError(error, '이메일 인증 링크를 처리하지 못했습니다.')
  } finally {
    authBusy.value = false
  }
}

function closeAuthDialog() {
  authDialogOpen.value = false
  authMessage.value = ''
  resetAuthForm()
}

function updateAuthField({ field, value }) {
  authForm[field] = value
}

async function applyAuthSuccess(data, persist = false) {
  authToken.value = data.token
  authPersist.value = persist
  currentUser.value = data.user
  setSyncFeedback('cloud', '클라우드 동기화 연결됨')
  persistAuthState({
    token: data.token,
    user: data.user,
    persist,
  })
  await loadGoals()
  await hydratePlannerRecordsFromApi()
  await loadAdminDashboard()
  syncProfileForm()
  closeAuthDialog()
}

async function submitAuthForm() {
  authBusy.value = true
  authMessage.value = ''

  try {
    if (authMode.value === 'reset-request') {
      const result = await requestPasswordReset({
        email: authForm.email,
      })
      authMessage.value = result.resetPreviewUrl
        ? `${result.message} 개발용 링크: ${result.resetPreviewUrl}`
        : result.message
      return
    }

    if (authMode.value === 'reset-confirm') {
      const result = await confirmPasswordReset({
        token: authForm.resetToken,
        newPassword: authForm.newPassword,
      })
      authMode.value = 'login'
      authForm.password = ''
      authForm.newPassword = ''
      authForm.resetToken = ''
      authMessage.value = result.message
      return
    }

    const result = authMode.value === 'login'
      ? await login({
          email: authForm.email,
          password: authForm.password,
        })
      : await signup({
          nickname: authForm.nickname,
          email: authForm.email,
          password: authForm.password,
        })

    if (authMode.value === 'signup') {
      authMode.value = 'login'
      authForm.password = ''
      authMessage.value = result.message
      return
    }

    await applyAuthSuccess(result, authForm.rememberSession)
  } catch (error) {
    authMessage.value = toUserFacingApiError(error, '인증 처리 중 문제가 발생했습니다.')
  } finally {
    authBusy.value = false
  }
}

async function resendVerificationEmail() {
  const email = authForm.email.trim()

  if (!email || !email.includes('@')) {
    authMessage.value = '인증 메일을 다시 받으려면 이메일 주소를 먼저 입력해 주세요.'
    return
  }

  authBusy.value = true

  try {
    const result = await requestVerification({ email }, authToken.value || undefined)
    authMessage.value = result.verificationPreviewUrl
      ? `${result.message} 개발용 링크: ${result.verificationPreviewUrl}`
      : result.message
  } catch (error) {
    authMessage.value = toUserFacingApiError(error, '인증 메일을 다시 보내지 못했습니다.')
  } finally {
    authBusy.value = false
  }
}

async function restoreAuthSession() {
  const savedAuth = readAuthState()

  if (!savedAuth.token) {
    return
  }

  authToken.value = savedAuth.token
  authPersist.value = savedAuth.persist
  currentUser.value = savedAuth.user ?? null

  try {
    const result = await fetchCurrentUser(savedAuth.token)
    currentUser.value = result.user
    setSyncFeedback('cloud', '클라우드 동기화 연결됨')
    persistAuthState({
      token: savedAuth.token,
      user: result.user,
      persist: savedAuth.persist,
    })
    await loadGoals()
    await hydratePlannerRecordsFromApi()
    await loadAdminDashboard()
    syncProfileForm()
  } catch (error) {
    authToken.value = ''
    authPersist.value = false
    currentUser.value = null
    setSyncFeedback('local', '로그인 후 클라우드 저장을 사용할 수 있습니다.', {
      visible: false,
    })
    clearAuthState()
  }
}

function clearAuthenticatedState() {
  clearPendingSyncTimers()
  authToken.value = ''
  authPersist.value = false
  currentUser.value = null
  goals.value = []
  goalQuery.value = ''
  goalMessage.value = ''
  adminMessage.value = ''
  adminUsers.value = []
  adminRecentLogins.value = []
  adminSelectedUserId.value = null
  adminUserDetail.value = null
  accountDeleteMessage.value = ''
  adminOverview.value = {
    totalUsers: 0,
    totalAdmins: 0,
    disabledUsers: 0,
    verifiedUsers: 0,
    activeUsers30d: 0,
    newUsers7d: 0,
    totalPlannerEntries: 0,
    totalGoals: 0,
  }
  if (screenMode.value === 'admin') {
    screenMode.value = 'planner'
  }
  setSyncFeedback('local', '로그인 후 클라우드 저장을 사용할 수 있습니다.', {
    visible: false,
  })
  clearAuthState()
  restoreLocalPlannerRecords()
  resetGoalForm()
  resetPasswordForm()
  resetAccountDeleteForm()
}

async function logout() {
  const token = authToken.value

  if (token) {
    try {
      await logoutRequest(token)
    } catch (error) {
      console.warn('서버 로그아웃 처리에 실패했습니다.', error)
    }
  }

  clearAuthenticatedState()
}

async function loadAdminDashboard() {
  if (!authToken.value || !isAdmin.value) {
    adminUsers.value = []
    adminRecentLogins.value = []
    adminSelectedUserId.value = null
    adminUserDetail.value = null
    adminMessage.value = ''
    return
  }

  adminBusy.value = true

  try {
    const result = await fetchAdminOverview(authToken.value)
    adminOverview.value = result.summary
    adminUsers.value = result.users
    adminRecentLogins.value = result.recentLogins
    adminMessage.value = ''
  } catch (error) {
    adminMessage.value = error.message || '관리자 데이터를 불러오지 못했습니다.'
  } finally {
    adminBusy.value = false
  }
}

async function loadAdminUserDetail(userId) {
  if (!authToken.value || !isAdmin.value) {
    return
  }

  adminDetailBusy.value = true

  try {
    const result = await fetchAdminUserDetail(authToken.value, userId)
    adminSelectedUserId.value = userId
    adminUserDetail.value = result
    adminMessage.value = ''
  } catch (error) {
    adminMessage.value = error.message || '사용자 상세 정보를 불러오지 못했습니다.'
  } finally {
    adminDetailBusy.value = false
  }
}

function selectAdminUser(user) {
  if (adminSelectedUserId.value === user.id && adminUserDetail.value) {
    adminSelectedUserId.value = null
    adminUserDetail.value = null
    return
  }

  void loadAdminUserDetail(user.id)
}

async function toggleAdminUserStatus(user) {
  const willDisable = !user.disabledAt
  const confirmed = window.confirm(
    willDisable
      ? `"${user.nickname}" 계정을 비활성화할까요? 즉시 로그인할 수 없고 현재 세션도 종료됩니다.`
      : `"${user.nickname}" 계정을 다시 사용할 수 있게 할까요?`,
  )

  if (!confirmed) {
    return
  }

  adminActionUserId.value = user.id

  try {
    const result = await updateAdminUserStatus(authToken.value, user.id, willDisable)
    adminMessage.value = result.message || '계정 상태를 변경했습니다.'
    await loadAdminDashboard()
    if (adminSelectedUserId.value === user.id) {
      await loadAdminUserDetail(user.id)
    }
  } catch (error) {
    adminMessage.value = error.message || '계정 상태를 변경하지 못했습니다.'
  } finally {
    adminActionUserId.value = null
  }
}

async function revokeAdminSessions(user) {
  const confirmed = window.confirm(`"${user.nickname}" 사용자를 현재 로그인된 모든 기기에서 로그아웃시킬까요?`)

  if (!confirmed) {
    return
  }

  adminActionUserId.value = user.id

  try {
    const result = await revokeAdminUserSessions(authToken.value, user.id)
    adminMessage.value = result.message || '사용자 세션을 정리했습니다.'
    await loadAdminDashboard()
    if (adminSelectedUserId.value === user.id) {
      await loadAdminUserDetail(user.id)
    }
  } catch (error) {
    adminMessage.value = error.message || '사용자 세션을 종료하지 못했습니다.'
  } finally {
    adminActionUserId.value = null
  }
}

async function removeAdminUser(user) {
  const confirmed = window.confirm(`"${user.nickname}" 계정을 삭제할까요? 플래너 기록과 목표 데이터도 함께 삭제됩니다.`)

  if (!confirmed) {
    return
  }

  adminActionUserId.value = user.id

  try {
    const result = await deleteAdminUser(authToken.value, user.id)
    adminMessage.value = result.message || '사용자 계정을 삭제했습니다.'
    await loadAdminDashboard()
    if (adminSelectedUserId.value === user.id) {
      adminSelectedUserId.value = null
      adminUserDetail.value = null
    }
  } catch (error) {
    adminMessage.value = error.message || '사용자 계정을 삭제하지 못했습니다.'
  } finally {
    adminActionUserId.value = null
  }
}

async function loadGoals() {
  if (!authToken.value) {
    return
  }

  goalBusy.value = true

  try {
    const result = await fetchGoals(authToken.value, {
      status: 'all',
    })

    goals.value = result.goals
    goalMessage.value = ''
  } catch (error) {
    goalMessage.value = error.message || '목표를 불러오지 못했습니다.'
  } finally {
    goalBusy.value = false
  }
}

async function submitGoal() {
  if (!goalForm.title.trim() || !goalForm.targetDate) {
    goalMessage.value = '목표 이름과 목표일을 입력해 주세요.'
    return
  }

  if ((goalForm.activeFrom && !goalForm.activeUntil) || (!goalForm.activeFrom && goalForm.activeUntil)) {
    goalMessage.value = '표시 시작일과 종료일은 함께 입력해 주세요.'
    return
  }

  if (goalForm.activeFrom && goalForm.activeUntil && goalForm.activeFrom > goalForm.activeUntil) {
    goalMessage.value = '표시 종료일은 시작일보다 빠를 수 없습니다.'
    return
  }

  const overlappedGoal = findOverlappingGoal({
    activeFrom: goalForm.activeFrom || null,
    activeUntil: goalForm.activeUntil || null,
  })

  if (overlappedGoal) {
    goalMessage.value = `"${overlappedGoal.title}" 목표와 표시 기간이 겹칩니다. D-DAY 기간은 하나만 설정할 수 있습니다.`
    return
  }

  goalBusy.value = true
  goalMessage.value = ''

  try {
    const result = await createGoal(authToken.value, {
      title: goalForm.title.trim(),
      targetDate: goalForm.targetDate,
      activeFrom: goalForm.activeFrom || null,
      activeUntil: goalForm.activeUntil || null,
    })

    await loadGoals()
    resetGoalForm()
    goalQuery.value = ''
    goalMessage.value = result.message || '목표가 추가되었습니다.'
  } catch (error) {
    goalMessage.value = error.message || '목표를 추가하지 못했습니다.'
  } finally {
    goalBusy.value = false
  }
}

function updateGoalFormField({ field, value }) {
  goalForm[field] = value

  if (field === 'targetDate' && !editingGoalId.value) {
    if (!goalForm.activeFrom) {
      goalForm.activeFrom = getTodayKey()
    }

    goalForm.activeUntil = value
  }
}

function startGoalEdit(goal) {
  editingGoalId.value = goal.id
  goalForm.title = goal.title ?? ''
  goalForm.targetDate = goal.targetDate ?? ''
  goalForm.activeFrom = goal.activeFrom ?? ''
  goalForm.activeUntil = goal.activeUntil ?? ''
  goalMessage.value = ''
}

async function saveGoalEdit() {
  if (!editingGoalId.value) {
    return
  }

  if (!goalForm.title.trim() || !goalForm.targetDate) {
    goalMessage.value = '목표 이름과 목표일을 입력해 주세요.'
    return
  }

  if ((goalForm.activeFrom && !goalForm.activeUntil) || (!goalForm.activeFrom && goalForm.activeUntil)) {
    goalMessage.value = '표시 시작일과 종료일은 함께 입력해 주세요.'
    return
  }

  if (goalForm.activeFrom && goalForm.activeUntil && goalForm.activeFrom > goalForm.activeUntil) {
    goalMessage.value = '표시 종료일은 시작일보다 빠를 수 없습니다.'
    return
  }

  const overlappedGoal = findOverlappingGoal({
    activeFrom: goalForm.activeFrom || null,
    activeUntil: goalForm.activeUntil || null,
    excludeGoalId: editingGoalId.value,
  })

  if (overlappedGoal) {
    goalMessage.value = `"${overlappedGoal.title}" 목표와 표시 기간이 겹칩니다. D-DAY 기간은 하나만 설정할 수 있습니다.`
    return
  }

  goalBusy.value = true
  goalMessage.value = ''

  try {
    const result = await updateGoal(authToken.value, editingGoalId.value, {
      title: goalForm.title.trim(),
      targetDate: goalForm.targetDate,
      activeFrom: goalForm.activeFrom || null,
      activeUntil: goalForm.activeUntil || null,
    })

    await loadGoals()
    resetGoalForm()
    goalMessage.value = result.message || '목표가 수정되었습니다.'
  } catch (error) {
    goalMessage.value = error.message || '목표를 수정하지 못했습니다.'
  } finally {
    goalBusy.value = false
  }
}

async function removeGoal(goal) {
  const confirmed = window.confirm(`"${goal.title}" 목표를 삭제할까요? 삭제하면 과거 날짜에서도 더 이상 표시되지 않습니다.`)

  if (!confirmed) {
    return
  }

  goalBusy.value = true
  goalMessage.value = ''

  try {
    const result = await deleteGoal(authToken.value, goal.id)
    await loadGoals()
    if (editingGoalId.value === goal.id) {
      resetGoalForm()
    }
    goalMessage.value = result.message || '목표가 삭제되었습니다.'
  } catch (error) {
    goalMessage.value = error.message || '목표를 삭제하지 못했습니다.'
  } finally {
    goalBusy.value = false
  }
}

function updateProfileField({ field, value }) {
  profileForm[field] = value
}

function updatePasswordField({ field, value }) {
  passwordForm[field] = value
}

function updateAccountDeleteField({ field, value }) {
  accountDeleteForm[field] = value
}

async function submitProfileForm() {
  profileBusy.value = true
  profileMessage.value = ''

  try {
    const result = await updateProfile(authToken.value, {
      nickname: profileForm.nickname,
      email: profileForm.email,
    })

    currentUser.value = result.user
    persistAuthState({
      token: authToken.value,
      user: result.user,
      persist: authPersist.value,
    })
    syncProfileForm()
    await loadAdminDashboard()
    if (!isAdmin.value && screenMode.value === 'admin') {
      screenMode.value = 'planner'
    }
    profileMessage.value = '프로필이 저장되었습니다.'
  } catch (error) {
    profileMessage.value = error.message || '프로필을 저장하지 못했습니다.'
  } finally {
    profileBusy.value = false
  }
}

async function submitPasswordForm() {
  if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
    passwordMessage.value = '모든 비밀번호 항목을 입력해 주세요.'
    return
  }

  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    passwordMessage.value = '새 비밀번호 확인이 일치하지 않습니다.'
    return
  }

  passwordBusy.value = true
  passwordMessage.value = ''

  try {
    await updatePassword(authToken.value, {
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword,
    })
    resetPasswordForm()
    passwordMessage.value = '비밀번호가 변경되었습니다.'
  } catch (error) {
    passwordMessage.value = error.message || '비밀번호를 변경하지 못했습니다.'
  } finally {
    passwordBusy.value = false
  }
}

async function submitDeleteAccount() {
  if (!accountDeleteForm.currentPassword) {
    accountDeleteMessage.value = '회원 탈퇴를 위해 현재 비밀번호를 입력해 주세요.'
    return
  }

  const confirmed = window.confirm('정말로 회원 탈퇴하시겠습니까? 작성한 플래너와 목표 데이터도 함께 삭제됩니다.')

  if (!confirmed) {
    return
  }

  accountDeleteBusy.value = true
  accountDeleteMessage.value = ''

  try {
    const result = await deleteAccount(authToken.value, {
      currentPassword: accountDeleteForm.currentPassword,
    })
    resetAccountDeleteForm()
    clearAuthenticatedState()
    authMessage.value = ''
    window.alert(result.message || '회원 탈퇴가 완료되었습니다.')
  } catch (error) {
    accountDeleteMessage.value = error.message || '회원 탈퇴를 처리하지 못했습니다.'
  } finally {
    accountDeleteBusy.value = false
  }
}

function replacePlannerRecords(nextRecords) {
  Object.keys(plannerRecords).forEach((key) => {
    delete plannerRecords[key]
  })

  Object.entries(nextRecords).forEach(([key, record]) => {
    plannerRecords[key] = record
  })
}

function restoreLocalPlannerRecords() {
  replacePlannerRecords(createInitialPlannerRecords(plannerSeed, normalizeRecord))
  selectedDate.value = new Date()
  calendarViewDate.value = new Date(selectedDate.value)
}

function findRecordKey(record) {
  return Object.entries(plannerRecords).find(([, value]) => value === record)?.[0] ?? null
}

function clearPendingSyncTimers() {
  syncTimers.forEach((timerId) => {
    window.clearTimeout(timerId)
  })
  syncTimers.clear()
}

function schedulePlannerSyncForRecord(record) {
  const recordKey = findRecordKey(record)

  if (!recordKey) {
    return
  }

  schedulePlannerSync(recordKey)
}

function schedulePlannerSync(recordKey) {
  if (!isAuthenticated.value || isHydratingRemoteRecords) {
    return
  }

  if (syncTimers.has(recordKey)) {
    window.clearTimeout(syncTimers.get(recordKey))
  }

  setSyncFeedback('syncing', '클라우드 저장 중...', {
    sticky: true,
  })

  const timerId = window.setTimeout(async () => {
    syncTimers.delete(recordKey)

    try {
      const record = plannerRecords[recordKey]

      if (!record) {
        if (syncTimers.size === 0) {
          setSyncFeedback('cloud', '클라우드 동기화 연결됨')
        }
        return
      }

      if (!hasPlannerContent(record)) {
        await deletePlannerEntry(authToken.value, recordKey)

        if (syncTimers.size === 0) {
          setSyncFeedback('cloud', '클라우드에서 삭제됨')
        }
        return
      }

      await savePlannerEntry(authToken.value, recordKey, {
        ...record,
        tasks: record.tasks.map((task) => ({ ...task })),
        memo: record.memo.map((item) => ({ ...item })),
        timetable: [...record.timetable],
      })

      if (syncTimers.size === 0) {
        setSyncFeedback('cloud', '클라우드에 저장됨')
      }
    } catch (error) {
      setSyncFeedback('error', error.message || '클라우드 저장에 실패했습니다.', {
        duration: 3200,
      })
    }
  }, 500)

  syncTimers.set(recordKey, timerId)
}

async function hydratePlannerRecordsFromApi() {
  if (!authToken.value) {
    return
  }

  isHydratingRemoteRecords = true
  setSyncFeedback('syncing', '클라우드 데이터를 불러오는 중...', {
    sticky: true,
  })

  try {
    const result = await fetchPlannerEntries(authToken.value)
    const remoteRecords = {}

    result.entries.forEach((entry) => {
      remoteRecords[entry.entryDate] = normalizeRecord(entry.payload)
    })

    replacePlannerRecords(remoteRecords)

    setSyncFeedback('cloud', '클라우드 동기화 연결됨')
  } catch (error) {
    setSyncFeedback('error', error.message || '클라우드 데이터를 불러오지 못했습니다.', {
      duration: 3200,
    })
  } finally {
    isHydratingRemoteRecords = false
  }
}

function applyPrintPageStyle(layout) {
  if (typeof document === 'undefined') {
    return
  }

  const pageRule =
    layout === 'double'
      ? '@page { size: A4 landscape; margin: 0; }'
      : '@page { size: A4 portrait; margin: 0; }'

  if (!printPageStyleElement) {
    printPageStyleElement = document.createElement('style')
    printPageStyleElement.setAttribute('data-print-page-style', 'true')
    document.head.appendChild(printPageStyleElement)
  }

  printPageStyleElement.textContent = pageRule
  document.body.dataset.printLayout = layout
}

async function printSelectedPlanner(layout = 'single') {
  printLayout.value = layout
  applyPrintPageStyle(layout)
  await nextTick()
  window.print()
}

async function printPlannerRange() {
  printLayout.value = printRangeLayout.value
  applyPrintPageStyle(printRangeLayout.value)
  await nextTick()
  window.print()
}

async function initializeAppSession() {
  await openVerificationFromUrl()
  openPasswordResetFromUrl()
  await restoreAuthSession()
}

onMounted(() => {
  resetGoalForm()
  setSyncFeedback('local', '로그인 후 클라우드 저장을 사용할 수 있습니다.', {
    visible: false,
  })
  updateWindowWidth()
  window.addEventListener('resize', updateWindowWidth)
  window.addEventListener('keydown', handleGlobalKeydown)
  initializeAppSession()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateWindowWidth)
  window.removeEventListener('keydown', handleGlobalKeydown)
})
</script>

<template>
  <main class="min-h-screen px-4 py-6 text-ink sm:px-6 lg:px-10 xl:h-screen xl:overflow-hidden">
    <div
      class="print-root mx-auto flex max-w-[1760px] flex-col gap-6"
      :class="isAuthenticated ? 'xl:h-[calc(100vh-3rem)] xl:grid xl:grid-cols-[300px_minmax(0,1fr)] xl:items-start' : 'min-h-[calc(100vh-3rem)] items-center justify-center'"
    >
      <section
        v-if="isAuthenticated && !showInlineLeftSidebar"
        class="print-hidden rounded-[28px] border border-white/60 bg-white/78 p-4 shadow-[0_18px_60px_rgba(28,25,23,0.08)] backdrop-blur"
      >
        <div class="flex items-start justify-between gap-4">
          <div>
            <p class="text-[10px] font-bold uppercase tracking-[0.22em] text-stone-500">10 Minute Planner</p>
            <p class="mt-2 text-lg font-semibold tracking-[-0.04em] text-stone-900">
              {{ screenMode.toUpperCase() }}
            </p>
            <p class="mt-1 text-[11px] font-semibold text-stone-500">
              {{ currentUser?.nickname }} 님의 플래너
            </p>
          </div>
          <button
            type="button"
            class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[11px] font-bold tracking-[0.16em] text-stone-700 transition hover:border-stone-400 hover:text-ink"
            @click="openLeftPanel"
          >
            MENU
          </button>
        </div>
      </section>

      <Transition name="panel-fade">
        <div
          v-if="isAuthenticated && !showInlineLeftSidebar && leftPanelOpen"
          class="fixed inset-0 z-40 bg-stone-900/22 backdrop-blur-[2px]"
          @click="closeLeftPanel"
        />
      </Transition>

      <aside
        v-if="isAuthenticated && showInlineLeftSidebar"
        class="scrollbar-hide print-hidden rounded-[28px] border border-white/60 bg-white/70 p-5 backdrop-blur sm:p-6 xl:h-full xl:overflow-y-auto"
      >
        <div class="space-y-6">
          <div class="overflow-hidden rounded-[28px] border border-stone-200 bg-[linear-gradient(145deg,rgba(255,255,255,0.96),rgba(246,238,228,0.92))] p-5 shadow-[0_18px_40px_rgba(28,25,23,0.06)]">
            <div class="flex items-center justify-between gap-3">
              <p class="text-[11px] font-bold uppercase tracking-[0.28em] text-stone-500">10 Minute Planner</p>
            </div>
            <div class="mt-6 space-y-3">
              <h1 class="text-[28px] font-semibold leading-[1.1] tracking-[-0.06em] text-stone-900">
                오늘의 흐름을
                <br>
                가볍게 기록하세요
              </h1>
              <p class="max-w-[18rem] text-[13px] font-semibold leading-6 tracking-[0.02em] text-stone-600">
                짧게 적고, 바로 체크하고, 날짜를 넘기며 하루의 리듬을 이어가는 플래너입니다.
              </p>
            </div>
          </div>

          <section class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <template v-if="isAuthenticated">
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">SIGNED IN</p>
              <p class="mt-2 text-lg font-semibold tracking-[-0.03em] text-stone-900">{{ currentUser.nickname }}</p>
              <p class="mt-1 text-sm font-semibold text-stone-500">{{ currentUser.email }}</p>
              <button
                type="button"
                class="mt-4 w-full rounded-full border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.16em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="logout"
              >
                LOGOUT
              </button>
            </template>
            <template v-else>
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">ACCOUNT</p>
              <p class="mt-2 text-sm font-semibold leading-6 text-stone-700">
                로그인 후 문서, 통계, 목표 관리가 모두 계정 기준으로 연결됩니다.
              </p>
              <div class="mt-4 grid gap-2">
                <button
                  type="button"
                  class="w-full rounded-full border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.16em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                  @click="openAuthDialog('login')"
                >
                  LOGIN
                </button>
                <button
                  type="button"
                  class="w-full rounded-full border border-stone-900 bg-stone-900 px-4 py-3 text-xs font-bold tracking-[0.16em] text-white transition hover:bg-stone-700"
                  @click="openAuthDialog('signup')"
                >
                  SIGN UP
                </button>
              </div>
            </template>
          </section>

          <section v-if="isAuthenticated" class="rounded-[24px] border border-stone-200 bg-white/85 p-4 shadow-[0_10px_30px_rgba(28,25,23,0.04)]">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">NAVIGATION</p>
            <div class="mt-4 grid gap-2">
              <button
                type="button"
                class="rounded-[20px] border px-4 py-4 text-left transition"
                :class="screenMode === 'planner' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                @click="setScreenMode('planner')"
              >
                <p class="text-xs font-bold tracking-[0.18em]">PLANNER</p>
                <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'planner' ? 'text-stone-200' : 'text-stone-500'">오늘 문서 작성과 캘린더 이동</p>
              </button>
              <button
                type="button"
                class="rounded-[20px] border px-4 py-4 text-left transition"
                :class="screenMode === 'stats' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                @click="setScreenMode('stats')"
              >
                <p class="text-xs font-bold tracking-[0.18em]">STATS</p>
                <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'stats' ? 'text-stone-200' : 'text-stone-500'">기간별 집중 시간과 완료율</p>
              </button>
              <button
                type="button"
                class="rounded-[20px] border px-4 py-4 text-left transition"
                :class="screenMode === 'goals' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                @click="setScreenMode('goals')"
              >
                <p class="text-xs font-bold tracking-[0.18em]">GOALS</p>
                <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'goals' ? 'text-stone-200' : 'text-stone-500'">D-DAY 목표와 표시 기간 관리</p>
              </button>
              <button
                type="button"
                class="rounded-[20px] border px-4 py-4 text-left transition"
                :class="screenMode === 'settings' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                @click="setScreenMode('settings')"
              >
                <p class="text-xs font-bold tracking-[0.18em]">SETTINGS</p>
                <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'settings' ? 'text-stone-200' : 'text-stone-500'">계정 정보와 비밀번호 수정</p>
              </button>
              <button
                v-if="isAdmin"
                type="button"
                class="rounded-[20px] border px-4 py-4 text-left transition"
                :class="screenMode === 'admin' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                @click="setScreenMode('admin')"
              >
                <p class="text-xs font-bold tracking-[0.18em]">ADMIN</p>
                <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'admin' ? 'text-stone-200' : 'text-stone-500'">사용자 현황과 운영 통계 확인</p>
              </button>
            </div>
          </section>

          <section v-if="isAuthenticated && screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">보기 방식</p>
            <div class="mt-4 grid gap-2">
              <button
                type="button"
                class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="viewMode === 'focus' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="setViewMode('focus')"
              >
                1페이지 + 정보
              </button>
              <button
                type="button"
                class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
                :class="viewMode === 'spread' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                @click="setViewMode('spread')"
              >
                2페이지 펼침
              </button>
            </div>
          </section>

          <section v-if="isAuthenticated && screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">날짜 이동</p>
            <div class="mt-4 grid gap-2">
              <button
                type="button"
                class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="shiftDate(-1)"
              >
                이전 날
              </button>
              <button
                type="button"
                class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="shiftDate(1)"
              >
                다음 날
              </button>
            </div>
          </section>

          <section v-if="isAuthenticated && screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
            <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">인쇄</p>
            <div class="mt-4 grid gap-2">
              <button
                type="button"
                class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="openPrintDialog"
              >
                PRINT
              </button>
            </div>
          </section>
        </div>
      </aside>

      <Transition name="drawer-left">
        <aside
          v-if="isAuthenticated && !showInlineLeftSidebar && leftPanelOpen"
          class="scrollbar-hide print-hidden fixed inset-y-4 left-4 z-50 w-[min(360px,calc(100vw-2rem))] overflow-y-auto rounded-[28px] border border-white/60 bg-white/70 p-5 shadow-[0_18px_60px_rgba(28,25,23,0.14)] backdrop-blur sm:p-6"
        >
          <div class="space-y-6">
            <div class="flex items-center justify-between rounded-[20px] border border-stone-200 bg-white/85 px-4 py-3">
              <div>
                <p class="text-[10px] font-bold uppercase tracking-[0.2em] text-stone-500">Navigation</p>
                <p class="mt-1 text-sm font-semibold text-stone-900">{{ currentUser?.nickname }}</p>
              </div>
              <button
                type="button"
                class="rounded-full border border-stone-200 px-3 py-1 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="closeLeftPanel"
              >
                CLOSE
              </button>
            </div>

            <div class="overflow-hidden rounded-[28px] border border-stone-200 bg-[linear-gradient(145deg,rgba(255,255,255,0.96),rgba(246,238,228,0.92))] p-5 shadow-[0_18px_40px_rgba(28,25,23,0.06)]">
              <div class="flex items-center justify-between gap-3">
                <p class="text-[11px] font-bold uppercase tracking-[0.28em] text-stone-500">10 Minute Planner</p>
              </div>
              <div class="mt-6 space-y-3">
                <h1 class="text-[28px] font-semibold leading-[1.1] tracking-[-0.06em] text-stone-900">
                  오늘의 흐름을
                  <br>
                  가볍게 기록하세요
                </h1>
                <p class="max-w-[18rem] text-[13px] font-semibold leading-6 tracking-[0.02em] text-stone-600">
                  짧게 적고, 바로 체크하고, 날짜를 넘기며 하루의 리듬을 이어가는 플래너입니다.
                </p>
              </div>
            </div>

            <section class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">SIGNED IN</p>
              <p class="mt-2 text-lg font-semibold tracking-[-0.03em] text-stone-900">{{ currentUser.nickname }}</p>
              <p class="mt-1 text-sm font-semibold text-stone-500">{{ currentUser.email }}</p>
              <button
                type="button"
                class="mt-4 w-full rounded-full border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.16em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="logout"
              >
                LOGOUT
              </button>
            </section>

            <section class="rounded-[24px] border border-stone-200 bg-white/85 p-4 shadow-[0_10px_30px_rgba(28,25,23,0.04)]">
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">NAVIGATION</p>
              <div class="mt-4 grid gap-2">
                <button
                  type="button"
                  class="rounded-[20px] border px-4 py-4 text-left transition"
                  :class="screenMode === 'planner' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                  @click="setScreenMode('planner')"
                >
                  <p class="text-xs font-bold tracking-[0.18em]">PLANNER</p>
                  <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'planner' ? 'text-stone-200' : 'text-stone-500'">오늘 문서 작성과 캘린더 이동</p>
                </button>
                <button
                  type="button"
                  class="rounded-[20px] border px-4 py-4 text-left transition"
                  :class="screenMode === 'stats' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                  @click="setScreenMode('stats')"
                >
                  <p class="text-xs font-bold tracking-[0.18em]">STATS</p>
                  <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'stats' ? 'text-stone-200' : 'text-stone-500'">기간별 집중 시간과 완료율</p>
                </button>
                <button
                  type="button"
                  class="rounded-[20px] border px-4 py-4 text-left transition"
                  :class="screenMode === 'goals' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                  @click="setScreenMode('goals')"
                >
                  <p class="text-xs font-bold tracking-[0.18em]">GOALS</p>
                  <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'goals' ? 'text-stone-200' : 'text-stone-500'">D-DAY 목표와 표시 기간 관리</p>
                </button>
                <button
                  type="button"
                  class="rounded-[20px] border px-4 py-4 text-left transition"
                  :class="screenMode === 'settings' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                  @click="setScreenMode('settings')"
                >
                  <p class="text-xs font-bold tracking-[0.18em]">SETTINGS</p>
                  <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'settings' ? 'text-stone-200' : 'text-stone-500'">계정 정보와 비밀번호 수정</p>
                </button>
                <button
                  v-if="isAdmin"
                  type="button"
                  class="rounded-[20px] border px-4 py-4 text-left transition"
                  :class="screenMode === 'admin' ? 'border-stone-900 bg-stone-900 text-white shadow-[0_12px_24px_rgba(28,25,23,0.18)]' : 'border-stone-200 bg-white text-stone-700 hover:border-stone-400'"
                  @click="setScreenMode('admin')"
                >
                  <p class="text-xs font-bold tracking-[0.18em]">ADMIN</p>
                  <p class="mt-1 text-[11px] font-semibold tracking-[0.04em]" :class="screenMode === 'admin' ? 'text-stone-200' : 'text-stone-500'">사용자 현황과 운영 통계 확인</p>
                </button>
              </div>
            </section>

            <section v-if="screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">보기 방식</p>
              <div class="mt-4 grid gap-2">
                <button
                  type="button"
                  class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
                  :class="viewMode === 'focus' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                  @click="setViewMode('focus')"
                >
                  1페이지 + 정보
                </button>
                <button
                  type="button"
                  class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
                  :class="viewMode === 'spread' ? 'bg-stone-900 text-white' : 'bg-stone-100 text-stone-500'"
                  @click="setViewMode('spread')"
                >
                  2페이지 펼침
                </button>
              </div>
            </section>

            <section v-if="screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">날짜 이동</p>
              <div class="mt-4 grid gap-2">
                <button
                  type="button"
                  class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                  @click="shiftDate(-1)"
                >
                  이전 날
                </button>
                <button
                  type="button"
                  class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                  @click="shiftDate(1)"
                >
                  다음 날
                </button>
              </div>
            </section>

            <section v-if="screenMode === 'planner'" class="rounded-[24px] border border-stone-200 bg-white/80 p-4">
              <p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">인쇄</p>
              <div class="mt-4 grid gap-2">
                <button
                  type="button"
                  class="rounded-2xl border border-stone-200 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                  @click="openPrintDialog"
                >
                  PRINT
                </button>
              </div>
            </section>
          </div>
        </aside>
      </Transition>

      <div class="min-w-0 space-y-6" :class="isAuthenticated ? 'xl:h-full xl:overflow-hidden' : 'w-full'">
      <section
        v-if="!isAuthenticated && !demoMode"
        class="scrollbar-hide print-hidden mx-auto w-full max-w-3xl rounded-[30px] border border-white/70 bg-white/72 px-5 py-7 shadow-[0_24px_80px_rgba(28,25,23,0.08)] sm:px-8 sm:py-9"
      >
        <div class="mx-auto flex max-w-2xl flex-col gap-6 text-center">
          <div>
            <p class="text-[11px] font-bold uppercase tracking-[0.28em] text-stone-500">MEMBERS ONLY</p>
            <h2 class="mt-3 text-3xl font-semibold tracking-[-0.05em] text-stone-900 sm:text-4xl">
              10 MINITES PLANNER
            </h2>
            <p class="mx-auto mt-3 max-w-xl text-sm leading-7 text-stone-600 sm:text-base">
              장기 목표, 할 일, 집중 시간, 짧은 코멘트를 한 장의 다이어리로 남기고<br />내일의 첫 작업까지 이어가세요.
            </p>
          </div>

          <div class="mx-auto grid w-full max-w-xl gap-0 border-y border-stone-200 text-left">
            <p class="flex items-center justify-between gap-4 border-b border-stone-200 py-3 text-sm font-semibold text-stone-700">
              <span>날짜별 기록 저장</span>
              <span class="text-[10px] font-bold tracking-[0.18em] text-stone-400">SAVE</span>
            </p>
            <p class="flex items-center justify-between gap-4 border-b border-stone-200 py-3 text-sm font-semibold text-stone-700">
              <span>통계와 목표 관리</span>
              <span class="text-[10px] font-bold tracking-[0.18em] text-stone-400">STATS</span>
            </p>
            <p class="flex items-center justify-between gap-4 py-3 text-sm font-semibold text-stone-700">
              <span>출력용 다이어리 유지</span>
              <span class="text-[10px] font-bold tracking-[0.18em] text-stone-400">PRINT</span>
            </p>
          </div>

          <div class="grid w-full gap-3 sm:mx-auto sm:max-w-2xl sm:grid-cols-3">
            <button
              type="button"
              class="h-12 w-full rounded-full border border-stone-300 bg-white px-6 text-xs font-bold tracking-[0.18em] text-stone-700 transition hover:border-stone-500 hover:text-stone-900"
              @click="demoMode = true; demoDayOffset = 0"
            >
              DEMO VIEW
            </button>
            <button
              type="button"
              class="h-12 w-full rounded-full border border-stone-300 bg-white px-6 text-xs font-bold tracking-[0.18em] text-stone-700 transition hover:border-stone-500 hover:text-stone-900"
              @click="openAuthDialog('login')"
            >
              LOGIN
            </button>
            <button
              type="button"
              class="h-12 w-full rounded-full border border-stone-900 bg-stone-900 px-6 text-xs font-bold tracking-[0.18em] text-white transition hover:bg-stone-700"
              @click="openAuthDialog('signup')"
            >
              SIGN UP
            </button>
          </div>
        </div>
      </section>

      <section
        v-else-if="!isAuthenticated && demoMode"
        class="print-hidden mx-auto grid w-full max-w-6xl gap-5 rounded-[30px] border border-white/70 bg-white/55 p-4 shadow-[0_24px_80px_rgba(28,25,23,0.08)] sm:p-6 xl:h-[calc(100vh-3rem)] xl:min-h-0 xl:overflow-hidden xl:grid-cols-[minmax(0,1fr)_280px]"
      >
        <div class="min-h-0 overflow-y-auto overflow-x-auto overscroll-contain rounded-[26px] border border-white/70 bg-white/45 p-3 sm:p-4 xl:h-full">
          <div class="mx-auto w-[762px] max-w-none">
            <PlannerPage
              readonly
              :date-main="demoDateDisplay.main"
              :date-weekday="demoDateDisplay.weekday"
              :date-weekday-tone="demoDateDisplay.weekdayTone"
              :dday="demoDday"
              :show-dday="true"
              :comment="demoPlanner.comment"
              :total-time="formatTotalTimeKorean(demoPlanner)"
              :tasks="demoPlanner.tasks"
              :memo="demoPlanner.memo"
              :hours="hours"
              :timetable="demoPlanner.timetable"
            />
          </div>
        </div>

        <aside class="min-h-0 overflow-y-auto rounded-[26px] border border-white/70 bg-[#f7f2ea]/95 p-4 xl:h-full">
          <p class="text-[10px] font-bold uppercase tracking-[0.24em] text-stone-500">DEMO PAGE</p>
          <h2 class="mt-3 text-2xl font-semibold tracking-[-0.05em] text-stone-900">
            3일치 샘플로<br>흐름을 먼저 보기
          </h2>
          <p class="mt-3 text-sm font-semibold leading-6 text-stone-600">
            이 화면은 저장되지 않는 샘플입니다. 어제, 오늘, 내일 기록이 어떻게 이어지는지 가볍게 확인해보세요.
          </p>

          <div class="mt-5 grid gap-2">
            <button
              v-for="item in [
                { label: '어제', offset: -1 },
                { label: '오늘', offset: 0 },
                { label: '내일', offset: 1 },
              ]"
              :key="item.offset"
              type="button"
              class="rounded-2xl border px-4 py-3 text-left text-xs font-bold tracking-[0.14em] transition"
              :class="demoDayOffset === item.offset ? 'border-stone-900 bg-stone-900 text-white' : 'border-stone-200 bg-white text-stone-600 hover:border-stone-400 hover:text-stone-900'"
              @click="demoDayOffset = item.offset"
            >
              {{ item.label }}
            </button>
          </div>

          <div class="mt-5 grid gap-2 border-t border-stone-200 pt-5">
            <button
              type="button"
              class="rounded-full border border-stone-900 bg-stone-900 px-5 py-3 text-xs font-bold tracking-[0.16em] text-white transition hover:bg-stone-700"
              @click="openAuthDialog('signup')"
            >
              SIGN UP
            </button>
            <button
              type="button"
              class="rounded-full border border-stone-300 bg-white px-5 py-3 text-xs font-bold tracking-[0.16em] text-stone-700 transition hover:border-stone-500 hover:text-stone-900"
              @click="openAuthDialog('login')"
            >
              LOGIN
            </button>
            <button
              type="button"
              class="rounded-full px-5 py-3 text-xs font-bold tracking-[0.16em] text-stone-500 transition hover:text-stone-900"
              @click="demoMode = false"
            >
              BACK
            </button>
          </div>
        </aside>
      </section>

      <section
        v-else-if="screenMode === 'planner' && viewMode === 'focus'"
        class="print-hidden relative grid gap-6 xl:h-full xl:min-h-0"
        :class="showInlineFocusSidebar ? 'xl:grid-cols-[minmax(0,1fr)_minmax(0,360px)] 2xl:grid-cols-[minmax(0,1fr)_640px]' : ''"
      >
        <Transition name="panel-fade">
          <div
            v-if="isOverlayFocusSidebar && rightPanelOpen"
            class="fixed inset-0 z-30 bg-stone-900/18 backdrop-blur-[2px]"
            @click="closeRightPanel"
          />
        </Transition>

        <div class="scrollbar-hide print-target border border-white/60 bg-white/45 xl:h-full xl:min-h-0 xl:overflow-y-auto xl:pr-3" :class="isCompactMobile ? 'rounded-[24px] p-3' : 'rounded-[28px] p-4'">
          <div v-if="isOverlayFocusSidebar" class="mb-4 flex justify-end">
            <button
              type="button"
              class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[11px] font-bold tracking-[0.16em] text-stone-700 transition hover:border-stone-400 hover:text-ink"
              @click="openRightPanel"
            >
              {{ isCompactMobile ? 'INFO' : 'OPEN SIDE PANEL' }}
            </button>
          </div>
          <PlannerPage
            :date-main="selectedDateDisplay.main"
            :date-weekday="selectedDateDisplay.weekday"
            :date-weekday-tone="selectedDateDisplay.weekdayTone"
            :dday="plannerDday"
            :show-dday="showPlannerDday"
            :comment="planner.comment"
            :total-time="formatTotalTimeKorean(planner)"
            :tasks="planner.tasks"
            :memo="planner.memo"
            :hours="hours"
            :timetable="planner.timetable"
            @update:comment="updateComment(planner, $event)"
            @update:task-label="updateTaskLabel(planner, $event)"
            @update:task-title="updateTaskTitle(planner, $event)"
            @toggle:task="toggleTask(planner, $event)"
            @clear:tasks="clearTasks(planner, $event)"
            @update:memo-label="updateMemoLabel(planner, $event)"
            @update:memo="updateMemo(planner, $event)"
            @update:timetable="updateTimetable(planner, $event)"
          />
        </div>

        <aside
          v-if="showInlineFocusSidebar"
          class="scrollbar-hide print-hidden rounded-[28px] border border-white/60 bg-[#f7f2ea]/95 p-3 xl:h-full xl:min-h-0 xl:overflow-y-auto"
          :class="[focusSidebarOuterClass]"
        >
          <div v-if="!showInlineFocusSidebar" class="mb-3 flex items-center justify-between rounded-[18px] border border-stone-200 bg-white/90 px-4 py-3">
            <p class="text-[11px] font-bold tracking-[0.18em] text-ink">SIDE PANEL</p>
            <button
              type="button"
              class="rounded-full border border-stone-200 px-3 py-1 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
              @click="closeRightPanel"
            >
              CLOSE
            </button>
          </div>

          <div class="grid gap-4 rounded-[22px] p-2" :class="focusSidebarGridClass">
            <div class="grid gap-4" :class="isWideFocusSidebar ? '' : 'max-w-[360px]'">
              <section class="2xl:w-[280px]">
                <MiniCalendar
                  :month-label="monthLabel"
                  :year-label="yearLabel"
                  :days="calendarDays"
                  :selected-key="toKey(selectedDate)"
                  :marked-keys="markedDateKeys"
                  @shift-month="shiftCalendarMonth"
                  @shift-year="shiftCalendarYear"
                  @go-today="selectDate(new Date())"
                  @select="selectDate"
                />
              </section>

              <section class="rounded-[24px] border border-stone-200 bg-white/88 p-4 shadow-[0_12px_36px_rgba(28,25,23,0.05)]">
                <div class="grid gap-3">
                  <div class="flex items-center justify-between gap-3">
                    <div class="flex items-center gap-2">
                      <p class="text-[11px] font-bold tracking-[0.22em] text-ink">TASK LABELS</p>
                      <GuideTooltip
                        title="Task Labels"
                        description="번호가 필요한 날만 빠르게 채우고, 필요 없으면 바로 비울 수 있습니다."
                        :visible="isGuideTooltipVisible('task-labels')"
                        @dismiss="dismissGuideTooltip('task-labels')"
                      />
                    </div>
                    <button
                      type="button"
                      class="relative h-8 w-16 shrink-0 rounded-full transition-colors duration-300 ease-out"
                      :class="areTaskLabelsNumbered(planner) ? 'bg-stone-900' : 'bg-stone-300'"
                      @click="areTaskLabelsNumbered(planner) ? clearTaskLabels(planner) : fillTaskLabelsWithNumbers(planner)"
                    >
                      <span
                        class="absolute left-1 top-1 h-6 w-6 transform-gpu rounded-full bg-white shadow-sm transition-transform duration-300 ease-out will-change-transform"
                        :class="areTaskLabelsNumbered(planner) ? 'translate-x-8' : 'translate-x-0'"
                      />
                    </button>
                  </div>

                  <div class="flex items-center justify-between gap-3 border-t border-stone-200 pt-3">
                    <div class="flex items-center gap-2">
                      <p class="text-[11px] font-bold tracking-[0.22em] text-ink">D-DAY 사용</p>
                      <GuideTooltip
                        title="D-Day"
                        description="현재 날짜에 적용된 목표가 있을 때만 본문 D-DAY 표시를 켜고 끌 수 있습니다. 목표는 GOALS 화면에서 표시 기간을 지정하면 자동으로 연결됩니다."
                        :visible="isGuideTooltipVisible('planner-dday')"
                        @dismiss="dismissGuideTooltip('planner-dday')"
                      />
                    </div>
                    <button
                      type="button"
                      class="relative h-8 w-16 shrink-0 rounded-full transition-colors duration-300 ease-out disabled:cursor-not-allowed disabled:opacity-50"
                      :class="plannerGoalToggleOn ? 'bg-stone-900' : 'bg-stone-300'"
                      :disabled="!hasActiveGoalForSelectedDate"
                      @click="updateGoalEnabled(planner, !plannerGoalToggleOn)"
                    >
                      <span
                        class="absolute left-1 top-1 h-6 w-6 transform-gpu rounded-full bg-white shadow-sm transition-transform duration-300 ease-out will-change-transform"
                        :class="plannerGoalToggleOn ? 'translate-x-8' : 'translate-x-0'"
                      />
                    </button>
                  </div>
                </div>
              </section>

              <section class="rounded-[24px] border border-stone-200 bg-white/88 p-4 shadow-[0_12px_36px_rgba(28,25,23,0.05)]">
                <div class="flex items-center gap-2">
                  <p class="text-[11px] font-bold tracking-[0.22em] text-ink">TIME TABLE 복사</p>
                  <GuideTooltip
                    title="Time Table Copy"
                    description="규칙적인 생활 패턴이면 특정 날짜의 타임테이블을 다른 날짜에 그대로 복사할 수 있습니다."
                    :visible="isGuideTooltipVisible('timetable-copy')"
                    @dismiss="dismissGuideTooltip('timetable-copy')"
                  />
                </div>

                <div class="mt-4 grid gap-3">
                  <label class="grid gap-2">
                    <span class="text-[10px] font-bold tracking-[0.14em] text-stone-500">복사할 날짜</span>
                    <div class="grid gap-2 sm:grid-cols-[minmax(0,1fr)_auto]">
                      <input
                        v-model="timetableCopyForm.sourceDate"
                        type="date"
                        class="h-11 rounded-2xl border border-stone-200 bg-white px-4 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
                      />
                      <button
                        type="button"
                        class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[10px] font-bold tracking-[0.12em] text-stone-600 transition hover:border-stone-400 hover:text-stone-900"
                        @click="useSelectedDateAsTimetableSource"
                      >
                        현재 날짜
                      </button>
                    </div>
                  </label>

                  <label class="grid gap-2">
                    <span class="text-[10px] font-bold tracking-[0.14em] text-stone-500">붙여넣을 날짜</span>
                    <div class="grid gap-2 sm:grid-cols-[minmax(0,1fr)_auto]">
                      <input
                        v-model="timetableCopyForm.targetDate"
                        type="date"
                        class="h-11 rounded-2xl border border-stone-200 bg-white px-4 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
                      />
                      <button
                        type="button"
                        class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[10px] font-bold tracking-[0.12em] text-stone-600 transition hover:border-stone-400 hover:text-stone-900"
                        @click="useSelectedDateAsTimetableTarget"
                      >
                        현재 날짜
                      </button>
                    </div>
                  </label>
                </div>

                <button
                  type="button"
                  class="mt-4 w-full rounded-full border border-stone-900 bg-stone-900 px-4 py-3 text-xs font-bold tracking-[0.14em] text-white transition hover:bg-stone-700"
                  @click="copyTimetableBetweenDates"
                >
                  타임테이블 복사하기
                </button>

                <p
                  v-if="timetableCopyMessage"
                  class="mt-3 rounded-2xl border border-stone-200 bg-white px-4 py-3 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600"
                >
                  {{ timetableCopyMessage }}
                </p>
              </section>

            </div>

            <div class="grid gap-4" :class="isWideFocusSidebar ? '' : 'max-w-[360px]'">
              <section class="rounded-[24px] border border-stone-200 bg-white/82 p-5 shadow-[0_12px_36px_rgba(28,25,23,0.05)]">
                <article>
                  <p class="text-[11px] font-bold tracking-[0.22em] text-ink">NEXT DAY</p>
                  <div class="mt-5 space-y-3">
                    <p class="text-lg font-semibold tracking-[-0.04em] text-stone-900">
                      <span>{{ secondaryDateDisplay.main }}</span>
                      <span class="ml-1" :class="secondaryDateDisplay.weekdayTone">{{ secondaryDateDisplay.weekday }}</span>
                    </p>
                    <p class="text-[11px] font-semibold tracking-[0.08em] text-stone-600">
                      {{ nextDaySummary }}
                    </p>
                  </div>

                  <div class="mt-5 border-t border-stone-200 pt-5">
                    <p class="text-[11px] font-bold tracking-[0.22em] text-ink">READ NEXT</p>
                    <div class="mt-3 grid gap-3">
                      <p
                        v-for="item in readNextItems"
                        :key="item"
                        class="rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-4 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-700"
                      >
                        {{ item || ' ' }}
                      </p>
                    </div>
                    <button
                      type="button"
                      class="mt-3 w-full rounded-full border border-stone-900 bg-stone-900 px-4 py-3 text-xs font-bold tracking-[0.14em] text-white transition hover:bg-stone-700 disabled:cursor-not-allowed disabled:border-stone-200 disabled:bg-stone-200 disabled:text-stone-500"
                      :disabled="incompleteTasks.length === 0"
                      @click="carryIncompleteTasksToNextDay"
                    >
                      미완료 항목 이월하기
                    </button>
                    <p
                      v-if="carryoverMessage"
                      class="mt-3 rounded-2xl border border-stone-200 bg-white px-4 py-3 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600"
                    >
                      {{ carryoverMessage }}
                    </p>
                  </div>

                  <div class="mt-5 border-t border-stone-200 pt-5">
                    <p class="text-[11px] font-bold tracking-[0.22em] text-ink">PREV SNAPSHOT</p>
                    <div class="mt-3 grid gap-3">
                      <p
                        v-for="item in prevSnapshotItems"
                        :key="item"
                        class="rounded-2xl border border-stone-200 bg-white px-4 py-4 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-700"
                      >
                        {{ item || ' ' }}
                      </p>
                    </div>
                  </div>
                </article>
              </section>
            </div>
          </div>
        </aside>

        <Transition name="drawer-right">
          <aside
            v-if="!showInlineFocusSidebar && rightPanelOpen"
            class="scrollbar-hide print-hidden fixed inset-y-4 right-4 z-40 w-[min(360px,calc(100vw-2rem))] overflow-y-auto rounded-[28px] border border-white/60 bg-[#f7f2ea]/95 p-3"
          >
            <div class="mb-3 flex items-center justify-between rounded-[18px] border border-stone-200 bg-white/90 px-4 py-3">
              <p class="text-[11px] font-bold tracking-[0.18em] text-ink">SIDE PANEL</p>
              <button
                type="button"
                class="rounded-full border border-stone-200 px-3 py-1 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
                @click="closeRightPanel"
              >
                CLOSE
              </button>
            </div>

            <div class="grid gap-4 rounded-[22px] p-2" :class="focusSidebarGridClass">
              <div class="grid max-w-[360px] gap-4">
                <section>
                  <MiniCalendar
                    :month-label="monthLabel"
                    :year-label="yearLabel"
                    :days="calendarDays"
                    :selected-key="toKey(selectedDate)"
                    :marked-keys="markedDateKeys"
                    @shift-month="shiftCalendarMonth"
                    @shift-year="shiftCalendarYear"
                    @go-today="selectDate(new Date())"
                    @select="selectDate"
                  />
                </section>

                <section class="rounded-[24px] border border-stone-200 bg-white/88 p-4 shadow-[0_12px_36px_rgba(28,25,23,0.05)]">
                  <div class="grid gap-3">
                    <div class="flex items-center justify-between gap-3">
                      <div class="flex items-center gap-2">
                        <p class="text-[11px] font-bold tracking-[0.22em] text-ink">TASK LABELS</p>
                        <GuideTooltip
                          title="Task Labels"
                          description="번호가 필요한 날만 빠르게 채우고, 필요 없으면 바로 비울 수 있습니다."
                          :visible="isGuideTooltipVisible('task-labels')"
                          @dismiss="dismissGuideTooltip('task-labels')"
                        />
                      </div>
                      <button
                        type="button"
                        class="relative h-8 w-16 shrink-0 rounded-full transition-colors duration-300 ease-out"
                        :class="areTaskLabelsNumbered(planner) ? 'bg-stone-900' : 'bg-stone-300'"
                        @click="areTaskLabelsNumbered(planner) ? clearTaskLabels(planner) : fillTaskLabelsWithNumbers(planner)"
                      >
                        <span
                          class="absolute left-1 top-1 h-6 w-6 transform-gpu rounded-full bg-white shadow-sm transition-transform duration-300 ease-out will-change-transform"
                          :class="areTaskLabelsNumbered(planner) ? 'translate-x-8' : 'translate-x-0'"
                        />
                      </button>
                    </div>

                    <div class="flex items-center justify-between gap-3 border-t border-stone-200 pt-3">
                      <div class="flex items-center gap-2">
                        <p class="text-[11px] font-bold tracking-[0.22em] text-ink">D-DAY 사용</p>
                        <GuideTooltip
                          title="D-Day"
                          description="현재 날짜에 적용된 목표가 있을 때만 본문 D-DAY 표시를 켜고 끌 수 있습니다. 목표는 GOALS 화면에서 표시 기간을 지정하면 자동으로 연결됩니다."
                          :visible="isGuideTooltipVisible('planner-dday')"
                          @dismiss="dismissGuideTooltip('planner-dday')"
                        />
                      </div>
                      <button
                        type="button"
                        class="relative h-8 w-16 shrink-0 rounded-full transition-colors duration-300 ease-out disabled:cursor-not-allowed disabled:opacity-50"
                        :class="plannerGoalToggleOn ? 'bg-stone-900' : 'bg-stone-300'"
                        :disabled="!hasActiveGoalForSelectedDate"
                        @click="updateGoalEnabled(planner, !plannerGoalToggleOn)"
                      >
                        <span
                          class="absolute left-1 top-1 h-6 w-6 transform-gpu rounded-full bg-white shadow-sm transition-transform duration-300 ease-out will-change-transform"
                          :class="plannerGoalToggleOn ? 'translate-x-8' : 'translate-x-0'"
                        />
                      </button>
                    </div>
                  </div>
                </section>

                <section class="rounded-[24px] border border-stone-200 bg-white/88 p-4 shadow-[0_12px_36px_rgba(28,25,23,0.05)]">
                  <div class="flex items-center gap-2">
                    <p class="text-[11px] font-bold tracking-[0.22em] text-ink">TIME TABLE 복사</p>
                    <GuideTooltip
                      title="Time Table Copy"
                      description="규칙적인 생활 패턴이면 특정 날짜의 타임테이블을 다른 날짜에 그대로 복사할 수 있습니다."
                      :visible="isGuideTooltipVisible('timetable-copy')"
                      @dismiss="dismissGuideTooltip('timetable-copy')"
                    />
                  </div>

                  <div class="mt-4 grid gap-3">
                    <label class="grid gap-2">
                      <span class="text-[10px] font-bold tracking-[0.14em] text-stone-500">복사할 날짜</span>
                      <div class="grid gap-2 sm:grid-cols-[minmax(0,1fr)_auto]">
                        <input
                          v-model="timetableCopyForm.sourceDate"
                          type="date"
                          class="h-11 rounded-2xl border border-stone-200 bg-white px-4 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
                        />
                        <button
                          type="button"
                          class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[10px] font-bold tracking-[0.12em] text-stone-600 transition hover:border-stone-400 hover:text-stone-900"
                          @click="useSelectedDateAsTimetableSource"
                        >
                          현재 날짜
                        </button>
                      </div>
                    </label>

                    <label class="grid gap-2">
                      <span class="text-[10px] font-bold tracking-[0.14em] text-stone-500">붙여넣을 날짜</span>
                      <div class="grid gap-2 sm:grid-cols-[minmax(0,1fr)_auto]">
                        <input
                          v-model="timetableCopyForm.targetDate"
                          type="date"
                          class="h-11 rounded-2xl border border-stone-200 bg-white px-4 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
                        />
                        <button
                          type="button"
                          class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[10px] font-bold tracking-[0.12em] text-stone-600 transition hover:border-stone-400 hover:text-stone-900"
                          @click="useSelectedDateAsTimetableTarget"
                        >
                          현재 날짜
                        </button>
                      </div>
                    </label>
                  </div>

                  <button
                    type="button"
                    class="mt-4 w-full rounded-full border border-stone-900 bg-stone-900 px-4 py-3 text-xs font-bold tracking-[0.14em] text-white transition hover:bg-stone-700"
                    @click="copyTimetableBetweenDates"
                  >
                    타임테이블 복사하기
                  </button>

                  <p
                    v-if="timetableCopyMessage"
                    class="mt-3 rounded-2xl border border-stone-200 bg-white px-4 py-3 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600"
                  >
                    {{ timetableCopyMessage }}
                  </p>
                </section>

              </div>

              <div class="grid max-w-[360px] gap-4">
                <section class="rounded-[24px] border border-stone-200 bg-white/82 p-5 shadow-[0_12px_36px_rgba(28,25,23,0.05)]">
                  <article>
                    <p class="text-[11px] font-bold tracking-[0.22em] text-ink">NEXT DAY</p>
                    <div class="mt-5 space-y-3">
                      <p class="text-lg font-semibold tracking-[-0.04em] text-stone-900">
                        <span>{{ secondaryDateDisplay.main }}</span>
                        <span class="ml-1" :class="secondaryDateDisplay.weekdayTone">{{ secondaryDateDisplay.weekday }}</span>
                      </p>
                      <p class="text-[11px] font-semibold tracking-[0.08em] text-stone-600">
                        {{ nextDaySummary }}
                      </p>
                    </div>

                    <div class="mt-5 border-t border-stone-200 pt-5">
                      <p class="text-[11px] font-bold tracking-[0.22em] text-ink">READ NEXT</p>
                      <div class="mt-3 grid gap-3">
                        <p
                          v-for="item in readNextItems"
                          :key="item"
                          class="rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-4 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-700"
                        >
                          {{ item || ' ' }}
                        </p>
                      </div>
                      <button
                        type="button"
                        class="mt-3 w-full rounded-full border border-stone-900 bg-stone-900 px-4 py-3 text-xs font-bold tracking-[0.14em] text-white transition hover:bg-stone-700 disabled:cursor-not-allowed disabled:border-stone-200 disabled:bg-stone-200 disabled:text-stone-500"
                        :disabled="incompleteTasks.length === 0"
                        @click="carryIncompleteTasksToNextDay"
                      >
                        미완료 항목 이월하기
                      </button>
                      <p
                        v-if="carryoverMessage"
                        class="mt-3 rounded-2xl border border-stone-200 bg-white px-4 py-3 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600"
                      >
                        {{ carryoverMessage }}
                      </p>
                    </div>

                    <div class="mt-5 border-t border-stone-200 pt-5">
                      <p class="text-[11px] font-bold tracking-[0.22em] text-ink">PREV SNAPSHOT</p>
                      <div class="mt-3 grid gap-3">
                        <p
                          v-for="item in prevSnapshotItems"
                          :key="item"
                          class="rounded-2xl border border-stone-200 bg-white px-4 py-4 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-700"
                        >
                          {{ item || ' ' }}
                        </p>
                      </div>
                    </div>
                  </article>
                </section>
              </div>
            </div>
          </aside>
        </Transition>
      </section>

      <section
        v-else-if="screenMode === 'planner'"
        class="scrollbar-hide print-hidden overflow-x-auto rounded-[28px] border border-white/60 bg-white/45 p-4 sm:p-6 xl:h-full xl:overflow-y-auto"
      >
        <div class="mx-auto flex gap-6" :style="spreadCanvasStyle">
          <div class="print-target overflow-hidden" :style="spreadPageFrameStyle">
            <PlannerPage
              :style="spreadPageStyle"
              :date-main="selectedDateDisplay.main"
              :date-weekday="selectedDateDisplay.weekday"
              :date-weekday-tone="selectedDateDisplay.weekdayTone"
              :dday="plannerDday"
              :show-dday="showPlannerDday"
              :comment="planner.comment"
              :total-time="formatTotalTimeKorean(planner)"
              :tasks="planner.tasks"
              :memo="planner.memo"
              :hours="hours"
              :timetable="planner.timetable"
              @update:comment="updateComment(planner, $event)"
              @update:task-label="updateTaskLabel(planner, $event)"
              @update:task-title="updateTaskTitle(planner, $event)"
              @toggle:task="toggleTask(planner, $event)"
              @clear:tasks="clearTasks(planner, $event)"
              @update:memo-label="updateMemoLabel(planner, $event)"
              @update:memo="updateMemo(planner, $event)"
              @update:timetable="updateTimetable(planner, $event)"
            />
          </div>
          <div class="print-hidden overflow-hidden" :style="spreadPageFrameStyle">
            <PlannerPage
              :style="spreadPageStyle"
              :date-main="secondaryDateDisplay.main"
              :date-weekday="secondaryDateDisplay.weekday"
              :date-weekday-tone="secondaryDateDisplay.weekdayTone"
              :dday="''"
              :show-dday="false"
              :comment="secondaryPlanner.comment"
              :total-time="formatTotalTimeKorean(secondaryPlanner)"
              :tasks="secondaryPlanner.tasks"
              :memo="secondaryPlanner.memo"
              :hours="hours"
              :timetable="secondaryPlanner.timetable"
              @update:comment="updateComment(secondaryPlanner, $event)"
              @update:task-label="updateTaskLabel(secondaryPlanner, $event)"
              @update:task-title="updateTaskTitle(secondaryPlanner, $event)"
              @toggle:task="toggleTask(secondaryPlanner, $event)"
              @clear:tasks="clearTasks(secondaryPlanner, $event)"
              @update:memo-label="updateMemoLabel(secondaryPlanner, $event)"
              @update:memo="updateMemo(secondaryPlanner, $event)"
              @update:timetable="updateTimetable(secondaryPlanner, $event)"
            />
          </div>
        </div>
      </section>

      <GoalsDashboard
        v-else-if="screenMode === 'goals'"
        class="scrollbar-hide print-hidden xl:h-full xl:overflow-y-auto"
        :goals="filteredGoals"
        :query="goalQuery"
        :form="goalForm"
        :editing-goal-id="editingGoalId"
        :busy="goalBusy"
        :message="goalMessage"
        :selected-date-key="toKey(selectedDate)"
        @update:query="goalQuery = $event"
        @update:form-field="updateGoalFormField"
        @submit:create="submitGoal"
        @start-edit="startGoalEdit"
        @cancel-edit="resetGoalForm(); goalMessage = ''"
        @submit:update="saveGoalEdit"
        @delete-goal="removeGoal"
      />

      <SettingsDashboard
        v-else-if="screenMode === 'settings'"
        class="scrollbar-hide print-hidden xl:h-full xl:overflow-y-auto"
        :user="currentUser"
        :profile-form="profileForm"
        :password-form="passwordForm"
        :profile-busy="profileBusy"
        :password-busy="passwordBusy"
        :profile-message="profileMessage"
        :password-message="passwordMessage"
        :account-delete-form="accountDeleteForm"
        :account-delete-busy="accountDeleteBusy"
        :account-delete-message="accountDeleteMessage"
        :auth-session-info="authSessionInfo"
        :guide-tooltip-reset-message="guideTooltipResetMessage"
        :carryover-check-policy="carryoverCheckPolicy"
        @update:profile-field="updateProfileField"
        @update:password-field="updatePasswordField"
        @update:account-delete-field="updateAccountDeleteField"
        @update:carryover-check-policy="updateCarryoverCheckPolicy"
        @submit:profile="submitProfileForm"
        @submit:password="submitPasswordForm"
        @submit:delete-account="submitDeleteAccount"
        @reset-guide-tooltips="resetGuideTooltips"
      />

      <AdminDashboard
        v-else-if="screenMode === 'admin' && isAdmin"
        class="scrollbar-hide print-hidden xl:h-full xl:overflow-y-auto"
        :summary="adminOverview"
        :users="adminUsers"
        :selected-user-id="adminSelectedUserId"
        :user-detail="adminUserDetail"
        :recent-logins="adminRecentLogins"
        :busy="adminBusy"
        :action-busy-user-id="adminActionUserId"
        :detail-busy="adminDetailBusy"
        :message="adminMessage"
        @select-user="selectAdminUser"
        @toggle-user-status="toggleAdminUserStatus"
        @revoke-user-sessions="revokeAdminSessions"
        @delete-user="removeAdminUser"
      />

      <StatsDashboard
        v-else
        class="scrollbar-hide print-hidden xl:h-full xl:overflow-y-auto"
        :overview-cards="overviewCards"
        :weekly-records="weeklyRecords"
        :recent-records="recentRecords"
        :best-day="bestDay"
        :selected-date-label="`${selectedDateDisplay.main} ${selectedDateDisplay.weekday}`"
        :range-start="normalizedStatsRange.startKey"
        :range-end="normalizedStatsRange.endKey"
        @update:range-start="statsRangeStart = $event"
        @update:range-end="statsRangeEnd = $event"
        @quick-range="applyStatsQuickRange"
      />

      <section v-if="isAuthenticated" class="print-only">
        <div
          v-for="(paper, paperIndex) in printPapers"
          :key="`${printLayout}-${paperIndex}`"
          class="print-paper"
          :class="printLayout === 'single' ? 'print-paper--single' : 'print-paper--double'"
        >
          <div
            v-for="page in paper"
            :key="page.key"
            class="print-sheet-frame"
          >
            <PlannerPage
              :date-main="page.display.main"
              :date-weekday="page.display.weekday"
              :date-weekday-tone="page.display.weekdayTone"
              :dday="page.dday"
              :show-dday="Boolean(page.dday)"
              :comment="page.record.comment"
              :total-time="formatTotalTimeKorean(page.record)"
              :tasks="page.record.tasks"
              :memo="page.record.memo"
              :hours="hours"
              :timetable="page.record.timetable"
            />
          </div>
          <div
            v-if="printLayout === 'double' && paper.length === 1"
            class="print-sheet-frame print-sheet-frame--blank"
          />
        </div>
      </section>
      </div>
    </div>

      <AuthDialog
        :open="authDialogOpen"
        :mode="authMode"
        :form="authForm"
        :busy="authBusy"
        :message="authMessage"
        :show-resend-verification="showVerificationResend"
        @close="closeAuthDialog"
        @submit="submitAuthForm"
        @resend-verification="resendVerificationEmail"
        @switch-mode="authMode = $event; authMessage = ''"
        @update:field="updateAuthField"
      />

    <div
      v-if="printDialogOpen"
      class="print-hidden fixed inset-0 z-50 flex items-center justify-center bg-stone-900/45 px-4 py-6 backdrop-blur-sm"
      @click.self="closePrintDialog"
    >
      <section class="w-full max-w-lg rounded-[30px] border border-white/70 bg-[#f7f2ea] p-5 shadow-[0_24px_80px_rgba(28,25,23,0.2)] sm:p-6">
        <div class="flex items-start justify-between gap-4">
          <div>
            <p class="text-[10px] font-bold uppercase tracking-[0.24em] text-stone-500">Print Planner</p>
            <h2 class="mt-3 text-2xl font-semibold tracking-[-0.05em] text-stone-900">
              출력할 날짜 범위 선택
            </h2>
            <p class="mt-3 text-sm font-semibold leading-6 text-stone-600">
              선택한 기간을 1페이지씩 또는 2페이지씩 묶어서 바로 출력합니다.
            </p>
          </div>
          <button
            type="button"
            class="rounded-full border border-stone-200 bg-white px-3 py-2 text-[10px] font-bold tracking-[0.14em] text-stone-500 transition hover:border-stone-400 hover:text-stone-900"
            @click="closePrintDialog"
          >
            CLOSE
          </button>
        </div>

        <div class="mt-6 grid gap-4 sm:grid-cols-2">
          <label class="flex flex-col gap-2 text-[11px] font-bold tracking-[0.14em] text-stone-500">
            시작일
            <input
              v-model="printRangeStart"
              type="date"
              class="rounded-2xl border border-stone-200 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
            />
          </label>
          <label class="flex flex-col gap-2 text-[11px] font-bold tracking-[0.14em] text-stone-500">
            종료일
            <input
              v-model="printRangeEnd"
              type="date"
              class="rounded-2xl border border-stone-200 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
            />
          </label>
        </div>

        <div class="mt-5 grid gap-2 sm:grid-cols-2">
          <button
            type="button"
            class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
            :class="printRangeLayout === 'single' ? 'bg-stone-900 text-white' : 'border border-stone-200 bg-white text-stone-500'"
            @click="printRangeLayout = 'single'"
          >
            1페이지씩
          </button>
          <button
            type="button"
            class="rounded-2xl px-4 py-3 text-xs font-bold tracking-[0.14em] transition"
            :class="printRangeLayout === 'double' ? 'bg-stone-900 text-white' : 'border border-stone-200 bg-white text-stone-500'"
            @click="printRangeLayout = 'double'"
          >
            2페이지씩
          </button>
        </div>

        <div class="mt-5 rounded-2xl border border-stone-200 bg-white/78 px-4 py-3">
          <p class="text-[11px] font-bold tracking-[0.12em] text-stone-500">출력 예정</p>
          <p class="mt-1 text-sm font-semibold text-stone-900">{{ printPageCountLabel }}</p>
        </div>

        <div class="mt-6 grid gap-2 sm:grid-cols-[1fr_auto]">
          <button
            type="button"
            class="rounded-full border border-stone-900 bg-stone-900 px-5 py-3 text-xs font-bold tracking-[0.16em] text-white transition hover:bg-stone-700"
            @click="printPlannerRange"
          >
            PRINT
          </button>
          <button
            type="button"
            class="rounded-full border border-stone-300 bg-white px-5 py-3 text-xs font-bold tracking-[0.16em] text-stone-700 transition hover:border-stone-500 hover:text-stone-900"
            @click="closePrintDialog"
          >
            취소
          </button>
        </div>
      </section>
    </div>

    <div
      v-if="carryoverCheckPrompt"
      class="fixed inset-0 z-50 flex items-center justify-center bg-stone-900/45 px-4 py-6 backdrop-blur-sm"
    >
      <section class="w-full max-w-md rounded-[28px] border border-white/70 bg-[#f7f2ea] p-5 shadow-[0_24px_80px_rgba(28,25,23,0.2)]">
        <p class="text-[10px] font-bold uppercase tracking-[0.24em] text-stone-500">Carryover Task</p>
        <h2 class="mt-3 text-2xl font-semibold tracking-[-0.04em] text-stone-900">
          이월된 할 일을 완료할까요?
        </h2>
        <p class="mt-3 text-sm font-semibold leading-6 text-stone-600">
          "{{ carryoverCheckPrompt.taskTitle }}" 항목은 {{ createDateLabel(carryoverCheckPrompt.originKey) }}부터 이월되었습니다.
          이전 날짜의 같은 항목도 함께 완료 처리할 수 있습니다.
        </p>

        <div class="mt-5 grid gap-2">
          <button
            type="button"
            class="rounded-full border border-stone-900 bg-stone-900 px-5 py-3 text-xs font-bold tracking-[0.16em] text-white transition hover:bg-stone-700"
            @click="answerCarryoverCheckPrompt('all')"
          >
            이전 날짜까지 모두 체크
          </button>
          <button
            type="button"
            class="rounded-full border border-stone-300 bg-white px-5 py-3 text-xs font-bold tracking-[0.16em] text-stone-700 transition hover:border-stone-500 hover:text-stone-900"
            @click="answerCarryoverCheckPrompt('current')"
          >
            오늘만 체크
          </button>
        </div>

        <div class="mt-4 grid gap-2 border-t border-stone-200 pt-4">
          <button
            type="button"
            class="rounded-full px-4 py-2 text-[10px] font-bold tracking-[0.14em] text-stone-500 transition hover:text-stone-900"
            @click="answerCarryoverCheckPrompt('all', 'all')"
          >
            앞으로 항상 모두 체크
          </button>
          <button
            type="button"
            class="rounded-full px-4 py-2 text-[10px] font-bold tracking-[0.14em] text-stone-500 transition hover:text-stone-900"
            @click="answerCarryoverCheckPrompt('current', 'current')"
          >
            앞으로 항상 오늘만 체크
          </button>
          <button
            type="button"
            class="rounded-full px-4 py-2 text-[10px] font-bold tracking-[0.14em] text-stone-400 transition hover:text-stone-900"
            @click="closeCarryoverCheckPrompt"
          >
            취소
          </button>
        </div>
      </section>
    </div>

    <transition
      enter-active-class="transition duration-200 ease-out"
      enter-from-class="translate-y-2 opacity-0"
      enter-to-class="translate-y-0 opacity-100"
      leave-active-class="transition duration-200 ease-in"
      leave-from-class="translate-y-0 opacity-100"
      leave-to-class="translate-y-2 opacity-0"
    >
      <div
        v-if="isAuthenticated && syncToastVisible"
        class="pointer-events-none fixed bottom-5 right-5 z-40 max-w-[240px] rounded-full border border-stone-200/70 bg-white/80 px-3 py-2 shadow-[0_10px_24px_rgba(28,25,23,0.08)] backdrop-blur"
      >
        <p
          class="text-[11px] font-semibold tracking-[0.04em]"
          :class="syncStatus === 'error' ? 'text-red-500' : syncStatus === 'syncing' ? 'text-blue-500' : 'text-stone-500'"
        >
          {{ syncMessage }}
        </p>
      </div>
    </transition>
  </main>
</template>

<style>
.scrollbar-hide {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.scrollbar-hide::-webkit-scrollbar {
  display: none;
}
</style>
